src/Controller/DashboardWidgetController.php line 259

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\DashboardChart;
  4. use App\Entity\Client;
  5. use App\Entity\Dashboard;
  6. use App\Entity\Partner;
  7. use App\Entity\DashboardWidget;
  8. use App\Form\DashboardAddWidgetOverviewTypeST;
  9. use App\Form\DashboardAddWidgetTypeGlobal;
  10. use App\Form\DashboardAddWidgetTypeST;
  11. use App\Form\DashboardWidgetType;
  12. use App\Repository\ClientRepository;
  13. use App\Repository\DashboardWidgetColumnRepository;
  14. use App\Repository\DashboardRepository;
  15. use App\Repository\DashboardChartRepository;
  16. use App\Repository\DashboardWidgetRepository;
  17. use App\Repository\PartnerRepository;
  18. use App\Repository\UserRepository;
  19. use App\Utils\CsvResponse;
  20. use App\Utils\SunburstDashboard;
  21. use App\Service\Datalake\WidgetService;
  22. use App\Utils\Slugger;
  23. use Doctrine\ORM\EntityManagerInterface;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  25. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
  28. use Symfony\Component\HttpFoundation\Session\Session;
  29. use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
  30. use Symfony\Component\HttpFoundation\File\File;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  36. use Symfony\Component\Validator\Constraints\DateTime;
  37. use Symfony\Component\Validator\Validator\ValidatorInterface;
  38. /**
  39. * @Route("/dashboard/widget")
  40. *
  41. */
  42. class DashboardWidgetController extends AbstractController
  43. {
  44.     /**
  45.     * @Route("/new", name="dashboard_widget_new", methods="GET")
  46.     */
  47.         public function new(Session $sessionDashboardRepository $dashboardRepository): Response
  48.     {
  49.         
  50.         if($session->get("id") != null)
  51.             $dashboard $dashboardRepository->findOneById($session->get("id"));
  52.         else
  53.             $dashboard $this->getUser()->getDashboards()[0];
  54.         return $this->redirectToRoute('dashboard_show', ['id' => $dashboard->getId(),'mclick' => 'widget-add']);
  55.     }
  56.     
  57.     /**
  58.     * @Route("/new/modal", name="dashboard_widget_new_modal", methods="POST")
  59.     */
  60.         public function newModal(Request $requestDashboardRepository $dashboardRepoDashboardChartRepository $dashboardChartRepoClientRepository $clientRepoPartnerRepository $partnerRepoUserRepository $userRepoSession $session): Response
  61.     {
  62.         $widget = new DashboardWidget();
  63.         $dashboardId $session->get("id");
  64.         $user $this->getUser();
  65.         $role $user->getRoles()[0];
  66.         $dashboard$dashboardRepo->findOneById($dashboardId);
  67.         // dump($dashboard->getClients()[0]->getName()); exit;
  68.         $event substr(lcfirst($dashboard->getName()), 0, -1);
  69.         // Par défaut, si Dashboard Global ou Client
  70.         //  - setName, setEvent, setDashboard
  71.         $widget->setDashboard($dashboardRepo->findOneById($dashboardId));
  72.         $dashboardClients $dashboardRepo->findOneById($dashboardId)->getClients();
  73.         // dump(count($dashboardClients)); exit;
  74.         
  75.         $widget->setEvent($event);
  76.         // if(count($dashboardClients) > 0 || count($user->getClients()) === 1){
  77.         //     if($role == "ROLE_CLIENT")
  78.         //         $widget->setName($dashboardClients[0]->getName." - ". "All Partners - ".$event);
  79.         //     else
  80.         //         $widget->setName($dashboard->getClients()[0]->getName()." - ". "All Partners - ".$event);
  81.         // } 
  82.         // else
  83.         //     $widget->setName("All advertisers - ". "All Partners - ".$event);
  84.         // dump($widget); exit;
  85.         if(null !== ($request->request->get("name")))
  86.             $widget->setName($request->request->get("name"));
  87.         if(null !== ($request->request->get("chart")))
  88.             $widget->setDashboardChart($dashboardChartRepo->findOneById($request->request->get("chart")));
  89.         if(null !== ($request->request->get("clients"))){
  90.             foreach($request->request->get("clients") as $client)
  91.                 $widget->addClient($clientRepo->findOneById($client));
  92.         }
  93.         if(null !== ($request->request->get("partners"))){
  94.             foreach($request->request->get("partners") as $partner)
  95.                 $widget->addPartner($partnerRepo->findOneById($partner));
  96.         }
  97.         $event substr(lcfirst($dashboardRepo->findOneById($dashboardId)->getName()), 0, -1);
  98.         if($event=="sale" || $event=="click" || $event=="impression" || $event=="lead" || $event=="visit")
  99.             $widget->setEvent($event);
  100.         elseif(null !== ($request->request->get("event")))
  101.             $widget->setEvent($request->request->get("event"));
  102.         // If Dashbord's clients exist, it is not a gobal dashboard, Or is User_Client has only 1 linked advertiser we can't add Clients
  103.         if(count($dashboardClients) > || count($user->getClients()) === 1){
  104.             $form $this->createForm(DashboardAddWidgetTypeST::class, $widget);
  105.         }    
  106.         else // It is a Global Dashboard, we can choose Clients
  107.             $form $this->createForm(DashboardAddWidgetTypeGlobal::class, $widget);
  108.         $title "Add new widget";
  109.         $modal $this->renderView('layout/modal/content.html.twig',array('widget' => $widget'title' => $title,'form' => $form->createView(),'path' => 'dashboard/widget/modal/_form.html.twig','id' => 'widget_new'));
  110.         
  111.         return new Response(json_encode(array('modal'=>$modal)));
  112.     }
  113.     
  114.     /**
  115.     * @Route("/ajax/new", name="dashboard_widget_ajax_new", methods="POST")
  116.     */
  117.     public function ajaxNew(AuthenticationUtils $helperRequest $requestDashboardRepository $dashboardRepoValidatorInterface $validator): Response
  118.     {
  119.         $widget = new DashboardWidget();
  120.         $dashboard $dashboardRepo->findOneById($request->request->get("dashboard"));
  121.         $dashboardClients =$dashboard->getClients();
  122.         //  Skaze à les droits d'édition sur tous les dashboard + l'user qui a créé le Dashboard
  123.         $event substr(lcfirst($dashboard->getName()), 0, -1);
  124.         $widget->setDashboard($dashboard);
  125.         $widget->setEvent($event);
  126.         $user $this->getUser();
  127.         if(count($dashboard->getClients()) > || count($user->getClients()) === 1)
  128.             $form $this->createForm(DashboardAddWidgetTypeST::class, $widget);
  129.         else
  130.             $form $this->createForm(DashboardAddWidgetTypeGlobal::class, $widget);
  131.         $widget->setDashboard($dashboard);
  132.         
  133.         
  134.         $form->handleRequest($request);
  135.          if ($request->isXmlHttpRequest()) {
  136.             if (!$form->isValid()) {
  137.                 foreach ($form as $fieldName => $formField) {
  138.                     $errors[$fieldName] = $formField->getErrors();
  139.                         return new Response(json_encode($errors));
  140.                 }
  141.             }
  142.             else {
  143.                 $em $this->getDoctrine()->getManager();
  144.                 // TODO: Ajout couche sécurité : empêcher l'édition
  145.                 //  Skaze à les droits d'édition sur tous les dashboard + l'user qui a créé le Dashboard
  146.                 // $event = substr(lcfirst($dashboard->getName()), 0, -1);
  147.                 // //  TODO: If dashboard getName = overview => create overviewType Form
  148.                 // if($request->request->get("event") != 'undefined')
  149.                 //     $widget->setEvent($request->request->get("event"));
  150.                 // elseif ($event=="sale" || $event=="click" || $event=="impression" || $event=="lead" || $event=="visit")
  151.                 //     $widget->setEvent($event);
  152.                 if($request->request->get("type") != 'undefined')
  153.                     $widget->setType($request->request->get("type"));
  154.                 else
  155.                     $widget->setType("count");
  156.                 //TODO: Changer le nom en fonctions des advertisers sélectionnés
  157.                 $widget->setX(0);
  158.                 $widget->setY(0);
  159.                 $widget->setWidth(6);
  160.                 $widget->setHeight(6);
  161.                 $widget->setStartDate(new \DateTime(date('Y-m-d 00:00:00',strtotime("-1 days"))));
  162.                 $widget->setEndDate(new \DateTime(date('Y-m-d 00:00:00',strtotime("-1 days"))));
  163.                 $widget->setTypeDate(0);
  164.                 $widget->setUser($this->getUser());
  165.                 // TODO: Ajout des columns
  166.                 $repository $this->getDoctrine()->getRepository(DashboardChart::class);
  167.                 //    Si il y a un POST_TYPE => prendre le $POST, sinon, $chart->getTypes()[0]
  168.                 $chart $repository->find($_POST['dashboardChart']);
  169.                 $widget->setDashboardChart($chart);
  170.                 if($chart->getIdentifier() == "table")
  171.                     $widget->setType("list");
  172.                 elseif($chart->getIdentifier() == "overview")
  173.                     $widget->setType("overview");
  174.                 else
  175.                     $widget->setType("count");
  176.                 $user $this->getUser();
  177.                 $role $user->getRoles()[0];
  178.                 // TODO: gerer les multi clients
  179.                 
  180.                 // if ($role === 'ROLE_CLIENT') {
  181.                 //     $dashboardClients = $dashboard->getClients();
  182.                 //     $dashboardClient = $dashboard->getUsers()[0]->getClients()[0];
  183.                 //     $widgetClients = $widget->getClients();
  184.                 //     // dump($widgetClients);
  185.                 //     // Only Add client to widget if dashboard has Client
  186.                 //     if(count($widgetClients) !== 0) {
  187.                 //         $widget->addClient($dashboardClient);
  188.                 //     }
  189.                 // } else
  190.                  if ($role === 'ROLE_PARTNER'){
  191.                     $dashboardPartner $dashboard->getUsers()[0]->getPartners()[0];
  192.                     $widget->addPartner($dashboardPartner);
  193.                 }
  194.                 
  195.                 if ($_POST['name']!='')
  196.                     $widget->setName($_POST['name']);
  197.                 // else if(count($dashboard->getClients()) > 0)
  198.                 //     $widget->setName($dashboard->getClients()[0]->getName().' - All Partners - '.ucFirst($event)."s");
  199.                 else
  200.                     $widget->setName('');
  201.                     
  202.                 // $em->persist($dashboard);
  203.                 // $em->persist($widget);
  204.                 // $em->flush();
  205.                 
  206.                 if ($role === 'ROLE_SKAZE' || $role === 'ROLE_ADMIN' || $role === 'ROLE_CLIENT') {
  207.                     //Client Add
  208.                     if (isset($_POST['clients']) && !empty($_POST['clients'])) {
  209.                         $clientTable explode(","$_POST['clients'] );
  210.                         //TODO: Voir pourquoi  $widget->addClient($client) ne marche pas
  211.                         foreach ($clientTable as $key => $client) {
  212.                             $repository $this->getDoctrine()->getRepository(Client::class);
  213.                             $client $repository->find($client);
  214.                             $client->addDashboardWidget($widget);
  215.                             $em->persist($client);
  216.                             $em->flush();
  217.                         }
  218.                     }
  219.                     if(count($dashboardClients) == 1)
  220.                     $widget->addClient($dashboard->getClients()[0]);
  221.                     if (isset($_POST['partners']) && !empty($_POST['partners'])) {
  222.                         $partnerTable explode(","$_POST['partners'] );
  223.                         //TODO: Voir pourquoi  $widget->addpartner($partner) ne marche pas
  224.                         foreach ($partnerTable as $key => $partner) {
  225.                             $repository $this->getDoctrine()->getRepository(Partner::class);
  226.                             $partner $repository->find($partner);
  227.                             $partner->addDashboardWidget($widget);
  228.                             $em->persist($partner);
  229.                             $em->flush();
  230.                         }
  231.                     }
  232.                 }
  233.                 
  234.                 $em->persist($dashboard);
  235.                 $em->persist($widget);
  236.                 $em->flush();
  237.                 $widget $this->renderView('dashboard/widget/ajax/_new.html.twig',['widget' => $widget]);
  238.                 return new Response(json_encode(array('widget' => $widget)));
  239.             }
  240.         }
  241.         return new Response(json_encode(false));
  242.     }
  243.     /**
  244.     * @Route("/{id}", name="dashboard_widget_show", methods="GET")
  245.     */
  246.     public function show(DashboardWidget $widgetDashboardRepository $dashRepo): Response
  247.     {
  248.         $isDashboardCampaign false;
  249.         $campaignDateIn false;
  250.         $campaignDateOut false;
  251.         if(count($widget->getDashboard()->getCampaigns()) >0) {
  252.             $campaign $widget->getDashboard()->getCampaigns()[0];
  253.             $isDashboardCampaign true;
  254.             $campaignDateIn $campaign->getDateIn();
  255.             $campaignDateOut $campaign->getDateOut();
  256.         }
  257.         $campaignList $widget->getDashboard()->getCampaigns();
  258.         $event  $widget->getEvent();
  259.         $campaigns = [];
  260.         foreach ($campaignList as $campaign) {
  261.             foreach ( $campaign->getPartnerCampaignIds() as $partnerCampaignId ){
  262.                 $campaigns[] = $partnerCampaignId->getCampaignDspId();
  263.             }
  264.         }
  265.         return $this->render($widget->getDashboardChart()->getPath(), ['widget' => $widget'isDashboardCampaign'=>$isDashboardCampaign 'campaignDateIn'=>$campaignDateIn'campaignDateOut'=>$campaignDateOut'uclients' => $this->getUser()->getClients(), "campaigns" => $campaigns"event" => $event]);
  266.     }
  267.     
  268.      /**
  269.     * @Route("/fs/{id}", name="dashboard_widget_showfs", methods="GET")
  270.     */
  271.     public function showfs(DashboardWidget $widget): Response
  272.     {
  273.         return $this->render($widget->getDashboardChart()->getPath(), ['widget' => $widget'uclients' => $this->getUser()->getClients(), 'fullSize' => true]);
  274.     }
  275.     /**
  276.     * @Route("/overview/{id}", name="dashboard_widget_overview", methods="GET|POST")
  277.     *
  278.     */
  279.     public function overview(DashboardWidget $widget): Response
  280.     {
  281.         $fileExist false;
  282.         $utilSunburst =  new SunburstDashboard();
  283.         $params $utilSunburst->getDateFromDuration($widget->getTypeDate());
  284.         if(count($widget->getClients()) == 0){
  285.             $pathName false;
  286.             $fileName false;
  287.             $generation false;
  288.         }else{
  289.             $pathName $this->getParameter('kernel.project_dir')."/var/tmp/".$widget->getClients()[0]->getName()." - ".$params["dateIn"]->format("yy-m-d")." - ".$params["dateOut"]->format("yy-m-d");
  290.             if(file_exists($pathName) && !(file_exists($pathName.".xlsx"))){
  291.                 $generation true;
  292.             }else{
  293.                 if(file_exists($pathName))
  294.                     unlink($pathName);
  295.                 $pathName .= ".xlsx";
  296.                 $fileName $widget->getClients()[0]->getName()." - ".$params["dateIn"]->format("yy-m-d")." - ".$params["dateOut"]->format("yy-m-d").".xlsx";
  297.                 $generation false;
  298.             }
  299.         }
  300.         
  301.         if(file_exists($pathName))
  302.             $fileExist $fileName;
  303.         $campaignList $widget->getDashboard()->getCampaigns();
  304.         $campaigns = [];
  305.         $campaignId "all";
  306.         foreach ($campaignList as $campaign) {
  307.             foreach ( $campaign->getPartnerCampaignIds() as $partnerCampaignId ){
  308.                 $campaigns[] = $partnerCampaignId->getCampaignDspId();
  309.                 $campaignId $partnerCampaignId->getCampaign()->getId();
  310.             }
  311.         }
  312.         return $this->render($widget->getDashboardChart()->getPath(), ['widget' => $widget'uclients' => $this->getUser()->getClients(), 'file' => $fileExist'fileName' => $fileName'generation' => $generation"campaigns" => $campaigns"campaignId" => $campaignId]);
  313.     }
  314.     /**
  315.     * @Route("/overview/mobile/{id}", name="dashboard_widget_overview_mobile", methods="GET|POST")
  316.     *
  317.     */
  318.     public function overviewMobile(DashboardWidget $widget): Response
  319.     {
  320.         return $this->render('dashboard/chart/template/overview3.html.twig', ['widget' => $widget'uclients' => $this->getUser()->getClients()]);
  321.     }
  322.     /**
  323.     * @Route("/setDate/overview", name="dashboard_widget_set_date_overview", methods="POST")
  324.     */
  325.      public function setDateOverview(Request $requestDashboardWidgetRepository $repo): Response
  326.     {
  327.         // Get Data from request
  328.         $date $request->request->get('date');
  329.         if($date == 3) {
  330.             // dump("date 3");
  331.             $start = new \DateTime($request->request->get('startDate'));
  332.             $end = new \DateTime($request->request->get('endDate'));
  333.         }
  334.         // if date
  335.         // dump($start, $end, $date);exit;
  336.         $widgetId $request->request->get('widget');
  337.         
  338.         // Set DashboardWidgetEntity
  339.         $em $this->getDoctrine()->getManager();
  340.         $widget $repo->find($widgetId);
  341.         $widget->setTypeDate($date);
  342.          
  343.         switch ($date) {
  344.             case 0:
  345.                 $returnDate "7 days";
  346.                 break;
  347.             
  348.             case 1:
  349.                 $returnDate "1 month";
  350.                 break;
  351.             case 2:
  352.                 $returnDate "2 months";
  353.                 break;
  354.             case 3:
  355.                 $returnDate "custom";
  356.                 $widget->setStartDate($start);
  357.                 $widget->setEndDate($end);
  358.                 break;
  359.             default:
  360.                 $returnDate "Unknown setting";
  361.                 break;
  362.         }
  363.         $em->persist($widget);
  364.         $em->flush();
  365.         // Return date for change span with js
  366.         return new JsonResponse($returnDate);    
  367.     }
  368.     
  369.     /**
  370.     * @Route("/sunburst/{tagId}/{duration}/{widgetId}", name="dashboard_widget_sunburst", methods="GET")
  371.     */
  372.      public function sunburst(Session $session,Request $requestEntityManagerInterface $em PartnerRepository $partnerRepoDashboardWidgetRepository $dashWidgetRepo): Response
  373.     {
  374.         // dump($request);
  375.         $projectDir $this->getParameter('kernel.project_dir');
  376.         $client $request->attributes->get('tagId');
  377.         $widgetId $request->attributes->get('widgetId');
  378.         $duration $request->attributes->get('duration');
  379.         if ($duration == ) {
  380.             $idate $dashWidgetRepo->findOneById($widgetId)->getStartDate()->format("Y-m-d");
  381.             $odate $dashWidgetRepo->findOneById($widgetId)->getEndDate()->format("Y-m-d");
  382.             // dump($idate, $odate);
  383.             // dump("duration 3"); exit;
  384.             // TODO: Si duration = 3, prendre les dates du widget
  385.             # code...
  386.         } else {
  387.             $utilSunburst =  new SunburstDashboard();
  388.             $params $utilSunburst->getDateFromDuration($duration);
  389.             
  390.             $idate $params['dateIn']->format("Y-m-d");
  391.             $odate $params['dateOut']->format("Y-m-d");
  392.         }
  393.         if($this->getUser()->getRoles()[0] == "ROLE_PROSPECT")
  394.             $CsvPath $projectDir."/var/fake/dashboard/sunburst/all/all.csv";
  395.         else
  396.             $CsvPath $projectDir."/var/dashboard/sunburst/".$client."/".$idate." ".$odate." - ".$client." - sunburst - skaze.csv";
  397.         if(!is_file($CsvPath) || (is_file($CsvPath) && !(date("Y-m-d"filemtime($CsvPath)) == date("Y-m-d")))){
  398.             $widgetService = new WidgetService();
  399.         
  400.             $widgetService->sunburstWrite($client,$duration$em$partnerRepo$projectDir$idate$odate);
  401.         }
  402.         $file = new File($CsvPath);
  403.         return $this->file($file);
  404.     }
  405.     /**
  406.     * @Route("/edit/{id}", name="dashboard_widget_edit", methods="GET")
  407.     */
  408.     public function edit(Request $requestDashboardWidget $widget): Response
  409.     {
  410.         $dashboard $widget->getDashboard();
  411.         return $this->redirectToRoute('dashboard_show', ['id' => $dashboard->getId(),'mclick' => 'widget-edit-'.$widget->getId()]);
  412.     }
  413.     /**
  414.     * @Route("/edit/{id}/modal", name="dashboard_widget_edit_modal", methods="POST")
  415.     */
  416.     public function editModal(Request $requestDashboardWidget $widgetDashboardRepository $dashboardRepoDashboardChartRepository $dashboardChartRepoClientRepository $clientRepoPartnerRepository $partnerRepo): Response
  417.     {
  418.         // dump($request); exit;
  419.         if(null !== ($request->request->get("name")))
  420.                 $widget->setName($request->request->get("name"));
  421.                 
  422.         if(null !== ($request->request->get("chart")))
  423.                 $widget->setDashboardChart($dashboardChartRepo->findOneById($request->request->get("chart")));
  424.                 
  425.         if(null !== ($request->request->get("clients"))){
  426.                 foreach($request->request->get("clients") as $client)
  427.                         $widget->addClient($clientRepo->findOneById($client));
  428.         }
  429.         
  430.         if(null !== ($request->request->get("partners"))){
  431.                 foreach($request->request->get("partners") as $partner)
  432.                         $widget->addPartner($partnerRepo->findOneById($partner));
  433.         }
  434.         
  435.         $event substr(lcfirst($dashboardRepo->findOneById($widget->getDashboard())->getName()), 0, -1);
  436.         
  437.         if ($event=="sale" || $event=="click" || $event=="impression" || $event=="lead" || $event=="visit")
  438.             $widget->setEvent($event);
  439.                 elseif(null !== ($request->request->get("event")))
  440.                         $widget->setEvent($request->request->get("event"));
  441.                         
  442.         //Copy
  443.         $dashboard $dashboardRepo->findOneById($widget->getDashboard());
  444.         // dump(count($dashboard->getClients())); exit;
  445.     
  446.         $user $this->getUser();
  447.         // dump(count($user->getClients())); exit;
  448.         if(count($dashboard->getClients()) > || count($user->getClients()) === 1)
  449.             $form $this->createForm(DashboardAddWidgetTypeST::class, $widget);
  450.         else
  451.             $form $this->createForm(DashboardAddWidgetTypeGlobal::class, $widget);
  452.         //end copy
  453.         // $form = $this->createForm(DashboardAddWidgetTypeST::class, $widget);
  454.         $form->handleRequest($request);
  455.         $title "Edit widget";
  456.         $modal $this->renderView('layout/modal/content.html.twig',array('widget' => $widget'title' => $title,'form' => $form->createView(),'path' => 'dashboard/widget/modal/_form.html.twig','id' => 'widget_edit'));
  457.         
  458.         return new Response(json_encode(array('modal'=>$modal)));
  459.     }
  460.     /**
  461.     * @Route("/ajax/update/{id}", name="dashboard_widget_ajax_update", methods="POST")
  462.     */
  463.     public function ajaxUpdate(Request $request,DashboardRepository $dashboardRepo$id) {
  464.         $em $this->getDoctrine()->getManager();
  465.         $dashboard $dashboardRepo->findOneById($request->request->get("dashboard"));
  466.         $repositoryWidget $this->getDoctrine()->getRepository(DashboardWidget::class);
  467.         $widget $repositoryWidget->find($id);
  468.         $widget->setDashboard($dashboard);
  469.         $oldName $widget->getName();
  470.         $clients $request->request->get('clients');
  471.         $partners $request->request->get('partners');
  472.         $dashboardChart $request->request->get('dashboardChart');
  473.         $name $request->request->get('name');
  474.         $user $this->getUser();
  475.         if ($name != ""){
  476.             $widget->setName($name);
  477.         } else {
  478.             $widget->setName('');
  479.         }
  480.         // When dashboard is Global or user has multi advertiser, we can set Client
  481.         if(count($dashboard->getClients()) === || count($user->getClients()) > ) {
  482.             //Remove old clients if exist
  483.             foreach($widget->getClients() as $client)
  484.                 $widget->removeClient($client);
  485.             if(!empty($clients) && $clients != "undefined") {
  486.                 $clientTable explode(",",$clients);
  487.                 //Register new clients
  488.                 $repositoryClient $this->getDoctrine()->getRepository(Client::class);
  489.                 foreach ($clientTable as $client) {
  490.                     $client $repositoryClient->find($client);
  491.                     $widget->addClient($client);
  492.                 }
  493.             }
  494.         }
  495.         //Remove old partners if exist
  496.         foreach($widget->getPartners() as $partner)
  497.             $widget->removePartner($partner);
  498.         if(!empty($partners) && ($partners != "undefined")) {
  499.             $partnerTable explode(",",$partners );
  500.             //Register new partners
  501.             $repositoryPartner $this->getDoctrine()->getRepository(Partner::class);
  502.             foreach ($partnerTable as $partner) {
  503.                 $partner $repositoryPartner->find($partner);
  504.                 $widget->addPartner($partner);
  505.             }
  506.         }
  507.         $repositoryDashboardChart $this->getDoctrine()->getRepository(DashboardChart::class);
  508.         $chart =  $repositoryDashboardChart->find($dashboardChart);
  509.         // Widget set type with chart selected (Table could be count but at time let it in list type)
  510.         if($chart->getName() === "table")
  511.             $widget->setType("list");
  512.         else
  513.             $widget->setType("count");
  514.         $widget->setDashboardChart($chart);
  515.         $user $this->getUser();
  516.         
  517.          if ($user->getRoles()[0] === 'ROLE_PARTNER'){
  518.             $dashboardPartner $dashboard->getUsers()[0]->getPartners()[0];
  519.             $widget->addPartner($dashboardPartner);
  520.         }
  521.         
  522.         $em->persist($dashboard);
  523.         $em->persist($widget);
  524.         $em->flush();
  525.         
  526.         $widget $this->renderView('dashboard/widget/ajax/_update.html.twig',['widget' => $widget'widgetName' => $widget->getName()]);
  527.         
  528.         return new Response(json_encode(array('widget' => $widget)));
  529.         }
  530.         
  531.     /**
  532.     * @Route("/delete/{id}", name="dashboard_widget_delete", methods="POST")
  533.     */
  534.     public function delete(Request $requestDashboardWidget $widget): Response
  535.     {
  536.         if ($this->isCsrfTokenValid('delete'.$widget->getId(), $request->request->get('_token'))) {
  537.             $em $this->getDoctrine()->getManager();
  538.             $em->remove($widget);
  539.             $em->flush();
  540.             return new Response(json_encode("true"));
  541.         }
  542.         return new Response(json_encode("false"));
  543.     }
  544.     
  545.     /**
  546.     * @Route("/delete/{id}/modal", name="dashboard_widget_delete_modal", methods="POST")
  547.     */
  548.     public function deleteModal(Request $requestDashboardWidget $widget): Response
  549.     {
  550.         $title "Delete widget ".$widget->getName();
  551.         $modal $this->renderView('layout/modal/content.html.twig',array('widget' => $widget,'title' => $title'path' => 'dashboard/widget/modal/_delete.html.twig','id' => 'widget_delete'));
  552.         
  553.         return new Response(json_encode(array('modal'=>$modal)));
  554.     }
  555.     
  556.     /**
  557.     * @Route("/ajax/date", name="dashboard_widget_ajax_date", methods="POST")
  558.     */
  559.     public function ajaxDate(Request $request)
  560.     {
  561.         $response true;
  562.         if(isset($_POST['myData'])){
  563.             //Test string
  564.             // ""
  565.             $repository $this->getDoctrine()->getRepository(DashboardWidget::class);
  566.             $entityManager $this->getDoctrine()->getManager();
  567.             if(isset($_POST['myData']['id']) && $widget $repository->find($_POST['myData']['id'])){
  568.                 //TODO: Add secure layer
  569.                 if(== 1){
  570.                     if(isset($_POST['myData']['typeDate']) && ($_POST['myData']['typeDate'] == "0" || $_POST['myData']['typeDate'] == "1" || $_POST['myData']['typeDate'] == "2"))
  571.                             $widget->setTypeDate($_POST['myData']['typeDate']);
  572.                     if(isset($_POST['myData']['startDate']) && preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$_POST['myData']['startDate']))
  573.                             $widget->setStartDate(new \DateTime($_POST['myData']['startDate']." 00:00:00.000000"));
  574.                     if(isset($_POST['myData']['endDate']) && preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$_POST['myData']['endDate']))
  575.                             $widget->setEndDate(new \DateTime($_POST['myData']['endDate']." 00:00:00.000000"));
  576.                     $entityManager->flush();
  577.                 }
  578.                 else
  579.                     $response false;
  580.             }
  581.             else
  582.                 $response false;
  583.         }
  584.         else
  585.             $response false;
  586.         return new Response(json_encode($response));
  587.     }
  588.     /**
  589.     * @Route("/ajax/position", name="dashboard_widget_ajax_position", methods="POST")
  590.     */
  591.         public function ajaxPosition(Request $request)
  592.     {
  593.         $response true;
  594.         if(isset($_POST['myData']) && is_array($_POST['myData'])){
  595.             $repository $this->getDoctrine()->getRepository(DashboardWidget::class);
  596.             $entityManager $this->getDoctrine()->getManager();
  597.             foreach($_POST['myData'] as $item){
  598.                 if(isset($item['id']) && $widget $repository->find($item['id'])){
  599.                         //TODO: Add secure layer
  600.                     if(== 1){
  601.                         if(isset($item['x']) && is_numeric($item['x']))
  602.                             $widget->setX($item['x']);
  603.                         if(isset($item['y']) && is_numeric($item['y']))
  604.                             $widget->setY($item['y']);
  605.                         if(isset($item['width']) && is_numeric($item['width']))
  606.                             $widget->setWidth($item['width']);
  607.                         if(isset($item['height']) && is_numeric($item['height']))
  608.                             $widget->setHeight($item['height']);
  609.                         $entityManager->flush();
  610.                     }
  611.                     else
  612.                         $response false;
  613.                 }
  614.                 else
  615.                     $response false;
  616.             }
  617.             $entityManager->flush();
  618.         }
  619.         else
  620.             $response false;
  621.        return new Response(json_encode($response));
  622.     }
  623.         
  624.      /**
  625.      * @Route("/ajax/convertToCsv", name="ajax_convert_csv", methods="POST")
  626.      */
  627.     public function ajaxConvertToCsv(Request $request): Response
  628.     {
  629.         if($request->isXmlHttpRequest() && isset($_POST['filename']) && isset($_POST['date']) && isset($_POST['data'])) {
  630.             $filename $_POST['filename'];
  631.             $pathFile $this->getParameter('kernel.project_dir')."/var/tmp";
  632.             if(!is_dir($pathFile))
  633.                 mkdir($pathFile);
  634.             $cb rand();
  635.             mkdir($pathFile."/".$cb);
  636.             $date $_POST['date'];
  637.             $data $_POST['data'];
  638.             $fp fopen($pathFile."/".$cb."/".$filename'w');
  639.             fputcsv($fp, array("date","count"),",",'"');
  640.             for($i=0;$i<count($date);$i++)
  641.                 fputcsv($fp, array($date[$i],$data[$i]),",",'"');
  642.             header('Content-Type: application/json');
  643.             return new JsonResponse(array($cb,$filename));
  644.         }
  645.         
  646.         header('Content-Type: application/json');
  647.         return new JsonResponse(false);
  648.     }
  649.     
  650.     /**
  651.      * @Route("/download/csv/{cb}/{file}", name="download_csv", methods="GET")
  652.      */
  653.     public function downloadCsv(Request $request$cb$file): Response
  654.     {
  655.         $pathFile $this->getParameter('kernel.project_dir');
  656.         if(is_file($pathFile."/var/tmp/".$cb.'/'.$file)) {
  657.             $response = new Response();
  658.                 $response->headers->set('Content-Type''text/csv');
  659.             $response->headers->set('Content-Disposition''attachment; filename="'$file '"');
  660.                 readfile($pathFile."/var/tmp/".$cb.'/'.$file);
  661.                 unlink($pathFile."/var/tmp/".$cb.'/'.$file);
  662.                 rmdir($pathFile."/var/tmp/".$cb);
  663.                 return $response;
  664.         }
  665.         else
  666.             throw $this->createNotFoundException('This file does not exist');
  667.     }
  668.     
  669.      /**
  670.      * @Route("/refresh/title/{id}", name="dashboard_widget_refresh_title", methods="POST")
  671.      */
  672.     public function refreshTitle(Request $request$id): Response
  673.     {
  674.         //TODO: Render only widget header to change title
  675.     }
  676. }