src/Controller/GraficaController.php line 60

Open in your IDE?
  1. <?php
  2. /*
  3.  * Autor:       Carlos Iglesias
  4.  * Description: Grafica Controller to handle routes and views
  5.  * Date:        15/September/2021
  6.  */
  7. namespace App\Controller;
  8. use App\Service\GraficaService;
  9. use App\Service\ShipmentService;
  10. use App\Service\ChartGoalService;
  11. use App\Service\SolicitudService;
  12. use App\Service\ChartHistoryService;
  13. use App\Service\FidelizacionService;
  14. use DateInterval;
  15. use DatePeriod;
  16. use Symfony\Component\Serializer\Serializer;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  22. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  23. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  24. use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
  25. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  26. set_time_limit(0);
  27. class GraficaController extends AbstractController
  28. {
  29.     /**
  30.      * @Route("/grafica", name="_grafica")
  31.      */
  32.     public function grafica(Request $requestGraficaService $graficaServiceChartHistoryService $chartHistoryService)
  33.     {   
  34.         $meses = [
  35.             'Enero',
  36.             'Febrero',
  37.             'Marzo',
  38.             'Abril',
  39.             'Mayo',
  40.             'Junio',
  41.             'Julio',
  42.             'Agosto',
  43.             'Septiembre',
  44.             'Octubre',
  45.             'Noviembre',
  46.             'Diciembre',
  47.         ];
  48.         return $this->render('grafica.html.twig',[
  49.             "meses" => json_encode($meses),
  50.         ]);
  51.     }
  52.     /**
  53.      * @Route("/graficas", name="_graficas_json")
  54.      */
  55.     public function getGraficas(Request $requestGraficaService $graficaServiceChartHistoryService $chartHistoryServiceSolicitudService $solicitudServiceFidelizacionService $fidelizacionServiceChartGoalService $chartGoalService) {
  56.         $year $request->query->get('year') ?? '2023';
  57.         $fidelizacion $this->getGraficaFidelizacion($fidelizacionService$chartHistoryService);
  58.         $solicitudes $this->getGraficaSolicitudes($year$solicitudService$graficaService$chartHistoryService);
  59.         $datosDeUsoArray $this->getGraficaRempateOEmpate($year$graficaService$chartHistoryServicetrue);
  60.         $porcentajesEmpatesDelivery $this->getGraficaRempateOEmpate($year$graficaService$chartHistoryServicefalse);
  61.         $empateGlobal $this->graficaEmpateGlobal($year$datosDeUsoArray$porcentajesEmpatesDelivery$chartHistoryService$solicitudes);
  62.         
  63.         $porcentajesEmpate = [];
  64.         $porcentajesEmpatesDeliveryArray = [];
  65.         $porcentajesEmpateGlobal = [];
  66.         $porcentajesSolicitudes = [];
  67.         $porcentajesFidelizacion = [];
  68.         $metasEmpate = [];
  69.         $metasEmpateDelivery = [];
  70.         $metasEmpateGlobal = [];
  71.         $metasSolicitudes = [];
  72.         $metasFidelizacion = [];
  73.         for ($i=0$i 12$i++) {
  74.             
  75.             $date = new \DateTime("01-01-".date($year));
  76.             $date->modify("+"$i ." month");
  77.             $porcentajesEmpate['data'][] = $this->generateDataChart($date'empate'$chartHistoryService);
  78.             $porcentajesEmpatesDeliveryArray['data'][] = $this->generateDataChart($date'empate_delivery'$chartHistoryService);
  79.             $porcentajesEmpateGlobal['data'][] = $this->generateDataChart($date'empate_global'$chartHistoryService);
  80.             $porcentajesSolicitudes['data'][] = $this->generateDataChart($date'solicitudes'$chartHistoryService);
  81.             $porcentajesFidelizacion['data'][] = $this->generateDataChart($date'fidelizacion'$chartHistoryService);
  82.             
  83.             $metasEmpate['data'][] = $this->generateDataChartGoal($date'empate'$chartGoalService);
  84.             $metasEmpateDelivery['data'][] = $this->generateDataChartGoal($date'empate_delivery'$chartGoalService);
  85.             $metasEmpateGlobal['data'][] = $this->generateDataChartGoal($date'empate_global'$chartGoalService);
  86.             $metasSolicitudes['data'][] = $this->generateDataChartGoal($date'solicitudes'$chartGoalService);
  87.             $metasFidelizacion['data'][] = $this->generateDataChartGoal($date'fidelizacion'$chartGoalService);
  88.         }
  89.         
  90.         return $this->json([
  91.             "porcentajes" => $porcentajesEmpate,
  92.             "porcentajesEmpatesDelivery" => $porcentajesEmpatesDeliveryArray,
  93.             "porcentajesGlobales" => $porcentajesEmpateGlobal,
  94.             "solicitudes" => $porcentajesSolicitudes,
  95.             'fidelizacion' => $porcentajesFidelizacion,
  96.             'metasEmpate' => $metasEmpate,
  97.             'metasEmpateDelivery' => $metasEmpateDelivery,
  98.             'metasEmpateGlobal' => $metasEmpateGlobal,
  99.             'metasSolicitudes' => $metasSolicitudes,
  100.             'metasFidelizacion' => $metasFidelizacion,
  101.         ]);
  102.     }
  103.     public function generateDataChart($date$typeChartHistoryService $chartHistoryService
  104.     {  
  105.         $data $chartHistoryService->getChartHistoryByDate($date$type);
  106.         if (empty($data)) {
  107.             $dataChart =  0.0;
  108.         } else {
  109.             $dataChart $data->getPercent();
  110.         }
  111.         return $dataChart;
  112.     }
  113.     public function generateDataChartGoal($date$typeChartGoalService $chartGoalService
  114.     {  
  115.         $data $chartGoalService->getChartGoalByDate($date$type);
  116.         if (empty($data)) {
  117.             $dataChart =  0.0;
  118.         } else {
  119.             $dataChart $data->getPercent();
  120.         }
  121.         return $dataChart;
  122.     }
  123.     
  124.     public function getGraficaRempateOEmpate($yearGraficaService $graficaServiceChartHistoryService $chartHistoryServicebool $isEmpate)
  125.     {
  126.         $data = [];
  127.         for ($i=0$i 12$i++) { 
  128.             $month $i+1;
  129.             $startDate date_create("$year-$month-01");
  130.             $endDate date_create("$year-$month-01")->modify('+7 days')->modify("+1 month");
  131.             $reempatesOrEmpates $isEmpate 
  132.                 $graficaService->getEmpatesByRangeDates($startDate$endDate) : 
  133.                 $graficaService->getReempatesByRangeDates($startDate$endDate);
  134.             
  135.             $shipments $graficaService->getShipmentsByMonthAndYear($i+1date("Y",  strtotime("$year-01-01")));
  136.             
  137.             $porcentaje = ($shipments != && $reempatesOrEmpates != 0) ? ($reempatesOrEmpates/$shipments) : 0;
  138.             $total = (float) number_format($porcentaje*1003'.'',');
  139.             $data[] = $total;
  140.             $date = new \DateTime("01-01-".date("Y",  strtotime("$year-01-01")));
  141.             $date->modify("+"$i ." month");
  142.             $isEmpate $chartHistoryService->createChartHistory($date$total'empate') :  $chartHistoryService->createChartHistory($date$total'empate_delivery');
  143.         }
  144.         return $data;
  145.     }
  146.     public function getGraficaSolicitudes($yearSolicitudService $solicitudServiceGraficaService $graficaServiceChartHistoryService $chartHistoryService)
  147.     {
  148.         for ($i=0$i 12$i++) { 
  149.             $solicitudesCerradas $solicitudService->getSolicitudesCerradas($i+1date("Y"strtotime("$year-01-01")));
  150.             
  151.             $shipments $graficaService->getShipmentsByMonthAndYear($i+1date("Y"strtotime("$year-01-01")));
  152.             $porcentaje = ($shipments != && $solicitudesCerradas != 0) ? ($solicitudesCerradas/$shipments) : 0;
  153.             $total = (float) number_format($porcentaje*1003'.'',');
  154.             $data[] = $total;
  155.             $date = new \DateTime("01-01-".date("Y"strtotime("$year-01-01")));
  156.             $date->modify("+"$i ." month");
  157.             $chartHistoryService->createChartHistory($date$total'solicitudes');
  158.         }
  159.         return $data;
  160.     }
  161.     public function getGraficaFidelizacion(FidelizacionService $fidelizacionServiceChartHistoryService $chartHistoryService)
  162.     {
  163.         for ($i=0$i 12$i++) { 
  164.             
  165.             $fidelizados $fidelizacionService->getFidelizacionByFidelizado($i+1);
  166.             $notFidelizados $fidelizacionService->getFidelizacionNotFidelizado($i+1);
  167.             $total $fidelizados $notFidelizados;
  168.             $porcentaje = ($total != && $fidelizados != 0) ? ($fidelizados/$total) : 0;
  169.             $total = (float) number_format($porcentaje*1003'.'',');
  170.             $data[] = $total;
  171.             $date = new \DateTime("01-01-".date("Y"));
  172.             $date->modify("+"$i ." month");
  173.             $chartHistoryService->createChartHistory($date$total'fidelizacion');
  174.         }
  175.         return $data;
  176.     }
  177.     public function graficaEmpateGlobal($year$empatesArray$empatesDeliveryArrayChartHistoryService $chartHistoryService$solicitudes) {
  178.         $empatesPorcentajes $empatesArray;
  179.         $empatesDeliveryPorcentajes $empatesDeliveryArray;
  180.         $countPorcentajes count($empatesPorcentajes);
  181.         $porcentajesGlobal = array();
  182.         for ($i=0$i $countPorcentajes$i++) { 
  183.             array_push($porcentajesGlobalnumber_format((($solicitudes[$i]+$empatesPorcentajes[$i]+$empatesDeliveryPorcentajes[$i])/3), 3'.'','));
  184.             $date = new \DateTime("01-01-".date("Y"strtotime("$year-01-01")));
  185.             $date->modify("+"$i ." month");
  186.             $chartHistoryService->createChartHistory($date$porcentajesGlobal[$i], 'empate_global');
  187.         }
  188.         $arrayFinal[0] = [
  189.             "name" => 'Empate Global',
  190.             "data" => $porcentajesGlobal
  191.         ];
  192.         $porcentajesJson json_encode($arrayFinal);
  193.         return $porcentajesJson;
  194.     }
  195.      /**
  196.      * @Route("/dashboard", name="_dashboard")
  197.      */
  198.     public function graficaModalidad(Request $requestGraficaService $graficaServiceShipmentService $shipmentService)
  199.     {
  200.         $fechaActual   = new \DateTime();        
  201.         $fechaClon = clone $fechaActual;
  202.         $fechaHace1Mes date_modify($fechaClon,'-45day');
  203.         $countTotal $graficaService->countTotalShipments($fechaHace1Mes$fechaActual);
  204.         $subTypes $shipmentService->getAllSubTypes($fechaHace1Mes$fechaActual);
  205.         $countPerSubType = [];
  206.         $countPerRegion = [];
  207.         $subTypesArr = [];
  208.         $regionesArr = [];
  209.         $cantidadArr = [];
  210.         $ciudadArr = [];
  211.         $countRegion 0;
  212.         $graficaBarrasInfo $graficaService->getDestinationsCount($fechaHace1Mes$fechaActual);
  213.         for($j 0$j<count($graficaBarrasInfo); $j++){
  214.             $cantidadArr[$j] = $graficaBarrasInfo[$j][1];
  215.             $ciudadArr[$j] = $graficaBarrasInfo[$j]['name'];
  216.             // $countPerSubType[$j] = (float)number_format($porcentaje, 3, '.', ',');
  217.         }
  218.         for($i 0$i<count($subTypes); $i++){
  219.             $subTypesArr[$i] = $subTypes[$i]['subType'];
  220.             $count $graficaService->countTotalShipments($fechaHace1Mes$fechaActual$subTypes[$i]['subType']);
  221.             $porcentaje = ($count/$countTotal)*100;
  222.             $countPerSubType[$i] = (float)number_format($porcentaje3'.'',');
  223.         }
  224.         $graficaRegionInfo $graficaService->getShipmentsPorRegion($fechaHace1Mes$fechaActual);
  225.         for($i=0$i<count($graficaRegionInfo); $i++){
  226.             $porcentaje = ($graficaRegionInfo[$i]['cantidad']/$countTotal)*100;
  227.             $countPerRegion[$i] = (float)number_format($porcentaje3'.'',');
  228.             $countRegion $countRegion $graficaRegionInfo[$i]['cantidad'];
  229.             $regionesArr[$i] = $graficaRegionInfo[$i]['region'];
  230.         }
  231.         $porcentaje = (($countTotal-$countRegion)/$countTotal)*100;
  232.         $countPerRegion[$i] = (float)number_format($porcentaje3'.'',');
  233.         $regionesArr[$i] = 'Sin región';
  234.         $regionesArrJson json_encode($regionesArr);
  235.         $porcentajeRegiones json_encode(array_values($countPerRegion));
  236.         $subTypesArrJson json_encode($subTypesArr);
  237.         $porcentajesJson json_encode(array_values($countPerSubType));
  238.         
  239.         $cantidadJson json_encode(array_values($cantidadArr));
  240.         $ciudadesJson json_encode(array_values($ciudadArr));
  241.         return $this->render('/graficas/graficaFiltros.html.twig',[
  242.             "porcentajes" => $porcentajesJson,
  243.             "subTypesJson" => $subTypesArrJson,
  244.             'subTypes' => $subTypes,
  245.             'dateToday' => $fechaActual->format('d-m-Y'),
  246.             'dateHace1Mes' => $fechaHace1Mes->format('d-m-Y'),
  247.             'cantidadJson' => $cantidadJson,
  248.             'ciudadesJson' => $ciudadesJson,
  249.             'regionesJson' => $regionesArrJson,
  250.             'porcentajeRegiones' => $porcentajeRegiones
  251.         ]);
  252.     }
  253.      /**
  254.      * @Route("/filtrarGrafica", name="_filtrar_grafica")
  255.      */
  256.     public function filtrarGrafica(Request $requestGraficaService $graficaServiceShipmentService $shipmentService){
  257.         $subTypesCall $request->query->get("subTypes");
  258.         $dateInicio $request->query->get("dateInicio");
  259.         $dateFinal $request->query->get("dateFinal");
  260.         $indexNameSelected $request->query->get("indexNameSelected");
  261.         $subTypesArr = [];
  262.         for($j=0;$j<count($subTypesCall); $j++){
  263.             $subTypesArr[$j] = $subTypesCall[$j]['name'];
  264.         }
  265.         $dateInicio = new \DateTime($dateInicio);
  266.         $dateFinal = new \DateTime($dateFinal);
  267.         $countTotal $graficaService->countTotalShipments($dateInicio$dateFinal);
  268.         // $subTypes = $shipmentService->getAllSubTypes($dateInicio, $dateFinal);
  269.         $countPerSubType = [];
  270.         for($i 0$i<count($subTypesArr); $i++){
  271.             $count $graficaService->countTotalShipments($dateInicio$dateFinal$subTypesArr[$i]);
  272.             if($count == || $countTotal == 0){
  273.                 $porcentaje 0;
  274.             }else{
  275.                 $porcentaje = ($count/$countTotal)*100;
  276.             }
  277.             $countPerSubType[$i] = (float)number_format($porcentaje3'.'',');
  278.         }
  279.         $subTypesArrJson json_encode($subTypesArr);
  280.         $porcentajesJson json_encode(array_values($countPerSubType));
  281.         $countRegion 0;
  282.         $graficaRegionInfo $graficaService->getShipmentsPorRegion($dateInicio$dateFinal$subTypesArr);
  283.         for($i=0$i<count($graficaRegionInfo); $i++){
  284.             $porcentaje = ($graficaRegionInfo[$i]['cantidad']/$countTotal)*100;
  285.             $countPerRegion[$i] = (float)number_format($porcentaje3'.'',');
  286.             $countRegion $countRegion $graficaRegionInfo[$i]['cantidad'];
  287.             $regionesArr[$i] = $graficaRegionInfo[$i]['region'];
  288.         }
  289.         $porcentaje = (($countTotal-$countRegion)/$countTotal)*100;
  290.         $countPerRegion[$i] = (float)number_format($porcentaje3'.'',');
  291.         $regionesArr[$i] = 'Sin región';
  292.         $regionesArrJson json_encode($regionesArr);
  293.         $porcentajeRegiones json_encode(array_values($countPerRegion));
  294.         if($indexNameSelected != '' && $indexNameSelected != null){
  295.             if($indexNameSelected == 'Sin región'){
  296.                 $region 'Sin regíon';
  297.             }else{
  298.                 $region $graficaService->getRegionByName($indexNameSelected);
  299.             }
  300.         }else{
  301.             $region null;
  302.         }
  303.         $graficaBarrasInfo $graficaService->getDestinationsCount($dateInicio$dateFinal$subTypesArr$region);
  304.         if(empty($graficaBarrasInfo)){
  305.             return $this->json(["data" => 'Tú búsqueda no arrojo ningún resultado.']);
  306.         }
  307.         for($j 0$j<count($graficaBarrasInfo); $j++){
  308.             $cantidadArr[$j] = $graficaBarrasInfo[$j][1];
  309.             $ciudadArr[$j] = $graficaBarrasInfo[$j]['name'];
  310.             // $countPerSubType[$j] = (float)number_format($porcentaje, 3, '.', ',');
  311.         }
  312.         $response[0] = $subTypesArrJson;
  313.         $response[1] = $porcentajesJson;
  314.         $response[2] = $regionesArrJson;
  315.         $response[3] = $porcentajeRegiones;
  316.         $response[4] = $cantidadArr;
  317.         $response[5] = $ciudadArr;
  318.         return $this->json(["data" => $response]);
  319.     }
  320.     /**
  321.      * @Route("/getRoutesByState", name="get_route_by_state")
  322.      */
  323.     public function getRoutesByState(Request $requestGraficaService $graficaServiceShipmentService $shipmentService)
  324.     {
  325.         $stateName $request->query->get("stateName");
  326.         $subTypes $request->query->get("subTypes");
  327.         $region $request->query->get("region");
  328.         $dateInicio $request->query->get("dateInicio");
  329.         $dateFinal $request->query->get("dateFinal");
  330.         $subTypesArr = [];
  331.         $returnArr = [];
  332.         if ($subTypes == null) {
  333.             return $this->json(['error' => 'No se encontraron rutas'])->setStatusCode(400);
  334.         }
  335.         for($j=0;$j<count($subTypes); $j++){
  336.             $subTypesArr[$j] = $subTypes[$j]['name'];
  337.         }
  338.         $dateInicio = new \DateTime($dateInicio);
  339.         $dateFinal = new \DateTime($dateFinal);
  340.         $state $graficaService->getStateByName($stateName);
  341.         if($region == 'Sin región'){
  342.             $region 'Sin regíon';
  343.         }else{
  344.             $region $graficaService->getRegionByName($region);
  345.         }
  346.         $shipments $shipmentService->getAllRoutesByState($dateInicio$dateFinal$state$subTypesArr$region);
  347.         foreach($shipments as $shipment){
  348.             $returnArr[] = [
  349.                 'idExample' => $shipment['id'],
  350.                 'destination' => $shipment['finalDestination'],
  351.                 'quantity' => $shipment['quantity']
  352.             ];
  353.         }
  354.         return $this->json(["data" => $returnArr]);
  355.     }
  356.      /**
  357.      * @Route("/metas_json", name="_graficas_metas_json")
  358.      */
  359.     public function metas(Request $requestChartGoalService $chartGoalService)
  360.     {   
  361.         $year $request->query->get("year") ?? '2022';
  362.         $type $request->query->get("type") ?? 'empate';
  363.         $chartValues = ['data' => []];
  364.         for ($i=0$i 12$i++) { 
  365.             $date = new \DateTime("01-01-".date($year));
  366.             $date->modify("+"$i ." month");
  367.             $chart $chartGoalService->getChartGoalByDate($date$type);
  368.             
  369.             if (empty($chart)) {
  370.                 array_push($chartValues['data'], 0.0);
  371.             } else {
  372.                 array_push($chartValues['data'], $chart->getPercent());
  373.             }
  374.         }
  375.         return $this->json(['metas' => $chartValues]);
  376.     }
  377.     /**
  378.      * @Route("/guardar_metas", name="_guardar_metas")
  379.      */
  380.     public function guardarMetas(Request $requestChartGoalService $chartGoalService)
  381.     {
  382.         $values $request->get("values");
  383.         $type $request->get("type") ?? 'empate';
  384.         $year $request->get("year") ?? '2022';
  385.         $total count($values);
  386.         $chartValues = ['data' => []];
  387.         
  388.         for ($i=0$i $total$i++) { 
  389.             $date = new \DateTime("01-01-".date($year));
  390.             $date->modify("+"$i ." month");
  391.             $chartGoalService->createChartGoal($date$values[$i], $type);
  392.             $chart $chartGoalService->getChartGoalByDate($date$type);
  393.             if (empty($chart)) {
  394.                 array_push($chartValues['data'], 0.0);
  395.             } else {
  396.                 array_push($chartValues['data'], $chart->getPercent());
  397.             }
  398.         }
  399.         return $this->json(['metas' => $chartValues]);
  400.     }
  401. }