src/Application/Internit/SettingBundle/Controller/SettingFrontController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Application\Internit\SettingBundle\Controller;
  3. use App\Application\Internit\BuilderBundle\Entity\Builder;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  10. use App\Application\Sonata\UserBundle\Entity\User;
  11. use App\Application\Internit\ContentBundle\Controller\CRUD;
  12. use Doctrine\Common\Collections\ArrayCollection;
  13. use App\Application\Internit\RealEstateBundle\Entity\RealEstate;
  14. use App\Application\Internit\ContactBundle\Entity\ContactUs;
  15. /**
  16.  * Hierarchy Front controller.
  17.  *
  18.  * @Route("/")
  19.  */
  20. class SettingFrontController extends Controller
  21. {
  22.     public function getBundleName()
  23.     {
  24.         return 'ApplicationInternitSettingBundle';
  25.     }
  26.     public function getEntityName()
  27.     {
  28.         return 'Hierarchy';
  29.     }
  30.     public function getFormType()
  31.     {
  32.         return 'App\Application\Internit\SettingBundle\Form\HierarchyType';
  33.     }
  34.     /**
  35.     * @Route("/", name="front_setting")
  36.     */
  37.     public function indexAction(Request $request)
  38.     {
  39.         // dados enviados pelo assistente virtual (chatbot)
  40.         $chatbotData = array(
  41.             "nome" => $request->request->get('nome'),
  42.             "email" => $request->request->get('email'),
  43.             "telefone" => $request->request->get('telefone'),
  44.         );
  45.         $realEstates $this->getDoctrine()
  46.             ->getRepository('ApplicationInternitRealEstateBundle:Realty')->findIdsAndNames();
  47.         $builder $this->getDoctrine()
  48.             ->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
  49.         return $this->render(
  50.             '@ApplicationInternit/SettingBundle/Resources/views/Home/home_front.html.twig',
  51.             array(
  52.                 'data' => $realEstates,
  53.                 'builder' => $builder,
  54.                 'modaltab' => $request->query->get('modaltab'),
  55.                 'chatbotData' => json_encode($chatbotData),
  56.             )
  57.         );
  58.     }
  59.     /**
  60.      * @Route("test")
  61.      */
  62.     public function testAction()
  63.     {
  64.         return $this->render('@ApplicationInternit/SecurityBundle/Resources/views/Mail/Template-email/index.html.twig', array(
  65.             'data' => array('email' => '[email protected]''username' => 'username''password' => '123456')
  66.         ));
  67.     }
  68.     /**
  69.      * @Route("/respond_account_activation_request", name="respond_account_activation_request")
  70.      */
  71.     public function respondAccountActivationRequestAction()
  72.     {
  73.         $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
  74.         $userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
  75.         $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
  76.         $actionText = isset($_REQUEST['actionText']) ? $_REQUEST['actionText'] : null;
  77.         if (!empty($action) && !empty($userId)) {
  78.             $user $this->container->get('doctrine')
  79.                 ->getRepository('ApplicationSonataUserBundle:User')
  80.                 ->find($userId);
  81.             if ($user) {
  82.                 if ($userType == 'Corretor') {
  83.                     $realEstates $this->getRealEstates($user);
  84.                     $dateOfBirth $user->getDateOfBirth()->format('d/m/Y');
  85.     
  86.                     $message "$actionText;;";
  87.                     $message .= "Nome: {$user->getFirstname()};" .
  88.                         "CPF: {$user->getCpf()};" 
  89.                         "CRECI: {$user->getCreci()};" .
  90.                         "Data de nascimento: {$dateOfBirth};" .
  91.                         "Gênero: {$user->getGenre()};" 
  92.                         "E-mail: {$user->getEmail()};" 
  93.                         "Telefone: {$user->getPhone()};" 
  94.                         "Imobiliária: {$realEstates};";
  95.                 }
  96.                 elseif ($userType == 'Imobiliária') {
  97.                     $realEstate $user->getRealEstates()[0];
  98.                     $message "$actionText;;";
  99.                     $message .= "Nome: {$realEstate->getName()};" 
  100.                         "Razão social: {$realEstate->getCorporateName()};" .
  101.                         "CNPJ: {$realEstate->getCnpj()};" .
  102.                         "CRECI Jurídico: {$realEstate->getCreci()};" .
  103.                         "Telefone: {$realEstate->getPhone()};" .
  104.                         "E-mail padrão: {$realEstate->getEmail()};"
  105.                     ;
  106.                 }
  107.                 
  108.                 return $this->render(
  109.                     '@ApplicationInternit/SettingBundle/Resources/views/Setting/respondAccountActivationRequest.html.twig',
  110.                     array(
  111.                         'data' => $user,
  112.                         'message' => $message,
  113.                         'userType' => $userType,
  114.                         'action' => $action,
  115.                         'actionText' => $actionText
  116.                     )
  117.                 );
  118.             }
  119.         }   
  120.         return $this->redirectToRoute('front_setting');
  121.     }
  122.     private function getRealEstates($user) {
  123.         return implode(', 'array_map(function($re) { return $re->getName(); }, $user->getRealEstates()->getValues()));
  124.     }
  125.     /**
  126.      * @Route("/activate_user_account", name="activate_user_account")
  127.      */
  128.     public function activateUserAccount() {
  129.         $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
  130.         $userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
  131.         $notifyUser = isset($_REQUEST['notifyUser']) ? $_REQUEST['notifyUser'] : null;
  132.         if ($userId) {
  133.             $user $this->container->get('doctrine')
  134.                 ->getRepository('ApplicationSonataUserBundle:User')
  135.                 ->find($userId);
  136.             if ($user) {
  137.                 $user->setEnabled(true);
  138.                 $user->setUpdatedAt(new \DateTime());
  139.                 $em $this->container->get('doctrine')->getManager();
  140.                 $em->persist($user);
  141.                 $em->flush();
  142.                 if ($notifyUser) {
  143.                     // e-mail para corretor
  144.                     $email $this->get('admin.mail.service');                        
  145.                     $email->setMessage()
  146.                         ->setTo(array(
  147.                             $user->getEmail(),
  148.                         ))
  149.                         ->setBcc(array(
  150.                             '[email protected]',
  151.                         ))
  152.                         ->setSubject("Conta ativada [Cadastro - $userType]")
  153.                         ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUserActivated.html.twig", array(
  154.                             'data' => $user,
  155.                             'userType' => $userType,
  156.                             'accountAction' => 'ativada'                                                
  157.                         )), 'text/html'); 
  158.                     $email->send();
  159.                 }
  160.                 $this->get('session')->getFlashBag()->set('flash_create_success''Conta ativada com sucesso');
  161.                 return new JsonResponse(array('error' => false'message' => 'conta ativada'));
  162.             }
  163.         }   
  164.         $this->get('session')->getFlashBag()->set('flash_create_error''Erro ao ativar conta');
  165.         return new JsonResponse(array('error' => true'message' => 'conta não localizada'));
  166.     }
  167.     /**
  168.      * @Route("/remove_user_account", name="remove_user_account")
  169.      */
  170.     public function removeUserAccount()
  171.     {
  172.         $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : null;
  173.         $userType = isset($_REQUEST['userType']) ? $_REQUEST['userType'] : null;
  174.         $notifyUser = isset($_REQUEST['notifyUser']) ? $_REQUEST['notifyUser'] === "true" null;
  175.         if ($userId) {
  176.             $user $this->container->get('doctrine')
  177.                 ->getRepository('ApplicationSonataUserBundle:User')
  178.                 ->find($userId);
  179.             if ($user) {
  180.                 if ($notifyUser) {
  181.                     // e-mail para corretor
  182.                     $email $this->get('admin.mail.service');                        
  183.                     $email->setMessage()
  184.                         ->setTo(array(
  185.                             $user->getEmail(),
  186.                         ))
  187.                         ->setBcc(array(
  188.                             '[email protected]',
  189.                         ))
  190.                         ->setSubject("Conta Reprovada [Cadastro - $userType]")
  191.                         ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUserActivated.html.twig", array(
  192.                             'data' => $user,
  193.                             'userType' => $userType,
  194.                             'accountAction' => 'removida'                                                
  195.                         )), 'text/html'); 
  196.                     $email->send();
  197.                 }
  198.                
  199.                 $em $this->container->get('doctrine')->getManager();
  200.                 $em->remove($user);
  201.                 $em->flush();
  202.                 $this->get('session')->getFlashBag()->set('flash_create_success''Conta removida com sucesso');
  203.                 return new JsonResponse(array('error' => false'message' => 'conta removida'));
  204.             }
  205.         }   
  206.         $this->get('session')->getFlashBag()->set('flash_create_error''Erro ao remover conta');
  207.         return new JsonResponse(array('error' => true'message' => 'conta não localizada'));
  208.     }
  209.     /**     
  210.      *
  211.      * @Route("/submitUser")
  212.      */
  213.     public function submitUserAction()
  214.     {
  215.         $caracteres "0123456789abcdefghijklmnopqrstuvwxyz+-/()";
  216.         $password substr(str_shuffle($caracteres),0,10);
  217. //        $realEstateName = (
  218. //            isset($_REQUEST['realEstateName']) && !empty($_REQUEST['realEstateName'])
  219. //        ) ? $_REQUEST['realEstateName'] : 'Imobiliária Autônoma';
  220. //        $realEstate = $this->container->get('doctrine')
  221. //            ->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
  222. //            ->findBy(array('name' => $realEstateName));
  223.         $realEstateId $_REQUEST['realEstateId'];
  224.         $realEstate $this->container->get('doctrine')
  225.             ->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
  226.             ->findOneBy(array('id' => $realEstateId));
  227.         if (empty($realEstate)) {
  228.             $this->get('session')->getFlashBag()->set('flash_create_error''Não foi possível criar a conta. Motivo: imobiliária informada não localizada.');
  229.         
  230.             return $this->redirectToRoute('front_setting');
  231.         }
  232.         //dd($realEstate);
  233.         $email $_REQUEST['email'];
  234.         $userArray $this->container->get('doctrine')
  235.             ->getRepository('ApplicationSonataUserBundle:User')->findBy(array('email' => $email));
  236.         if (!empty($userArray)) {
  237.             $this->get('session')->getFlashBag()->set('flash_create_error''Não foi possível criar a conta. Motivo: e-mail fornecido já foi cadastrado.');
  238.         
  239.             return $this->redirectToRoute('front_setting');
  240.         }
  241.         
  242.         $request $_REQUEST;
  243.         $user = new User();
  244.         $user->setFirstname($_REQUEST['firstName']);
  245.         $user->setCpf($_REQUEST['cpf']);
  246.         $user->setDateOfBirth(new \DateTime($_REQUEST['birthDay']));
  247.         $user->setPhone($_REQUEST['phone']);
  248.         $user->setGenre($_REQUEST['genre']);
  249.         $user->setEmail($_REQUEST['email']);
  250.         $user->setCreci($_REQUEST['creci']);
  251.         $user->setUsername($_REQUEST['email']);
  252.         $user->setPlainPassword($password);
  253.         $user->setEnabled(false);
  254.         $user->setRealEstates(array($realEstate));
  255.         $user->setCreatedAt(new \DateTime());
  256.         $user->setUpdatedAt(new \DateTime());
  257.         $user->setRoles(['ROLE_CORRETOR']);
  258.         //$user->setRealEstates([$realEstate]);
  259.         $data['password'] = $password;
  260.         $data['username'] = $_REQUEST['email'];
  261.         $data['name'] = $_REQUEST['firstName'];
  262.         $data['email'] = $_REQUEST['email'];
  263.         $data['verifier'] = 'imobiliária';
  264.         $em $this->container->get('fos_user.user_manager');       
  265.         $em->updateUser($user);
  266.         // e-mail para corretor
  267.         $email $this->get('admin.mail.service');                        
  268.         $email->setMessage()
  269.             ->setTo(array(
  270.                 $_REQUEST['email'],
  271.             ))
  272.             ->setSubject("Conta criada [Cadastro - Corretor]")
  273.             ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUser.html.twig", array(
  274.                 'data' => $data,                                                
  275.             )), 'text/html'); 
  276.         $email->send(); 
  277.         $em $this->getDoctrine();
  278.         /**
  279.          * @var Builder $contrutora
  280.          */
  281.         $contrutora $em->getRepository(Builder::class)->findOneBy(['id' => 1]);
  282.         $emailConstrutora $contrutora->getAccountCreationEmailsToSend();
  283.         $emailsEnvio array_merge([$realEstate->getEmail()], $emailConstrutora);
  284.         //dd($emailsEnvio);
  285.         // e-mail para imobiliária
  286.         $email->setMessage()
  287.             ->setTo($emailsEnvio)
  288.             ->setSubject('Ativar conta [Cadastro - Corretor]')
  289.             ->setBody(
  290.                 $this->renderView('@ApplicationInternit/SettingBundle/Resources/views/Mail/emailActivateAccount.html.twig'
  291.                 array(
  292.                     'data' => $user
  293.                 )), 'text/html'
  294.             );
  295.         $email->send();
  296.         $this->get('session')->getFlashBag()->set('flash_create_success''Conta criada com sucesso. Aguarde a aprovação por e-mail.');
  297.         
  298.         return $this->redirectToRoute('front_setting');
  299.     }
  300.     /**     
  301.      *
  302.      * @Route("/submitRealEstate")
  303.      */
  304.     public function submitRealEstateAction()
  305.     {
  306.         $caracteres "0123456789abcdefghijklmnopqrstuvwxyz";
  307.         $password substr(str_shuffle($caracteres),0,10);
  308.         
  309.         $email $_REQUEST['email'];
  310.         $userArray $this->container->get('doctrine')
  311.             ->getRepository('ApplicationSonataUserBundle:User')->findBy(array('email' => $email));
  312.         if (!empty($userArray)) {
  313.             $this->get('session')->getFlashBag()->set('flash_create_error''Não foi possível criar a conta. Motivo: e-mail fornecido já foi cadastrado.');
  314.         
  315.             return $this->redirectToRoute('front_setting');
  316.         }
  317.         $request $_REQUEST;
  318.         $realEstate = new RealEstate();
  319.         $realEstate->setName($_REQUEST['name']);
  320.         $realEstate->setCnpj($_REQUEST['cnpj']);        
  321.         $realEstate->setPhone($_REQUEST['phone']);
  322.         $realEstate->setEmail($_REQUEST['email']);
  323.         $realEstate->setCorporateName($_REQUEST['corporateName']);
  324.         $realEstate->setCreci($_REQUEST['creci']); 
  325.         $realEstate->setCreatedAt(new \DateTime());
  326.         $realEstate->setUpdatedAt(new \DateTime());
  327.         
  328.         $em $this->container->get('doctrine')->getManager();
  329.         $em->persist($realEstate);
  330.         $em->flush($realEstate);
  331.         $user = new User();
  332.         $user->setFirstname($_REQUEST['name']);                
  333.         $user->setPhone($_REQUEST['phone']);
  334.         $user->setCreci($_REQUEST['creci']);
  335.         $user->setEmail($_REQUEST['email']);
  336.         $user->setUsername($_REQUEST['email']);
  337.         $user->setPlainPassword($password);
  338.         $user->setEnabled(false);
  339.         $user->setCreatedAt(new \DateTime());
  340.         $user->setUpdatedAt(new \DateTime());
  341.         $user->setRealEstates([$realEstate]);
  342.         $group $this->container->get('doctrine')
  343.             ->getRepository('ApplicationSonataUserBundle:Group')
  344.             ->findBy(['name' => 'Imobiliária']);
  345.         if (!empty($group)) {
  346.             $group $group[0];
  347.         }
  348.         
  349.         $user->addGroup($group);
  350.         $data['password'] = $password;
  351.         $data['username'] = $_REQUEST['email'];
  352.         $data['name'] = $_REQUEST['name'];
  353.         $data['email'] = $_REQUEST['email'];
  354.         $data['verifier'] = 'construtora';
  355.         $em $this->container->get('fos_user.user_manager');       
  356.         $em->updateUser($user);
  357.         $builder $this->getDoctrine()
  358.             ->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
  359.         $email $this->get('admin.mail.service');                        
  360.         $email->setMessage()
  361.             ->setTo(array(
  362.                 $user->getEmail(),
  363.             ))
  364.             ->setSubject("Conta criada [Cadastro - Imobiliária]")
  365.             ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailUser.html.twig", array(
  366.                 'data' => $data,                                                
  367.             )), 'text/html'); 
  368.         $email->send();
  369.         if ($builder) {
  370.             $accountCreationEmails $builder->getAccountCreationEmailsToSend();
  371.             
  372.             // mensagem para a construtora
  373.             $email->setMessage()
  374.                 ->setTo($accountCreationEmails)
  375.                 ->setSubject("Verificar conta [Cadastro - Imobiliária]")
  376.                 ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailActivateRealEstateAccount.html.twig", array(
  377.                     'data' => $user,                                                
  378.                 )), 'text/html'); 
  379.             $email->send();
  380.         }
  381.         $this->get('session')->getFlashBag()->set('flash_create_success''Conta criada com sucesso. Aguarde a aprovação por e-mail.');
  382.         
  383.         return $this->redirectToRoute('front_setting');
  384.     }
  385.     /**     
  386.      *
  387.      * @Route("/submitContact")
  388.      */
  389.     public function submitContactAction()
  390.     {
  391.         $request $_REQUEST;
  392.         $contact = new ContactUs();
  393.         $contact->setName($_REQUEST['name']);
  394.         $contact->setEmail($_REQUEST['email']);        
  395.         $contact->setPhone($_REQUEST['phone']);
  396.         $contact->setMessage($_REQUEST['message']);
  397.         $contact->setSource('externo');
  398.         $contact->setCreatedAt(new \DateTime());
  399.         $contact->setUpdatedAt(new \DateTime());
  400.         
  401.         $em $this->container->get('doctrine')->getManager();
  402.         $em->persist($contact);
  403.         $em->flush($contact);
  404.         $data['name'] = $_REQUEST['name'];
  405.         $data['email'] = $_REQUEST['email'];
  406.         $data['phone'] = $_REQUEST['phone'];
  407.         $data['message'] = $_REQUEST['email'];
  408.         $builder $this->getDoctrine()
  409.             ->getRepository('ApplicationInternitBuilderBundle:Builder')->find(1);
  410.         if ($builder) {
  411.             $email $this->get('admin.mail.service');                        
  412.             $email->setMessage()
  413.                 ->setTo($builder->getContactEmailsToSend())
  414.                 ->setSubject("[Fale Conosco]")
  415.                 ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailContactFront.html.twig", array(
  416.                     'data' => $data,                                                
  417.                 )), 'text/html'); 
  418.             $email->send(); 
  419.         }
  420.         $this->get('session')->getFlashBag()->set('flash_create_success''Mensagem enviada com sucesso');
  421.         
  422.         return $this->redirectToRoute('front_setting');
  423.     }
  424.     /**
  425.      * @Route("/changeMenu", name="changeMenu")
  426.      */
  427.     public function changeMenu(Request $request)
  428.     {
  429.         $menu $request->request->get('menu');
  430.         $menuSession $request->getSession('menu');
  431.         $menuSession->set('menu'$menu);
  432.         return $this->json('Session Change for: '.$menu);
  433.     }
  434. }