src/Controller/Admin/ClientesController.php line 266

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\Imoveis;
  4. use App\Form\ClientType;
  5. use App\Repository\ImoveisRepository;
  6. use App\Service\AlogliaHelper;
  7. use Doctrine\DBAL\Connection;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\File\UploadedFile;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\HttpFoundation\UrlHelper;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\Mailer\MailerInterface;
  18. use Symfony\Component\Mime\Email;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  20. use ZipStream\File;
  21. use App\Entity\HistoryClientComissions;
  22. use function Symfony\Component\DependencyInjection\Loader\Configurator\service_locator;
  23. /**
  24.  * @Route("/admin/clientes")
  25.  * @IsGranted("ROLE_ADMIN" ,"ROLE_OPERATOR")
  26.  */
  27. class ClientesController extends AbstractController
  28. {
  29.     public function __construct(UrlHelper $urlHelperImoveisRepository $imoveisRepository)
  30.     {
  31.         $this->urlHelper $urlHelper;
  32.         $this->ImoveisRepository $imoveisRepository;
  33.     }
  34.     /**
  35.      * @Route("/bitrix", methods={"GET"}, name="admin_clientes_bitrix")
  36.      */
  37.     public function clientesBitrix(){
  38.         ini_set('memory_limit',-1);
  39.         ini_set('max_execution_time',-1);
  40.         $connection $this->getDoctrine()->getConnection();
  41. //        $sql ="SELECT cod_stays, nome, email, cpf, celular, plano FROM `imoveis` WHERE cpf not in('000.000.000-00','') and (email <> '' or celular<>'')";
  42.         $sql ="SELECT cod_stays, nome, email, cpf, celular, plano FROM `imoveis` WHERE plano > 0";
  43.         $clientes $connection->executeQuery($sql)->fetchAll();
  44.         $this->curl curl_init();
  45.         $continue true$i=0;
  46.         foreach ($clientes as $cliente) {
  47.             $idContatct false//$this->bitrixGetContact($cliente);
  48.             //dump("ID contato: ".$idContatct);
  49.             dump($cliente);
  50.             $this->bitrixGetImovel($cliente,$idContatct);
  51.             $i++;
  52.             if($i%15==0)
  53.                 sleep(2);
  54.         }
  55.         curl_close($this->curl);
  56.         die;
  57.     }
  58.     protected function bitrixGetImovel($cliente$cod_contact){
  59.         $cod_stays $cliente['cod_stays'];
  60.         $filter['filter']['STAGE_ID'] = 'C28:NEW';
  61.         $filter['filter']['UF_CRM_1663851986'] = $cod_stays;
  62.         $url 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.deal.list?'.http_build_query($filter);
  63.         curl_setopt_array($this->curl, array(
  64.             CURLOPT_URL => $url,
  65.             CURLOPT_RETURNTRANSFER => true,
  66.             CURLOPT_ENCODING => '',
  67.             CURLOPT_MAXREDIRS => 10,
  68.             CURLOPT_TIMEOUT => 0,
  69.             CURLOPT_FOLLOWLOCATION => true,
  70.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  71.             CURLOPT_CUSTOMREQUEST => 'GET',
  72.         ));
  73.         $response curl_exec($this->curl);
  74.         $result json_decode($response,true);
  75.         if($result['total']==0)
  76.             return false;
  77.         else {
  78.             $id $result['result'][0]['ID'];
  79.             if($cod_contact)
  80.                 $fields['fields']['CONTACT_ID'] = $cod_contact;
  81.             $fields['fields']['UF_CRM_1648061516'] = $cliente['plano'];
  82.             dump("ID imovel: ".$id);
  83.             $url 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.deal.update?ID=' $id '&' http_build_query($fields);
  84.             dump($url);
  85.             curl_setopt_array($this->curl, array(
  86.                 CURLOPT_URL => $url,
  87.                 CURLOPT_RETURNTRANSFER => true,
  88.                 CURLOPT_ENCODING => '',
  89.                 CURLOPT_MAXREDIRS => 10,
  90.                 CURLOPT_TIMEOUT => 0,
  91.                 CURLOPT_FOLLOWLOCATION => true,
  92.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  93.                 CURLOPT_CUSTOMREQUEST => 'GET',
  94.             ));
  95.             $response curl_exec($this->curl);
  96.             $result json_decode($responsetrue);
  97.             dump($result);
  98.         }
  99.     }
  100.     protected function bitrixGetContact($cliente){
  101.         $phone $cliente['celular'];
  102.         $name $cliente['nome'];
  103.         $email $cliente['email'];
  104.         $filter['filter']['PHONE'] = $phone;
  105.         $fields['fields']['TYPE_ID'] = 'CLIENT';
  106.         $fields['fields']['NAME'] = $name;
  107.         $fields['fields']['PHONE'][0]['VALUE'] = $phone;
  108.         $fields['fields']['PHONE'][0]['VALUE_TYPE'] = 'MOBILE';
  109.         $fields['fields']['EMAIL'][0]['VALUE'] = $email;
  110.         $fields['fields']['EMAIL'][0]['VALUE_TYPE'] = 'WORK';
  111.         $fields['fields']['UF_CRM_1646672583'] = preg_replace("/[^0-9]/"""$cliente['cpf'] );
  112.         $url 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.contact.list?'.http_build_query($filter);
  113.         curl_setopt_array($this->curl, array(
  114.             CURLOPT_URL => $url,
  115.             CURLOPT_RETURNTRANSFER => true,
  116.             CURLOPT_ENCODING => '',
  117.             CURLOPT_MAXREDIRS => 10,
  118.             CURLOPT_TIMEOUT => 0,
  119.             CURLOPT_FOLLOWLOCATION => true,
  120.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  121.             CURLOPT_CUSTOMREQUEST => 'GET',
  122.         ));
  123.         $response curl_exec($this->curl);
  124.         $result json_decode($response,true);
  125.         dump($result);
  126.         if($result['total']==|| !$result){
  127.             $url 'https://bnbg.bitrix24.com.br/rest/4/p2hhksryy92wc3hs/crm.contact.add/?'.http_build_query($fields);
  128.             dump($url);
  129.             curl_setopt_array($this->curl, array(
  130.                 CURLOPT_URL => $url,
  131.                 CURLOPT_RETURNTRANSFER => true,
  132.                 CURLOPT_ENCODING => '',
  133.                 CURLOPT_MAXREDIRS => 10,
  134.                 CURLOPT_TIMEOUT => 0,
  135.                 CURLOPT_FOLLOWLOCATION => true,
  136.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  137.                 CURLOPT_CUSTOMREQUEST => 'GET',
  138.             ));
  139.             $response curl_exec($this->curl);
  140.             $result2 json_decode($response,true);
  141.             dump('insert');
  142.             dump($result2);
  143.             return $result2['result'];
  144.         }
  145.         else{
  146.             return $result['result'][0]['ID'];
  147.         }
  148.     }
  149.     /**
  150.      * @Route("/lista", methods={"GET"}, name="admin_clientes_lista")
  151.      */
  152.     public function lista_clientes()
  153.     {
  154.         $status=$_GET['status']=='ativos' || !$_GET['status']? 10;
  155.         $em $this->getDoctrine()->getManager();
  156.         $imoveis $em->getRepository(Imoveis::class)->findAlltoArray(['status'=>$status]);
  157.         return $this->render('admin/lista_clientes.html.twig', [
  158.             'data' => $imoveis,
  159.             'status' =>$status
  160.         ]);
  161.     }
  162.     /**
  163.      * @Route("/migrate_mysql", methods={"GET"}, name="admin_clientes_migrate")
  164.      */
  165.     public function migrate_clientes(EntityManagerInterface $emConnection $connection)
  166.     {
  167.         die;
  168.         $algolia = new AlogliaHelper();
  169.         $index $algolia->client->initIndex('clientes');
  170.         $data $index->search('',[
  171.             'hitsPerPage' => 1000,
  172.         ]);
  173.         foreach($data['hits'] as $row){
  174.             $imovel = new Imoveis();
  175.             $imovel->setObjectID($row['objectID']);
  176.             $imovel->setEmail(trim($row['email']));
  177.             $imovel->setNome(trim($row['nome']));
  178.             $imovel->setCelular(trim($row['celular']));
  179.             $imovel->setCidade(trim($row['praia']));
  180.             $imovel->setEndereco(trim($row['endereco']));
  181.             $imovel->setContrato($row['contrato']);
  182.             $imovel->setCpf($row['cpf']);
  183.             $imovel->setCodStays($row['cod_stays']);
  184.             $imovel->setPlano($row['plano']);
  185.             $imovel->setAviso($row['aviso']);
  186.             $em->persist($imovel);
  187.             $em->flush();
  188.         }
  189.         $connection->executeQuery('UPDATE imoveis AS U1, imoveis AS U2 SET U1.id = U2.object_id WHERE U2.id = U1.id');
  190.         die;
  191.     }
  192.     /**
  193.      * @Route("/migrate_invenstario", methods={"GET"}, name="admin_inventario_migrate")
  194.      */
  195.     public function migrate_inventario(EntityManagerInterface $emConnection $connection)
  196.     {
  197.         die;
  198.         $em $this->getDoctrine()->getManager();
  199.         $imoveis $em->getRepository(Imoveis::class)->findAll();
  200.         $algolia = new AlogliaHelper();
  201.         $inventario $algolia->client->initIndex('inventarios');
  202.         /** @var Imoveis $imovel */
  203.         foreach ($imoveis as $imovel){
  204.             if($imovel->getObjectID()){
  205.                 $itens $inventario->search('',[
  206.                     'facetFilters' => [
  207.                         "cliente_id:".$imovel->getObjectID(),
  208.                     ],
  209.                     'hitsPerPage' => 1
  210.                 ]);
  211.                 $imovel->setInventario($itens['hits'][0]['images']);
  212.                 $em->persist($imovel);
  213.                 $em->flush();
  214.             }
  215.         }
  216.         die('aaaa');
  217.     }
  218.     /**
  219.      * @Route("/editar/{id}", methods={"GET","POST"}, name="admin_clientes_edit")
  220.      */
  221.     public function edit_clientes(Request $requestImoveisRepository $imoveisRepository$id)
  222.     {
  223.         $cliente $imoveisRepository->find($id);
  224.         $cliente->setPlano($cliente->getPlano()? $cliente->getPlano(): 0);
  225.         $planoOld $cliente->getPlano();
  226.         $form $this->createForm(ClientType::class, $cliente);
  227.         $form->handleRequest($request);
  228.         if ($form->isSubmitted() && $form->isValid()) {
  229.             if($planoOld!=$cliente->getPlano()){
  230.                 $updatePlano=true;
  231.             }
  232.             $validate $this->verifyDuplicate($cliente);
  233.             if($validate['error']){
  234.                 $this->addFlash('danger'$validate['message']);
  235.                 return $this->render('admin/clientes_edit.html.twig', [
  236.                     'data' => $cliente,
  237.                     'form' => $form->createView(),
  238.                     'new' => false
  239.                 ]);
  240.             }
  241.             if($updatePlano){
  242.                 $this->updatePlano($cliente);
  243.             }
  244.             $entityManager $this->getDoctrine()->getManager();
  245.             $entityManager->persist($cliente);
  246.             $entityManager->flush();
  247.             $this->addFlash('success''Atualização realizada com sucesso!');
  248.             return $this->redirectToRoute('admin_clientes_lista');
  249.         }
  250.         return $this->render('admin/clientes_edit.html.twig', [
  251.             'data' => $cliente,
  252.             'form' => $form->createView(),
  253.             'new' => false
  254.         ]);
  255.     }
  256.     protected function updatePlano(Imoveis $cliente){
  257.         $history = new HistoryClientComissions();
  258.         $history->setListingId($cliente->getCodStays());
  259.         $history->setPercentege($cliente->getPlano());
  260.         $now = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo'));
  261.         $history->setUntilDate($now);
  262.         $entityManager $this->getDoctrine()->getManager();
  263.         $entityManager->persist($history);
  264.         $entityManager->flush();
  265.     }
  266.     /**
  267.      * @Route("/novo", methods={"GET","POST"}, name="admin_clientes_new")
  268.      */
  269.     public function new_clientes(Request $request)
  270.     {
  271.         $imovel = new Imoveis();
  272.         $form $this->createForm(ClientType::class, $imovel);
  273.         $form->handleRequest($request);
  274.         if ($form->isSubmitted() && $form->isValid()) {
  275.             $validate $this->verifyDuplicate($imovel);
  276.             if($validate['error']){
  277.                 $this->addFlash('danger'$validate['message']);
  278.                 return $this->render('admin/clientes_edit.html.twig', [
  279.                     'form' => $form->createView(),
  280.                     'data' => $imovel,
  281.                     'new' => true
  282.                 ]);
  283.             }
  284.             $imovel->setStatus(1);
  285.             $entityManager $this->getDoctrine()->getManager();
  286.             $entityManager->persist($imovel);
  287.             $entityManager->flush();
  288.             $this->addFlash('success''Registro incluído com sucesso!');
  289.             return $this->redirectToRoute('admin_clientes_lista');
  290.         }
  291.         return $this->render('admin/clientes_edit.html.twig', [
  292.             'form' => $form->createView(),
  293.             'data' => $imovel,
  294.             'new' => true
  295.         ]);
  296.     }
  297.     /**
  298.      * @Route("contrato_upload", methods={"POST"}, name="admin_clientes_contrato")
  299.      */
  300.     public function contrato_upload(Request $request){
  301.         $file $request->files->get('file');
  302.         /** @var $file UploadedFile */
  303.         $id $_GET['id'];
  304.         $dir __DIR__.'/../../../web/uploads/clientes/'.$id.'/';
  305.         $new_name time().'.pdf';
  306.         if($file->move($dir,$new_name)){
  307.             return new JsonResponse([
  308.                 'url' => $this->urlHelper->getAbsoluteUrl(
  309.                     $this->generateUrl('admin_clientes_contrato_download',[
  310.                         'file'=>$new_name,
  311.                         'cliente_id' => $id,
  312.                     ])
  313.                 )
  314.             ]);
  315.         }
  316.     }
  317.     /**
  318.      * @Route("contrato_download/{cliente_id}/{file}", methods={"GET"}, name="admin_clientes_contrato_download")
  319.      */
  320.     public function contrato_download($cliente_id,$file){
  321.         $file_path __DIR__.'/../../../web/uploads/clientes/'.$cliente_id.'/'.$file;
  322.         $file = new \Symfony\Component\HttpFoundation\File\File($file_path);
  323.         return $this->file($file);
  324.     }
  325.     public function verifyDuplicate($client){
  326.         $connection $this->getDoctrine()->getConnection();
  327.         $sql ='SELECT id FROM imoveis where cod_stays= "'.$client->getCodStays().'"'.($client->getId()? ' and id <> "'.$client->getId().'"''');
  328.         $vCodStays $connection->executeQuery($sql)->rowCount();
  329.         if($vCodStays>0){
  330.             return ['error'=>true'message'=>'Esse código stays já está sendo utilizado por outro imóvel.'];
  331.         }
  332. //        $sql ='SELECT id FROM imoveis where cpf= "'.$client->getCpf().'"'.($client->getId()? ' and id <> "'.$client->getId().'"': '');
  333. //        $vCpf = $connection->executeQuery($sql)->rowCount();
  334. //
  335. //        if($vCpf>0){
  336. //            return ['error'=>true, 'message'=>'Esse CPF já está sendo utilizado por outro imóvel.'];
  337. //        }
  338.         return ['error'=>false];
  339.     }
  340.     public static function getClient($id){
  341.         die('refazer chamada getClient');
  342.     }
  343. }