src/Controller/MainController.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use App\Service\Utils;
  12. use App\Entity\Products;
  13. use App\Entity\Requests;
  14. use App\Entity\Reviews;
  15. use App\Entity\ReviewData;
  16. class MainController extends AbstractController
  17. {
  18.     private $numMonthPrev;
  19.     public function __construct(){
  20.         $this->numMonthPrev 5;
  21.     }
  22.     /**
  23.      * @Route("/", name="main_page", methods={"GET"})
  24.      * 
  25.      */
  26.     public function mainPage(Request $requestManagerRegistry $doctrineUtils $utils): Response
  27.     {
  28.         $user $this->getUser();
  29.         if (!$user) {
  30.             return $this->redirectToRoute('app_login');
  31.         }
  32.         return $this->redirectToRoute('product_detail', array('id' => 1));
  33.         $utils->addLog($doctrine$user"""view-panel");
  34.         $em $doctrine->getManager();
  35.         $productsRepository $em->getRepository(Products::class); 
  36.         $requestsRepository $em->getRepository(Requests::class);
  37.         $reviewsRepository $em->getRepository(Reviews::class);
  38.         $products $productsRepository->findBy(array("status"=>1));
  39.         $listProducts = array();
  40.         if($products && count($products) > 0){
  41.             
  42.             foreach($products as $product){
  43.                 $global $reviewsRepository->getReviewsInfo($product);
  44.                 $sentimentGlobal 0;
  45.                 if($global){
  46.                     if($global[0]["positive"] > $global[0]["neutral"] && $global[0]["positive"] > $global[0]["negative"]){
  47.                         $sentimentGlobal 1;
  48.                     }else if($global[0]["negative"] > $global[0]["neutral"] && $global[0]["negative"] > $global[0]["positive"]){
  49.                         $sentimentGlobal 2;
  50.                     }
  51.                 }
  52.                 $total $reviewsRepository->getReviewsTotal($product);
  53.                 if($total){
  54.                     $total $total[0]["total"];
  55.                 }else{
  56.                     $total 0;
  57.                 }
  58.                 $requests $requestsRepository->getRequestByProduct($product);
  59.                 $channelsInfo = array();
  60.                 if($requests){
  61.                     foreach($requests as $request){
  62.                         $channel $reviewsRepository->getReviewsInfo($product$request);
  63.                         $alias = ($request->getType() == 0)? "walmart" "amazon";
  64.                         $quantity 0;
  65.                         $sentiment 0;
  66.                         if($channel){
  67.                             if($channel[0]["positive"] > $channel[0]["neutral"] && $channel[0]["positive"] > $channel[0]["negative"]){
  68.                                 $sentiment 1;
  69.                             }else if($channel[0]["negative"] > $channel[0]["neutral"] && $channel[0]["negative"] > $channel[0]["positive"]){
  70.                                 $sentiment 2;
  71.                             }
  72.                         }
  73.                         $quantity $reviewsRepository->getReviewsTotal($product$request);
  74.                         if($quantity){
  75.                             $quantity $quantity[0]["total"];
  76.                         }else{
  77.                             $total 0;
  78.                         }
  79.                         $channelsInfo[$alias] = array(
  80.                             "quantity" => number_format($quantity 0',''.'),
  81.                             "sentiment" => $sentiment     
  82.                         );
  83.                     }
  84.                 }
  85.                 $aux = array(
  86.                     "info" => $product,
  87.                     "data" => array(
  88.                         "channels" => $channelsInfo,
  89.                         "global" => array(
  90.                             "quantity" => number_format($total0',''.'),
  91.                             "sentiment" => $sentimentGlobal,                            
  92.                         )
  93.                     )  
  94.                 );
  95.                 $listProducts[] = $aux;
  96.             }
  97.             
  98.         }
  99.         return $this->render('panel.html.twig', array(
  100.             "listProducts" => $listProducts
  101.         ));
  102.     }
  103.     /**
  104.      * @Route("/logged", name="main_page_logged", methods={"GET"})
  105.      * 
  106.      */
  107.     public function mainPageLogged(Request $requestManagerRegistry $doctrineUtils $utils): Response
  108.     {
  109.         $user $this->getUser();
  110.         if (!$user) {
  111.             return $this->redirectToRoute('app_login');
  112.         }
  113.         $utils->addLog($doctrine$user"""login");
  114.         return $this->redirectToRoute('main_page');
  115.     }
  116.     /**
  117.      * @Route("/product/{id}", name="product_detail", methods={"GET","POST"})
  118.      * 
  119.      */
  120.     public function productDetail(Request $requestManagerRegistry $doctrineUtils $utils$id): Response
  121.     {
  122.         $user $this->getUser();
  123.         if (!$user) {
  124.             return $this->redirectToRoute('app_login');
  125.         }
  126.         $utils->addLog($doctrine$userjson_encode(array("id"=>$id"channel"=>$request->get("channel"))), "view-detail");
  127.         $em $doctrine->getManager();
  128.         $numMonthPrev $this->numMonthPrev;
  129.         $now = new \DateTime('now');
  130.         $now->setTimezone(new \DateTimeZone('Europe/Madrid'));
  131.         $productsRepository $em->getRepository(Products::class); 
  132.         $requestsRepository $em->getRepository(Requests::class);
  133.         $reviewsRepository $em->getRepository(Reviews::class);
  134.         $reviewDataRepository $em->getRepository(ReviewData::class);
  135.         $product $productsRepository->find($id);
  136.         if($product){
  137.             $filter_channel = ($request->get("channel") === || $request->get("channel") === || $request->get("channel") === "1" || $request->get("channel") === "0")? $request->get("channel") : null;
  138.             $total $reviewsRepository->getReviewsTotal($productnull$filter_channel);
  139.             if($total){
  140.                 $total $total[0]["total"];
  141.             }else{
  142.                 $total 0;
  143.             }
  144.             $totalTemporal = [];
  145.             $ratingInfoTemporal = array(
  146.                 "average" => [],
  147.                 "bayes" => []
  148.             );
  149.             $labelPrev = array();
  150.             $dateStartPrev $now->format("Y-m-01 00:00:00");
  151.             $dateEndPrev $now->format("Y-m-t 23:59:59");
  152.             $dateStart $dateStartPrev;
  153.             $dateEnd $dateEndPrev;
  154.             for($i $numMonthPrev$i >= 0$i--){
  155.                 $dateStartPrev date("Y-m-01 00:00:00"strtotime("-".$i." months",strtotime($dateStart)));
  156.                 $dateEndPrev date("Y-m-t 23:59:59"strtotime("-".$i." months",strtotime($dateEnd)));
  157.                 $labelPrev[] = date("m-Y",strtotime($dateStartPrev));
  158.                 $accTotal $reviewsRepository->getReviewsTotal($productnull$filter_channel$dateStartPrev$dateEndPrev);
  159.                 if($accTotal){
  160.                     $accTotal $accTotal[0]["total"];
  161.                 }else{
  162.                     $accTotal 0;
  163.                 }
  164.                 $totalTemporal[] = $accTotal;
  165.                 $rating $reviewsRepository->getReviewsRating($productnull$filter_channel$dateStartPrev$dateEndPrev);
  166.                 if($rating){
  167.                     $ratingInfoTemporal["average"][] = ($rating[0]["rating"])? $rating[0]["rating"] : 0;
  168.                     $ratingInfoTemporal["bayes"][] = ($rating[0]["bayes"])? $rating[0]["bayes"] : 0;
  169.                 }
  170.             }
  171.             $global $reviewsRepository->getReviewsInfo($productnull$filter_channel);
  172.             $sentiments = array(
  173.                 "positive" => 0,
  174.                 "neutral" => 0,
  175.                 "negative" => 0
  176.             );
  177.             if($global){
  178.                 $sentiments["positive"] = str_replace(".",",",round($global[0]["positive"],2));
  179.                 $sentiments["neutral"] = str_replace(".",",",round($global[0]["neutral"],2));
  180.                 $sentiments["negative"] = str_replace(".",",",round($global[0]["negative"],2));
  181.             }
  182.             $rating $reviewsRepository->getReviewsRating($productnull$filter_channel);
  183.             $ratingInfo = array(
  184.                 "average" => 0,
  185.                 "bayes" => 0
  186.             );
  187.             if($rating){
  188.                 $ratingInfo["average"] = str_replace(".",",",round($rating[0]["rating"],2));
  189.                 $ratingInfo["bayes"] = str_replace(".",",",round($rating[0]["bayes"],2));
  190.             }
  191.             $requests $requestsRepository->getRequestByProduct($product$filter_channel);
  192.             $channelsInfo = array();
  193.             $types = array();
  194.             if($requests){
  195.                 foreach($requests as $requestProduct){
  196.                     $channel $reviewsRepository->getReviewsInfo($product$requestProduct);
  197.                     $alias = ($requestProduct->getType() == 0)? "walmart" "amazon";
  198.                     $types[] = $requestProduct->getType();
  199.                     $quantity 0;
  200.                     $sentiment 0;
  201.                     if($channel){
  202.                         if($channel[0]["positive"] > $channel[0]["neutral"] && $channel[0]["positive"] > $channel[0]["negative"]){
  203.                             $sentiment 1;
  204.                         }else if($channel[0]["negative"] > $channel[0]["neutral"] && $channel[0]["negative"] > $channel[0]["positive"]){
  205.                             $sentiment 2;
  206.                         }
  207.                     }
  208.                     $quantity $reviewsRepository->getReviewsTotal($product$requestProduct);
  209.                     if($quantity){
  210.                         $quantity $quantity[0]["total"];
  211.                     }else{
  212.                         $total 0;
  213.                     }
  214.                     $channelsInfo[$alias] = array(
  215.                         "quantity" => number_format($quantity 0',''.'),
  216.                         "sentiment" => $sentiment     
  217.                     );
  218.                 }
  219.             }
  220.             $temporal = array(
  221.                 "labels" => array()
  222.             );
  223.     
  224.             $typeTemporal "months";
  225.             // if($start_date != "" && $start_date == $end_date){
  226.             //     $type = "hours";
  227.             // }else{
  228.             //     if($start_date != ""){
  229.             //         if($end_date == ""){
  230.             //             $end_date = date("Y-m-d");
  231.             //         }
  232.             //         $diff = date_diff(new \DateTime($start_date." 00:00:00"), new \DateTime($end_date." 23:59:59"));
  233.             //         if($diff->days > 61){
  234.             //             $type = "months";
  235.             //         }
  236.             //     }
  237.             // }
  238.             $temporalData $reviewsRepository->getReviewsTemporal($product$filter_channel);
  239.             foreach($temporalData as $data){
  240.                 if($typeTemporal == "months"$date str_pad($data["month"], 2'0'STR_PAD_LEFT)."/".$data["year"];
  241.                 if(!in_array($date,$temporal["labels"])){
  242.                     $temporal["labels"][] = $date;
  243.                     foreach($types as $type){
  244.                         if(!isset($temporal["data_".$type][$date])) $temporal["data_".$type][$date] = 0;
  245.                     }
  246.                 }
  247.                 $temporal["data_".$data["type"]][$date] = $data["qtt"];
  248.             }
  249.             foreach($temporal as $key => $t){
  250.                 $temporal[$key] = array_values($temporal[$key]);
  251.             }
  252.             $temporalRating = array(
  253.                 "labels" => array()
  254.             );
  255.             $temporalRatingData $reviewsRepository->getReviewsTemporalRating($product$filter_channel);
  256.             $ratingsType = array(1,2,3,4,5);
  257.             foreach($temporalRatingData as $data){
  258.                 if($typeTemporal == "months"$date str_pad($data["month"], 2'0'STR_PAD_LEFT)."/".$data["year"];
  259.                 if(!in_array($date,$temporalRating["labels"])){
  260.                     $temporalRating["labels"][] = $date;
  261.                     foreach($ratingsType as $rt){
  262.                         if(!isset($temporalRating["data_".$rt][$date])) $temporalRating["data_".$rt][$date] = 0;
  263.                     }
  264.                 }
  265.                 $temporalRating["data_".$data["rating"]][$date] = $data["qtt"];
  266.             }
  267.             foreach($temporalRating as $key => $t){
  268.                 $temporalRating[$key] = array_values($temporalRating[$key]);
  269.             }
  270.             $topics = array("topic_price","topic_usage""topic_fragrance","topic_clean");
  271.             
  272.             $topicsData = array();
  273.             if($topics){
  274.                 foreach($topics as $topic){
  275.                     $topicsData[] = $reviewDataRepository->getReviewsDataTopics($product$topic$filter_channel);
  276.                 }
  277.             }
  278.             foreach($topicsData as $key => $topic){
  279.                 $topicsData[$key] = $topicsData[$key][0];
  280.                 $topicsData[$key]["topic"] = $topics[$key];
  281.             }
  282.             usort($topicsData,function($first,$second){
  283.                 return $first["positive"] < $second["positive"];
  284.             });
  285.             
  286.             $topicsDataResult = array(
  287.                 "labels" => array(),
  288.                 "positive" => array(),
  289.                 "negative" => array()
  290.             );
  291.             foreach($topicsData as $topic){
  292.                 $topicsDataResult["labels"][] = ucfirst(str_replace("topic_","",$topic["topic"]));
  293.                 $topicsDataResult["positive"][] = $topic["positive"];
  294.                 $topicsDataResult["negative"][] = $topic["negative"]*-1;
  295.             }
  296.             $keywords $reviewDataRepository->getReviewsDataKeywords($product$filter_channel);
  297.             $usedIn $reviewDataRepository->getReviewsDataProducts($product$filter_channel);
  298.             $insight $reviewDataRepository->getReviewsDataInsight($product$filter_channel);
  299.             $emotions $reviewDataRepository->getReviewsDataEmotions($product$filter_channel);
  300.             $emotionsData = array(
  301.                 "labels" => array(),
  302.                 "data" => array()
  303.             );
  304.         
  305.             if($emotions){
  306.                 foreach($emotions as $emotion){
  307.                     $emotionsData["labels"][] = ucfirst($emotion["text"]);
  308.                     $emotionsData["data"][] = round(($emotion["count"]*100)/$total,2);
  309.                 }
  310.             }
  311.             $messagesLastBest $reviewsRepository->getReviewsMessagesLastBest($product$filter_channel);
  312.             if($messagesLastBest){
  313.                 $messagesLastBest $messagesLastBest[0];
  314.             }
  315.             $messagesLastWorse $reviewsRepository->getReviewsMessagesLastWorse($product$filter_channel);
  316.             if($messagesLastWorse){
  317.                 $messagesLastWorse $messagesLastWorse[0];
  318.             }
  319.             $reviewsNeutral $reviewsRepository->getReviewsNeutral($product$filter_channel);
  320.             $reviewsPositive $reviewsRepository->getReviewsPositive($product$filter_channel);
  321.             $reviewsNegative $reviewsRepository->getReviewsNegative($product$filter_channel);
  322.             
  323.             $dataResponse = array(
  324.                 "product" => $product,
  325.                 "total" => $total,
  326.                 "channels" => $channelsInfo,
  327.                 "sentiments" => $sentiments,
  328.                 "rating" => $ratingInfo,
  329.                 "temporal" => json_encode($temporal),
  330.                 "temporalRating" => json_encode($temporalRating),
  331.                 "topics" => json_encode($topicsDataResult),
  332.                 "keywords" => json_encode($keywords),
  333.                 "usedIn" => json_encode($usedIn),
  334.                 "insight" => json_encode($insight),
  335.                 "emotions" => json_encode($emotionsData),
  336.                 "messagesLastBest" => $messagesLastBest,
  337.                 "messagesLastWorse" => $messagesLastWorse,
  338.                 "reviewsNeutral" => $reviewsNeutral,
  339.                 "reviewsPositive" => $reviewsPositive,
  340.                 "reviewsNegative" => $reviewsNegative,
  341.                 "totalTemporal" => json_encode($totalTemporal),
  342.                 "ratingInfoTemporal" => json_encode($ratingInfoTemporal["average"]),
  343.                 "ratingInfoTemporalBayes" => json_encode($ratingInfoTemporal["bayes"]),
  344.                 "labelPrev" => json_encode($labelPrev)
  345.             );
  346.             if($request->get("ajax")){
  347.                 return new JsonResponse([
  348.                     "status" => "success",
  349.                     "data" => $dataResponse
  350.                 ] , Response::HTTP_OK);
  351.             }else{
  352.                 return $this->render('detail.html.twig'$dataResponse);
  353.             }
  354.             
  355.         }else{
  356.             return $this->redirectToRoute('main_page');
  357.         }
  358.     }
  359. }