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

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 Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  18. use App\Application\Internit\LeadBundle\Entity\ProductUser;
  19. use App\Application\Internit\LeadBundle\Entity\realStatePercent;
  20. use App\Application\Internit\LeadBundle\Entity\Product;
  21. /**
  22.  * Client Admin controller.
  23.  *
  24.  * @Route("/admin/internit/lead/product")
  25.  */
  26. class ProductAdminController extends CRUD
  27. {
  28.     public $base "@ApplicationInternit/LeadBundle/Resources/views/Product/";
  29.     public $bundle "ApplicationInternitLeadBundle:Product";
  30.     private $listActionRoles            = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  31.     private $createActionRoles          = array('ROLE_CONSTRUTORA');
  32.     private $editActionRoles            = array('ROLE_CONSTRUTORA');
  33.     private $showActionRoles            = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  34.     private $exportFilteredActionRoles  = array('ROLE_CONSTRUTORA''ROLE_DIRETORIA''ROLE_IMOBILIARIA');
  35.     public function listAction($order = array('id' => 'DESC'))
  36.     {
  37.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->listActionRoles)) 
  38.         {
  39.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  40.         }  
  41.         return parent::listAction($order);
  42.     }
  43.     
  44.     public function createAction()
  45.     {     
  46.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->createActionRoles)) 
  47.         {
  48.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  49.         }        
  50.         $request $this->getRequest();
  51.         // the key used to lookup the template
  52.         $templateKey 'edit';
  53.         $this->admin->checkAccess('create');
  54.         
  55.         $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  56.         
  57.         $newObject $this->admin->getNewInstance();
  58.         $preResponse $this->preCreate($request$newObject);
  59.         if (null !== $preResponse) {
  60.             return $preResponse;
  61.         }
  62.         $this->admin->setSubject($newObject);
  63.         $form $this->admin->getForm();
  64.         
  65.         $form->setData($newObject);
  66.         $form->handleRequest($request);
  67.         
  68.         if ($form->isSubmitted()) {
  69.             $isFormValid $form->isValid();            
  70.             // persist if the form was valid and if in preview mode the preview was approved
  71.             if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  72.                 $this->persistImageApresentation($form);
  73.                 $submittedObject $form->getData();
  74.                 $this->admin->setSubject($submittedObject);
  75.                 $this->admin->checkAccess('create'$submittedObject);                
  76.                 try {
  77.                     $token md5(random_bytes(10).date('dmYHis'));
  78.                     $realStatePercentList $submittedObject->getRealStatePercents();
  79.                     $productUserList $submittedObject->getProductUsers();
  80.                     
  81.                     $newObject->setProductUsers(null);
  82.                     $newObject->setToken($token);
  83.                     if($realStatePercentList)
  84.                     {
  85.                         //Checa percent = 100%
  86.                         $totalPercent 0;
  87.                         foreach ($realStatePercentList as $rsPercent) {
  88.                             $totalPercent += $rsPercent->getPercent();
  89.                         }
  90.                         if($totalPercent != 100)
  91.                         {
  92.                             
  93.                             $this->get('session')->getFlashBag()->set('flash_create_error''As porcentagens das imobiliárias devem somar 100%');
  94.                             return $this->redirectToRoute('admin_internit_lead_product_create');
  95.          
  96.                         }
  97.                         foreach ($realStatePercentList as $imob => $rsPercent) {
  98.                             $imobComEspaco str_replace(
  99.                                 array('_'),
  100.                                 ' ',
  101.                                 $imob
  102.                             );
  103.                             $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneByName($imobComEspaco);
  104.                             if($realEstate){
  105.                                 $rsPercent->setProduct($newObject);
  106.                                 $rsPercent->setRealEstate($realEstate);
  107.                                 
  108.                                 $newRealStatePercent $this->admin->create($rsPercent);
  109.                                 $newObject->addRealStatePercents($newRealStatePercent);
  110.                             }
  111.                         }
  112.                     }
  113.                     if($productUserList)
  114.                     {
  115.                         $i=0;
  116.                         foreach ($productUserList as $user) {
  117.                             $userImob explode(':',$user);
  118.                             $corretor $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneById($userImob[1]);
  119.                             $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneById($userImob[0]);
  120.                             if($corretor && $realEstate){
  121.                                 
  122.                                 $productUser = new ProductUser();
  123.                                 $productUser->setUser($corretor);
  124.                                 $productUser->setRealEstate($realEstate);
  125.                                 $productUser->setProduct($newObject);
  126.                                 $productUser->setPosition($i);
  127.                                 $newProductUser $this->admin->create($productUser);
  128.                                 $newObject->addProductUsers($newProductUser);
  129.                                 $i++;
  130.                             }
  131.                         }
  132.                     }
  133.                     $newObject $this->admin->create($newObject);
  134.                                         
  135.                     $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  136.                                         
  137.                     // redirect to edit mode
  138.                     return $this->redirectTo($newObject);
  139.                 } catch (ModelManagerException $e) {
  140.                     $this->handleModelManagerException($e);
  141.                     $isFormValid false;
  142.                 }
  143.             }
  144.             
  145.             // show an error message if the form failed validation
  146.             if (!$isFormValid) {
  147.                 if (!$this->isXmlHttpRequest()) 
  148.                 {        
  149.                     $errors = array();
  150.                     foreach ($form->getErrors(true) as $error) {
  151.                         $errors[] = $error->getMessage();
  152.                     } 
  153.                       
  154.                     $this->get('session')->getFlashBag()->set('flash_create_error'implode('<br>'$errors));
  155.                 }
  156.             }
  157.         }
  158.         $formView $form->createView();
  159.     
  160.         return $this->renderWithExtraParams($this->base."create.html.twig", [
  161.             'form' => $formView
  162.         ], null);     
  163.     }
  164.     public function saveExtraLeadsAction(Request $request)
  165.     {
  166.         $realEstate $request->get('realStateId');
  167.         $extraLeads $request->get('extraLeads');
  168.         $productId $request->get('product');
  169.         $product $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:realStatePercent')->findOneBy(['product' => $productId'realEstate' => $realEstate]);
  170.         if($product){
  171.             $product->setExtraLeads($extraLeads);
  172.             $em $this->getDoctrine()->getManager();
  173.             $em->persist($product);
  174.             $em->flush();
  175.         }
  176.         $route $request->headers->get('referer');
  177.         return $this->redirect($route);
  178.     }
  179.     public function editAction($id null)
  180.     {
  181.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->editActionRoles)) 
  182.         {
  183.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  184.         }
  185.         // return parent::editAction($id = null);
  186.         $request $this->getRequest();        
  187.         $templateKey 'edit';
  188.         $id $request->get($this->admin->getIdParameter());       
  189.         $existingObject $this->admin->getObject($id);
  190.         //dump($existingObject->getUpdatedAt());
  191.         if (!$existingObject) {
  192.             throw $this->createNotFoundException(sprintf('unable to find the object with id: %s'$id));
  193.         }
  194.         $form $this->admin->getForm();       
  195.         $form->setData($existingObject);
  196.         $form->handleRequest($request);
  197.         if ($form->isSubmitted()) {
  198.             $isFormValid $form->isValid();
  199.             $submittedObject $form->getData();
  200.             $this->admin->setSubject($submittedObject);
  201.             try {
  202.                 $realStatePercentList $submittedObject->getRealStatePercents();
  203.                 //Checa percent = 100%
  204.                 $totalPercent 0;
  205.                 foreach ($realStatePercentList as $imob => $rsPercent) {
  206.                     if (is_string($imob)) {
  207.                         $totalPercent += $rsPercent->getPercent();
  208.                     }
  209.                 }
  210.                 if($totalPercent != 100)
  211.                 {
  212.                     $this->get('session')->getFlashBag()->set('flash_create_error''As porcentagens das imobiliárias devem somar 100%');
  213.                     $isFormValid false;
  214.                     // redirect to edit mode
  215.                     return $this->redirectTo($existingObject); 
  216.                 }
  217.                 $realStatePercent $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:realStatePercent')->findBy(['product' => $submittedObject]);
  218.                 $rpLastExtraLeads = [];
  219.                 /** @var $rp realStatePercent */
  220.                 foreach ($realStatePercent as $rp) {
  221.                     $rpLastExtraLeads[$rp->getRealEstate()->getId()] = $rp->getExtraLeads();
  222.                 }
  223.                 //Clean corretores selecionados para atualizar
  224.                 $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->cleanProductUser($submittedObject->getId());
  225.                 
  226.                 $productUserList $submittedObject->getProductUsers();
  227.                 //Atualizar corretores selecionados
  228.                 
  229.                 $submittedObject->setProductUsers(null);
  230.                 if($productUserList){
  231.                     $i=0;
  232.                     foreach ($productUserList as $user) {
  233.                         $userImob explode(':',$user);
  234.                         $corretor $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneById($userImob[1]);
  235.                         $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneById($userImob[0]);
  236.                         if($corretor && $realEstate){
  237.                             $productUser = new ProductUser();
  238.                             $productUser->setUser($corretor);
  239.                             $productUser->setRealEstate($realEstate);
  240.                             $productUser->setProduct($submittedObject);
  241.                             $productUser->setPosition($i);
  242.                             $newProductUser $this->admin->create($productUser);
  243.                             $submittedObject->addProductUsers($newProductUser);
  244.                             $i++;
  245.                         }
  246.                     }
  247.                 }
  248.                 $lastRealStatePercent $this->getDoctrine()->getRepository(realStatePercent::class)->findBy(['product' => $id]);
  249.                 $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->cleanRealEstatePercent($submittedObject->getId());
  250.                 // Salvar historico das turnos das imobiliarias do produto atual
  251.                 // Quando for criar as novas realState_percent manter o campo turn
  252.                 //Atualizar porcentagem das imobiliarias nas campanhas
  253.                 if($realStatePercentList)
  254.                 {
  255.                     foreach ($realStatePercentList as $imob => $rsPercent) {
  256.                         $imobComEspaco str_replace(
  257.                             array('_'),
  258.                             ' ',
  259.                             $imob
  260.                         );
  261.                         $realEstate $this->getDoctrine()->getRepository('ApplicationInternitRealEstateBundle:RealEstate')->findOneByName($imobComEspaco);
  262.                         if($realEstate){
  263.                             /**
  264.                              * @var $lastRP realStatePercent
  265.                              */
  266.                             foreach ($lastRealStatePercent as $lastRP){
  267.                                 if($lastRP->getRealEstate() === $realEstate){
  268.                                     $rsPercent->setTurn($lastRP->getTurn());
  269.                                 }
  270.                             }
  271.                             $rsPercent->setProduct($submittedObject);
  272.                             $rsPercent->setRealEstate($realEstate);
  273.                             $rsPercent->setExtraLeads($rpLastExtraLeads[$realEstate->getId()]?? 0);
  274.                             $newRealStatePercent $this->admin->create($rsPercent);
  275.                             $submittedObject->addRealStatePercents($newRealStatePercent);
  276.                         }
  277.                     }
  278.                 }
  279.                 $existingObject $this->admin->update($submittedObject);
  280.                 $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  281.                 // redirect to edit mode
  282.                 return $this->redirectTo($existingObject);
  283.             } catch (ModelManagerException $e) {
  284.                 $this->handleModelManagerException($e);
  285.                 $isFormValid false;
  286.             } catch (LockException $e) {
  287.                 $this->get('session')->getFlashBag()->set('flash_create_error''Mensagem enviada com sucesso');
  288.             }
  289.             //}
  290.             // show an error message if the form failed validation
  291.             if (!$isFormValid) {
  292.                 if (!$this->isXmlHttpRequest()) {
  293.                     $this->addFlash(
  294.                         'sonata_flash_error',
  295.                         $this->trans(
  296.                             'flash_edit_error',
  297.                             ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
  298.                             'SonataAdminBundle'
  299.                         )
  300.                     );
  301.                 }
  302.             } elseif ($this->isPreviewRequested()) {
  303.                 // enable the preview template if the form was valid and preview was requested
  304.                 $templateKey 'preview';
  305.                 $this->admin->getShow();
  306.             }
  307.        }
  308.        $formView $form->createView();
  309.     /*    dump($existingObject);
  310.         dump($existingObject->getLeadsGroupByRealState());
  311.         dump($existingObject->getRealStateProductInfo());*/
  312. //        $realStatePercents = [];
  313. //        foreach ($existingObject->realStatePercentByName() as $realState)
  314. //        {
  315. //            $realStatePercents[] =
  316. //        }
  317.        return $this->renderWithExtraParams($this->base."edit.html.twig", [
  318.            'action' => 'edit',
  319.            'form'   => $formView,
  320.            'obj'    => $existingObject
  321.        ], null);
  322.     }
  323.     public function showAction($id null)
  324.     {     
  325.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->showActionRoles)) 
  326.         {
  327.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  328.         }
  329.         $request $this->getRequest();
  330.         $id $request->get($this->admin->getIdParameter());   
  331.         $filter=[
  332.             'from' => '',
  333.             'to' => '',
  334.             'imob' => '',
  335.             'group' => '',
  336.             'user' => '',
  337.         ];
  338.         if(isset($_POST['filter']))
  339.         {
  340.             $filter $_POST['filter'];
  341.         }   
  342.         $data $this->getDoctrine()->getRepository($this->bundle)->find($id);
  343.         $template $this->base.'show.html.twig';
  344.         //$imobFilter = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findAllImobs($id);
  345.         $imobs $this->getDoctrine()->getRepository(RealEstate::class)->findAll();
  346.         foreach ($imobs as $imob){
  347.             $imobFilter[] = [ 'name' => $imob->getName() ];
  348.         }
  349.         $users $this->getDoctrine()->getRepository(User::class)->findAll();
  350.         foreach ($users as $user){
  351.             $userFilter[] = [ 'name' => $user->getFirstname() ];
  352.         }
  353.        // dd($imobFilter);
  354.         $userGroup $this->get('security.token_storage')->getToken()->getUser()->getGroups()[0]->getName();
  355.         return $this->renderWithExtraParams($template, [
  356.             'action' => 'show',
  357.             'data' => $data,
  358.             'imobFilter' => $imobFilter,
  359.             'userFilter' => $userFilter,
  360.             'filter' => $filter,
  361.             'userGroup' => $userGroup,
  362.         ], null);
  363.         return parent::showAction($id null);
  364.     }
  365.     /**
  366.      * Trata a requisição para exportar os leads filtrados em um arquivo csv.
  367.      * @param int $id - ID da campanha cujos leads serão exportados.
  368.      */
  369.     public function exportFilteredAction($id null)
  370.     {
  371.         if (!$this->get('security.token_storage')->getToken()->getUser()->hasRole($this->exportFilteredActionRoles)) 
  372.         {
  373.             return $this->renderWithExtraParams("@ApplicationInternit/ContentBundle/Resources/views/permission.html.twig");    
  374.         }
  375.         $request $this->getRequest();
  376.         $id $request->get($this->admin->getIdParameter());
  377.         $product $this->getDoctrine()->getRepository($this->bundle)->find($id);
  378.         $productName is_null($product) ? '' $product->getName();
  379.         $filter $_POST['filter'];
  380.         $leads $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')
  381.             ->findLeadByGroup($id$filter['group'], $filter);
  382.         $data = [];
  383.         if($filter['user'])
  384.         {
  385.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['firstname' => $filter['user']]);
  386.             $data = [];
  387.             foreach ($leads as $lead)
  388.                 if($lead['brokerEmail'] == $user->getEmail())
  389.                     $data[] = $lead;
  390.             $leads $data;
  391.         }
  392.         $spreadsheet = new Spreadsheet();
  393.         /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  394.         $sheet $spreadsheet->getActiveSheet();
  395.         $date date('d/m/Y H:i:s');
  396.         $dateFileName date('d-m-y__H-i-s');
  397.         $this->generateFileContent($sheet$leads);
  398.         
  399.         $writer = new Csv($spreadsheet);
  400.         $group = empty($filter['group']) ? '' $filter['group'];
  401.         $fileName "leads_{$productName}_{$group}_$dateFileName.csv";
  402.         $contentType 'text/csv';
  403.         return $this->generateFileResponse($fileName$contentType$writer);
  404.     }
  405.     /**
  406.      * Escreve os leads em um arquivo de spreadsheet.
  407.      * 
  408.      * @param \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet $sheet - planilha de trabalho atual
  409.      * @param array $leads - array dos leads filtrados para escrita.
  410.      */
  411.     private function generateFileContent($sheet$leads)
  412.     {
  413.         $columns = [
  414.             'A' => ['label' => 'Nome''field' => 'name'],
  415.             'B' => ['label' => 'E-mail''field' => 'email'],
  416.             'C' => ['label' => 'Telefone''field' => 'phone'],
  417.             'D' => ['label' => 'Imobiliária''field' => 'brokerRealState'],
  418.             'E' => ['label' => 'E-mail corretor''field' => 'brokerEmail'],
  419.             'F' => ['label' => 'Origem''field' => 'origem'],
  420.             'G' => ['label' => 'Grupo''field' => 'group'],
  421.             'H' => ['label' => 'Data de envio''field' => 'createdAt'],
  422.             'I' => ['label' => 'Utm Source''field' => 'utm_source'],
  423.             'J' => ['label' => 'Utm Medium''field' => 'utm_medium'],
  424.             'K' => ['label' => 'Utm Campaign''field' => 'utm_campaign'],
  425.         ];
  426.         $indRow 1;
  427.         foreach($columns as $col => $content) {
  428.             $sheet->setCellValue($col $indRow$content['label']);
  429.         }
  430.         $indRow 2;
  431.         foreach($leads as $lead) {
  432.             foreach ($columns as $col => $content) {
  433.                 $field $content['field'];
  434.                 $sheet->setCellValue($col $indRow$lead[$field]);
  435.             }
  436.             $indRow++;
  437.         }
  438.     }
  439.     /**
  440.      * Gera o arquivo csv exportado como uma resposta para o cliente.
  441.      * 
  442.      * @param string $fileName - nome do arquivo
  443.      * @param string $contentType - tipo mime do arquivo
  444.      * @param use PhpOffice\PhpSpreadsheet\Writer\Csv $writer - objeto que vai exportar o arquivo csv 
  445.      * @return StreamedResponse
  446.      */
  447.     private function generateFileResponse($fileName$contentType$writer)
  448.     {
  449.         $response = new StreamedResponse();
  450.         $response->headers->set('Content-Type'$contentType);
  451.         $response->headers->set('Content-Disposition''attachment;filename="'.$fileName.'"');
  452.         $response->setPrivate();
  453.         $response->headers->addCacheControlDirective('no-cache'true);
  454.         $response->headers->addCacheControlDirective('must-revalidate'true);
  455.         $response->setCallback(function() use ($writer) {
  456.             $writer->save('php://output');
  457.         });
  458.         return $response;
  459.     }
  460.     public function getBundleName()
  461.     {
  462.         return 'ApplicationInternitLeadBundle';
  463.     }
  464.     public function getEntityName()
  465.     {
  466.         return 'Product';
  467.     }
  468.     public function getFormType()
  469.     {
  470.         return 'App\Application\Internit\LeadBundle\Form\ProductType';
  471.     }
  472. }