src/Application/Internit/LeadBundle/Controller/ProductAdminController.php line 184

Open in your IDE?
  1. <?php
  2. namespace App\Application\Internit\LeadBundle\Controller;
  3. // Include PhpSpreadsheet required namespaces
  4. use App\Application\Internit\RealEstateBundle\Entity\RealEstate;
  5. use App\Application\Sonata\UserBundle\Entity\User;
  6. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  7. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  8. use PhpOffice\PhpSpreadsheet\Writer\Csv;
  9. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  10. use Symfony\Component\HttpFoundation\StreamedResponse;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  12. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  16. use App\Application\Internit\ContentBundle\Controller\CRUD;
  17. use App\Application\Internit\LeadBundle\DTO\ProductUserDTO;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  19. use App\Application\Internit\LeadBundle\Entity\ProductUser;
  20. use App\Application\Internit\LeadBundle\Entity\realStatePercent;
  21. use App\Application\Internit\LeadBundle\Entity\Product;
  22. use App\Application\Internit\LeadBundle\Entity\ProductLog;
  23. /**
  24.  * Client Admin controller.
  25.  *
  26.  * @Route("/admin/internit/lead/product")
  27.  */
  28. class ProductAdminController extends CRUD
  29. {
  30.     public $base "@ApplicationInternit/LeadBundle/Resources/views/Product/";
  31.     public $bundle "ApplicationInternitLeadBundle:Product";
  32.     private $listActionRoles            = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  33.     private $createActionRoles          = array('ROLE_CONSTRUTORA');
  34.     private $editActionRoles            = array('ROLE_CONSTRUTORA');
  35.     private $showActionRoles            = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  36.     private $exportFilteredActionRoles  = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  37.     public function listAction($order = array('id' => 'DESC'))
  38.     {
  39.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->listActionRoles)) 
  40.         {
  41.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  42.         }  
  43.         return parent::listAction($order);
  44.     }
  45.     
  46.     public function createAction()
  47.     {     
  48.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->createActionRoles)) 
  49.         {
  50.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  51.         }        
  52.         $request $this->getRequest();
  53.         // the key used to lookup the template
  54.         $templateKey 'edit';
  55.         $this->admin->checkAccess('create');
  56.         
  57.         $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  58.         
  59.         $newObject $this->admin->getNewInstance();
  60.         $preResponse $this->preCreate($request$newObject);
  61.         if (null !== $preResponse) {
  62.             return $preResponse;
  63.         }
  64.         $this->admin->setSubject($newObject);
  65.         $form $this->admin->getForm();
  66.         
  67.         $form->setData($newObject);
  68.         $form->handleRequest($request);
  69.         
  70.         if ($form->isSubmitted()) {
  71.             $isFormValid $form->isValid();            
  72.             // persist if the form was valid and if in preview mode the preview was approved
  73.             if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  74.                 $this->persistImageApresentation($form);
  75.                 $submittedObject $form->getData();
  76.                 $this->admin->setSubject($submittedObject);
  77.                 $this->admin->checkAccess('create'$submittedObject);                
  78.                 try {
  79.                     $token md5(random_bytes(10).date('dmYHis'));
  80.                     $realStatePercentList $submittedObject->getRealStatePercents();
  81.                     $productUserList $submittedObject->getProductUsers();
  82.                     
  83.                     $newObject->setProductUsers(null);
  84.                     $newObject->setToken($token);
  85.                     if($realStatePercentList)
  86.                     {
  87.                         //Checa percent = 100%
  88.                         $totalPercent 0;
  89.                         foreach ($realStatePercentList as $rsPercent) {
  90.                             $totalPercent += $rsPercent->getPercent();
  91.                         }
  92.                         if($totalPercent != 100)
  93.                         {
  94.                             
  95.                             $this->get('session')->getFlashBag()->set('flash_create_error''As porcentagens das imobiliárias devem somar 100%');
  96.                             return $this->redirectToRoute('admin_internit_lead_product_create');
  97.          
  98.                         }
  99.                         foreach ($realStatePercentList as $imob => $rsPercent) {
  100.                             $imobComEspaco str_replace(
  101.                                 array('_'),
  102.                                 ' ',
  103.                                 $imob
  104.                             );
  105.                             $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneByName($imobComEspaco);
  106.                             if($realEstate){
  107.                                 $rsPercent->setProduct($newObject);
  108.                                 $rsPercent->setRealEstate($realEstate);
  109.                                 
  110.                                 $newRealStatePercent $this->admin->create($rsPercent);
  111.                                 $newObject->addRealStatePercents($newRealStatePercent);
  112.                             }
  113.                         }
  114.                     }
  115.                     if($productUserList)
  116.                     {
  117.                         $i=0;
  118.                         foreach ($productUserList as $user) {
  119.                             $userImob explode(':',$user);
  120.                             $corretor $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneById($userImob[1]);
  121.                             $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneById($userImob[0]);
  122.                             if($corretor && $realEstate){
  123.                                 
  124.                                 $productUser = new ProductUser();
  125.                                 $productUser->setUser($corretor);
  126.                                 $productUser->setRealEstate($realEstate);
  127.                                 $productUser->setProduct($newObject);
  128.                                 $productUser->setPosition($i);
  129.                                 $newProductUser $this->admin->create($productUser);
  130.                                 $newObject->addProductUsers($newProductUser);
  131.                                 $i++;
  132.                             }
  133.                         }
  134.                     }
  135.                     $newObject $this->admin->create($newObject);
  136.                                         
  137.                     $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  138.                                         
  139.                     // redirect to edit mode
  140.                     return $this->redirectTo($newObject);
  141.                 } catch (ModelManagerException $e) {
  142.                     $this->handleModelManagerException($e);
  143.                     $isFormValid false;
  144.                 }
  145.             }
  146.             
  147.             // show an error message if the form failed validation
  148.             if (!$isFormValid) {
  149.                 if (!$this->isXmlHttpRequest()) 
  150.                 {        
  151.                     $errors = array();
  152.                     foreach ($form->getErrors(true) as $error) {
  153.                         $errors[] = $error->getMessage();
  154.                     } 
  155.                       
  156.                     $this->get('session')->getFlashBag()->set('flash_create_error'implode('<br>'$errors));
  157.                 }
  158.             }
  159.         }
  160.         $formView $form->createView();
  161.     
  162.         return $this->renderWithExtraParams($this->base."create.html.twig", [
  163.             'form' => $formView
  164.         ], null);     
  165.     }
  166.     public function saveExtraLeadsAction(Request $request)
  167.     {
  168.         $realEstate $request->get('realStateId');
  169.         $extraLeads $request->get('extraLeads');
  170.         $productId $request->get('product');
  171.         $product $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:realStatePercent')->findOneBy(['product' => $productId'realEstate' => $realEstate]);
  172.         if($product){
  173.             $product->setExtraLeads($extraLeads);
  174.             $em $this->getDoctrine()->getManager();
  175.             $em->persist($product);
  176.             $em->flush();
  177.         }
  178.         $route $request->headers->get('referer');
  179.         return $this->redirect($route);
  180.     }
  181.     public function saveLogs($productIdRequest $request)
  182.     {
  183.         $formData $request->request->all();
  184.         $formKey array_key_first($formData);
  185.         $users $formData[$formKey]['productUsers'];
  186.         $percents $formData[$formKey]['realStatePercents'];
  187.         $product $formData[$formKey]['name'];
  188.         
  189.         $data = [];
  190.         foreach($users as $user){
  191.             $user explode(':',$user);
  192.             $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneById($user[0]);
  193.             $corretor $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneById($user[1]);            
  194.             
  195.             $index str_replace(" ""_"$this->removeAcentos($realEstate->getName()));
  196.             $data[$index]["corretores"][] = $corretor->getFirstname();
  197.         }
  198.         
  199.         foreach($percents as $key=>$percent){
  200.             if($percent['percent'] > && !is_numeric($key) )
  201.             {
  202.                 $data[$key]['percent'] = $percent['percent'];
  203.                 // dump($key);
  204.             }
  205.             
  206.         }
  207.         // dump($percents);
  208.         // dump($data); exit;;/
  209.         
  210.         // $finalData["product"] = $product;
  211.         $finalData["LogData"] = date('d/m/Y H:i:s');
  212.         $finalData["Imobiliarias"] = [];
  213.         foreach($data as $key => $val){
  214.             $percent = isset($val["percent"]) ? $val["percent"] : 0;
  215.             unset($val["percent"]); // Remove o campo interno
  216.             $finalData["Imobiliarias"][$key " " $percent "%"] = $val;
  217.         }
  218.         $productObject $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneById($productId);
  219.         //dump($productObject); exit;
  220.         $dataJson json_encode($finalDataJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE);
  221.         $log = new ProductLog();
  222.         $log->setProduct($productObject);
  223.         $log->setLog($dataJson);
  224.         $log->setType("CAMPANHA");
  225.         $log->setCreatedAt(new \DateTime());
  226.         $em $this->getDoctrine()->getManager();
  227.         $em->persist($log);
  228.         
  229.     }
  230.     function removeAcentos($string) {
  231.         $acentos = [
  232.             'á','à','ã','â','ä','é','è','ê','ë','í','ì','î','ï','ó','ò','õ','ô','ö','ú','ù','û','ü','ç',
  233.             'Á','À','Ã','Â','Ä','É','È','Ê','Ë','Í','Ì','Î','Ï','Ó','Ò','Õ','Ô','Ö','Ú','Ù','Û','Ü','Ç'
  234.         ];
  235.         $semAcentos = [
  236.             'a','a','a','a','a','e','e','e','e','i','i','i','i','o','o','o','o','o','u','u','u','u','c',
  237.             'A','A','A','A','A','E','E','E','E','I','I','I','I','O','O','O','O','O','U','U','U','U','C'
  238.         ];
  239.         return str_replace($acentos$semAcentos$string);
  240.     }
  241.     public function editAction($id null)
  242.     {
  243.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->editActionRoles)) 
  244.         {
  245.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  246.         }
  247.         // return parent::editAction($id = null);
  248.         $request $this->getRequest();        
  249.         $templateKey 'edit';
  250.         $id $request->get($this->admin->getIdParameter());       
  251.         $existingObject $this->admin->getObject($id);
  252.         if (!$existingObject) {
  253.             throw $this->createNotFoundException(sprintf('unable to find the object with id: %s'$id));
  254.         }
  255.         $form $this->admin->getForm();        
  256.         
  257.         
  258.         $form->setData($existingObject);
  259.         $form->handleRequest($request);  
  260.              
  261.         
  262.         if ($form->isSubmitted()) {
  263.             $isFormValid $form->isValid();
  264.             $submittedObject $form->getData();
  265.             $this->admin->setSubject($submittedObject);
  266.             
  267.             try {
  268.                 $this->saveLogs($id$request);
  269.                
  270.                 $realStatePercentList $submittedObject->getRealStatePercents();
  271.                 //Checa percent = 100%
  272.                 $totalPercent 0;
  273.                 foreach ($realStatePercentList as $imob => $rsPercent) {
  274.                     if (is_string($imob)) {
  275.                         $totalPercent += $rsPercent->getPercent();
  276.                     }
  277.                 }
  278.                 if($totalPercent != 100)
  279.                 {
  280.                     $this->get('session')->getFlashBag()->set('flash_create_error''As porcentagens das imobiliárias devem somar 100%');
  281.                     $isFormValid false;
  282.                     // redirect to edit mode
  283.                     return $this->redirectTo($existingObject); 
  284.                 }
  285.                 $realStatePercent $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:realStatePercent')->findBy(['product' => $submittedObject]);
  286.                 $rpLastExtraLeads = [];
  287.                 /** @var $rp realStatePercent */
  288.                 foreach ($realStatePercent as $rp) {
  289.                     $rpLastExtraLeads[$rp->getRealEstate()->getId()] = $rp->getExtraLeads();
  290.                 }
  291.                 //Clean corretores selecionados para atualizar
  292.                 $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->cleanProductUser($submittedObject->getId());
  293.                 
  294.                 $productUserList $submittedObject->getProductUsers();
  295.                 //Atualizar corretores selecionados
  296.                 
  297.                 $submittedObject->setProductUsers(null);
  298.                 if($productUserList){
  299.                     $i=0;
  300.                     foreach ($productUserList as $user) {
  301.                         $userImob explode(':',$user);
  302.                         $corretor $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneById($userImob[1]);
  303.                         $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneById($userImob[0]);
  304.                         if($corretor && $realEstate){
  305.                             $productUser = new ProductUser();
  306.                             $productUser->setUser($corretor);
  307.                             $productUser->setRealEstate($realEstate);
  308.                             $productUser->setProduct($submittedObject);
  309.                             $productUser->setPosition($i);
  310.                             $newProductUser $this->admin->create($productUser);
  311.                             $submittedObject->addProductUsers($newProductUser);
  312.                             $i++;
  313.                         }
  314.                     }
  315.                 }
  316.                 $lastRealStatePercent $this->getDoctrine()->getRepository(realStatePercent::class)->findBy(['product' => $id]);
  317.                 $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->cleanRealEstatePercent($submittedObject->getId());
  318.                 // Salvar historico das turnos das imobiliarias do produto atual
  319.                 // Quando for criar as novas realState_percent manter o campo turn
  320.                 //Atualizar porcentagem das imobiliarias nas campanhas
  321.                 if($realStatePercentList)
  322.                 {
  323.                     foreach ($realStatePercentList as $imob => $rsPercent) {
  324.                         $imobComEspaco str_replace(
  325.                             array('_'),
  326.                             ' ',
  327.                             $imob
  328.                         );
  329.                         $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneByName($imobComEspaco);
  330.                         if($realEstate){
  331.                             /**
  332.                              * @var $lastRP realStatePercent
  333.                              */
  334.                             foreach ($lastRealStatePercent as $lastRP){
  335.                                 if($lastRP->getRealEstate() === $realEstate){
  336.                                     $rsPercent->setTurn($lastRP->getTurn());
  337.                                 }
  338.                             }
  339.                             $rsPercent->setProduct($submittedObject);
  340.                             $rsPercent->setRealEstate($realEstate);
  341.                             $rsPercent->setExtraLeads($rpLastExtraLeads[$realEstate->getId()]?? 0);
  342.                             $newRealStatePercent $this->admin->create($rsPercent);
  343.                             $submittedObject->addRealStatePercents($newRealStatePercent);
  344.                         }
  345.                     }
  346.                 }
  347.                 $existingObject $this->admin->update($submittedObject);
  348.                 $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  349.                 // redirect to edit mode
  350.                 return $this->redirectTo($existingObject);
  351.             } catch (ModelManagerException $e) {
  352.                 $this->handleModelManagerException($e);
  353.                 $isFormValid false;
  354.             } catch (LockException $e) {
  355.                 $this->get('session')->getFlashBag()->set('flash_create_error''Mensagem enviada com sucesso');
  356.             }
  357.             //}
  358.             // show an error message if the form failed validation
  359.             if (!$isFormValid) {
  360.                 if (!$this->isXmlHttpRequest()) {
  361.                     $this->addFlash(
  362.                         'sonata_flash_error',
  363.                         $this->trans(
  364.                             'flash_edit_error',
  365.                             ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
  366.                             'SonataAdminBundle'
  367.                         )
  368.                     );
  369.                 }
  370.             } elseif ($this->isPreviewRequested()) {
  371.                 // enable the preview template if the form was valid and preview was requested
  372.                 $templateKey 'preview';
  373.                 $this->admin->getShow();
  374.             }
  375.        }
  376.        $formView $form->createView();
  377.        return $this->renderWithExtraParams($this->base."edit.html.twig", [
  378.            'action' => 'edit',
  379.            'form'   => $formView,
  380.            'obj'    => $existingObject,
  381.            'next' => $this->get('tupi.caster.service')->next($existingObjectnull),
  382.        ], null);
  383.     }
  384.     public function showAction($id null)
  385.     {     
  386.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->showActionRoles)) 
  387.         {
  388.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  389.         }
  390.         $request $this->getRequest();
  391.         $id $request->get($this->admin->getIdParameter());   
  392.         $filter=[
  393.             'from' => '',
  394.             'to' => '',
  395.             'imob' => '',
  396.             'group' => '',
  397.             'user' => '',
  398.         ];
  399.         if(isset($_POST['filter']))
  400.         {
  401.             $filter $_POST['filter'];
  402.         }   
  403.         $data $this->getDoctrine()->getRepository($this->bundle)->find($id);
  404.         $template $this->base.'show.html.twig';
  405.         //$imobFilter = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findAllImobs($id);
  406.         $imobs $this->getDoctrine()->getRepository(RealEstate::class)->findAll();
  407.         foreach ($imobs as $imob){
  408.             $imobFilter[] = [ 'name' => $imob->getName() ];
  409.         }
  410.         $users $this->getDoctrine()->getRepository(User::class)->findAll();
  411.         foreach ($users as $user){
  412.             $userFilter[] = [ 'name' => $user->getFirstname() ];
  413.         }
  414.        // dd($imobFilter);
  415.         $userGroup $this->get('security.token_storage')->getToken()->getUser()->getGroups()[0]->getName();
  416.         return $this->renderWithExtraParams($template, [
  417.             'action' => 'show',
  418.             'data' => $data,
  419.             'imobFilter' => $imobFilter,
  420.             'userFilter' => $userFilter,
  421.             'filter' => $filter,
  422.             'userGroup' => $userGroup,
  423.         ], null);
  424.         return parent::showAction($id null);
  425.     }
  426.     function exportLogSendedAction()
  427.     {
  428.         $request $this->getRequest();
  429.         $id $request->get($this->admin->getIdParameter());          
  430.         return $this->exportLogs($id"DISTRIBUICAO");        
  431.     }
  432.     public function exportLogAction()
  433.     {
  434.         $request $this->getRequest();
  435.         $id $request->get($this->admin->getIdParameter());          
  436.         return $this->exportLogs($id"CAMPANHA");      
  437.     }
  438.     public function exportLogs($id null$type null)
  439.     {
  440.         $request $this->getRequest();
  441.         $id $request->get($this->admin->getIdParameter());          
  442.         $logEntities $this->getDoctrine()->getRepository("ApplicationInternitLeadBundle:ProductLog")->findBy(['product' => $id'type' => $type]);
  443.         // dump($logEntities); exit;
  444.         if (!$logEntities) {
  445.             return  $response = new Response("Log com ID {$id} não encontrado.");
  446.             //throw $this->createNotFoundException("Log com ID {$id} não encontrado.");
  447.         }
  448.         $allLogs = [];
  449.         $allLogs = [
  450.                 'id' => $logEntities[0]->getId(),
  451.                 'createdAt' => $logEntities[0]->getCreatedAt()->format('Y-m-d H:i:s'),
  452.                 'product' => $logEntities[0]->getProduct() ? $logEntities[0]->getProduct()->getName() : null,
  453.                 
  454.             ];
  455.         $realEstateArray = [];
  456.         foreach ($logEntities as $logEntity) {
  457.             $logData json_decode($logEntity->getLog(), true);
  458.             $realEstateArray[] = $logData;
  459.             // Adiciona metadados opcionais, como ID ou data
  460.             
  461.         }
  462.         $allLogs['data'] = $realEstateArray;
  463.         
  464.         $jsonContent json_encode($allLogsJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE);
  465.         $fileName 'logs_' date('Y-m-d_H-i-s') . '.json';
  466.         $response = new Response($jsonContent);
  467.         $response->headers->set('Content-Type''application/json');
  468.         $response->headers->set('Content-Disposition'$response->headers->makeDisposition(
  469.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  470.             $fileName
  471.         ));
  472.         return $response;
  473.            
  474.     }
  475.     /**
  476.      * Trata a requisição para exportar os leads filtrados em um arquivo csv.
  477.      * @param int $id - ID da campanha cujos leads serão exportados.
  478.      */
  479.     public function exportFilteredAction($id null)
  480.     {
  481.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->exportFilteredActionRoles)) 
  482.         {
  483.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  484.         }
  485.         $request $this->getRequest();
  486.         $id $request->get($this->admin->getIdParameter());
  487.         $product $this->getDoctrine()->getRepository($this->bundle)->find($id);
  488.         $productName is_null($product) ? '' $product->getName();
  489.         $filter $_POST['filter'];
  490.         $leads $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')
  491.             ->findLeadByGroup($id$filter['group'], $filter);
  492.         $data = [];
  493.         if($filter['user'])
  494.         {
  495.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['firstname' => $filter['user']]);
  496.             $data = [];
  497.             foreach ($leads as $lead)
  498.                 if($lead['brokerEmail'] == $user->getEmail())
  499.                     $data[] = $lead;
  500.             $leads $data;
  501.         }
  502.         $spreadsheet = new Spreadsheet();
  503.         /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  504.         $sheet $spreadsheet->getActiveSheet();
  505.         $date date('d/m/Y H:i:s');
  506.         $dateFileName date('d-m-y__H-i-s');
  507.         $this->generateFileContent($sheet$leads);
  508.         
  509.         $writer = new Csv($spreadsheet);
  510.         $group = empty($filter['group']) ? '' $filter['group'];
  511.         $fileName "leads_{$productName}_{$group}_$dateFileName.csv";
  512.         $contentType 'text/csv';
  513.         return $this->generateFileResponse($fileName$contentType$writer);
  514.     }
  515.     /**
  516.      * Escreve os leads em um arquivo de spreadsheet.
  517.      * 
  518.      * @param \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet $sheet - planilha de trabalho atual
  519.      * @param array $leads - array dos leads filtrados para escrita.
  520.      */
  521.     private function generateFileContent($sheet$leads)
  522.     {
  523.         $columns = [
  524.             'A' => ['label' => 'Nome''field' => 'name'],
  525.             'B' => ['label' => 'E-mail''field' => 'email'],
  526.             'C' => ['label' => 'Telefone''field' => 'phone'],
  527.             'D' => ['label' => 'Imobiliaria''field' => 'brokerRealState'],
  528.             'E' => ['label' => 'E-mail corretor''field' => 'brokerEmail'],
  529.             'F' => ['label' => 'Fidelidade''field' => 'loyalty'],
  530.             'G' => ['label' => 'Origem''field' => 'origem'],
  531.             'H' => ['label' => 'Grupo''field' => 'group'],
  532.             'I' => ['label' => 'Data de envio''field' => 'createdAt'],
  533.             'J' => ['label' => 'Enviado''field' => 'send_status'],
  534.             'K' => ['label' => 'Utm Source''field' => 'utm_source'],
  535.             'L' => ['label' => 'Utm Medium''field' => 'utm_medium'],
  536.             'M' => ['label' => 'Utm Campaign''field' => 'utm_campaign'],
  537.             
  538.         ];
  539.         $indRow 1;
  540.         foreach($columns as $col => $content) {
  541.             $sheet->setCellValue($col $indRow$content['label']);
  542.         }
  543.         $indRow 2;
  544.         foreach($leads as $lead) {
  545.             foreach ($columns as $col => $content) {
  546.                 $field $content['field'];
  547.                 $sheet->setCellValue($col $indRow$lead[$field]);
  548.             }
  549.             $indRow++;
  550.         }
  551.     }
  552.     /**
  553.      * Gera o arquivo csv exportado como uma resposta para o cliente.
  554.      * 
  555.      * @param string $fileName - nome do arquivo
  556.      * @param string $contentType - tipo mime do arquivo
  557.      * @param use PhpOffice\PhpSpreadsheet\Writer\Csv $writer - objeto que vai exportar o arquivo csv 
  558.      * @return StreamedResponse
  559.      */
  560.     private function generateFileResponse($fileName$contentType$writer)
  561.     {
  562.         $response = new StreamedResponse();
  563.         $response->headers->set('Content-Type'$contentType);
  564.         $response->headers->set('Content-Disposition''attachment;filename="'.$fileName.'"');
  565.         $response->setPrivate();
  566.         $response->headers->addCacheControlDirective('no-cache'true);
  567.         $response->headers->addCacheControlDirective('must-revalidate'true);
  568.         $response->setCallback(function() use ($writer) {
  569.             $writer->save('php://output');
  570.         });
  571.         return $response;
  572.     }
  573.     public function getBundleName()
  574.     {
  575.         return 'ApplicationInternitLeadBundle';
  576.     }
  577.     public function getEntityName()
  578.     {
  579.         return 'Product';
  580.     }
  581.     public function getFormType()
  582.     {
  583.         return 'App\Application\Internit\LeadBundle\Form\ProductType';
  584.     }
  585. }