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

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