src/Application/Internit/LeadBundle/Controller/ProductFrontController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Application\Internit\LeadBundle\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\Internit\LeadBundle\Entity\Lead;
  10. use App\Application\Internit\LeadBundle\Entity\LeadErrorLog;
  11. use App\Application\Internit\LeadBundle\Message\LeadMessage;
  12. use Symfony\Component\Messenger\MessageBusInterface;
  13. use App\Application\Internit\LeadBundle\Entity\ChatbotLead;
  14. use App\Application\Internit\LeadBundle\Entity\TemporaryLead;
  15. use Symfony\Component\HttpKernel\Exception\HttpException;
  16. use Swift_SmtpTransport;
  17. use Swift_Mailer;
  18. use Swift_Message;
  19. /**
  20.  * Product Front controller.
  21.  *
  22.  * @Route("/api/leads")
  23.  */
  24. class ProductFrontController extends Controller
  25. {    
  26.     public function getBundleName()
  27.     {
  28.         return 'ApplicationInternitLeadBundle';
  29.     }
  30.     public function getEntityName()
  31.     {
  32.         return 'Product';
  33.     }
  34.     public function getFormType()
  35.     {
  36.         return 'App\Application\Internit\LeadBundle\Form\ProductType';
  37.     }
  38.     /**
  39.      * @Route("/getLead", name="front_product_lead_send_get")
  40.      * @Method("GET")
  41.      */
  42.     public function getLead(Request $request)
  43.     {
  44.         $id_pipe = $request->get('id_pipe');
  45.         $response = [];
  46.         if($id_pipe){
  47.             try {
  48.                 $lead = $this->getDoctrine()
  49.                     ->getRepository('ApplicationInternitLeadBundle:Lead')
  50.                     ->findByIdPipe(intval($id_pipe));
  51.                 if (!$lead) {
  52.                     return $this->sendStatus(404, "Lead não encontrado.");
  53.                 }
  54.                 $broker = $this->getDoctrine()
  55.                     ->getRepository('ApplicationSonataUserBundle:User')
  56.                     ->findOneByEmail($lead->getBrokerEmail());
  57.                 if (!$broker) {
  58.                     return $this->sendStatus(404, "Corretor associado não encontrado.");
  59.                 }
  60.                 $response = [
  61.                     'Broker_Name' => $broker->getFirstName(),
  62.                     'Realstate_Name' => $lead->getBrokerRealState()
  63.                 ];
  64.                 return $this->sendStatus(200, "Dados recuperados com sucesso.", $response);
  65.             } catch (\Exception $e) {
  66.                 return new \Symfony\Component\HttpFoundation\JsonResponse([
  67.                     'status' => 500,
  68.                     'message' => $e->getMessage(), 
  69.                     'file' => $e->getFile(),       
  70.                     'line' => $e->getLine()        
  71.                 ], 500);
  72.             }
  73.         }
  74.     }
  75.     /**
  76.      * @Route("/send", name="front_product_lead_send")
  77.      * @Method("POST")
  78.      */
  79.     public function send(Request $request, MessageBusInterface $bus)
  80.     {
  81.         $data = json_decode($request->getContent());
  82.         
  83.         if (!$data) {
  84.             return $this->sendStatus(400, "New Lead is not valid");
  85.         }
  86.         if (isset($data->token)) {
  87.             if (
  88.                 !empty($data->name) &&
  89.                 !empty($data->origem) &&
  90.                 !empty($data->group)
  91.             ) {
  92.                 // form de whatsapp não traz e-mail
  93.                 $emailLead = isset($data->email) ? $data->email : '';
  94.                 $phoneLead = isset($data->phone) ? $data->phone : '';
  95.                 $id_pipe = isset($data->id_pipe) ? intval($data->id_pipe) : '';
  96.                 $message = new LeadMessage(
  97.                     $data->name,
  98.                     $emailLead,
  99.                     $phoneLead,
  100.                     $data->group,
  101.                     $data->origem,
  102.                     $data->token,
  103.                     $data->fixedPhone ?? '',
  104.                     $data->empreendimento ?? '',
  105.                     $data->utm_source ?? '',
  106.                     $data->utm_medium ?? '',
  107.                     $data->utm_campaign ?? '',
  108.                     $id_pipe
  109.                 );
  110.                 $bus->dispatch($message);
  111.                 return $this->sendStatus(200, "Lead criado");
  112.             } else {
  113.                 return $this->sendStatus(400, "Invalid content");
  114.             }
  115.         }
  116.         return $this->sendStatus(400, "Token is required");
  117.     }
  118.     public function sendLast(Request $request)
  119.     {
  120.         $data = json_decode($request->getContent());
  121.         $statusCode = 400;
  122.         $result = [];
  123.         if (!$data)
  124.             return $this->sendStatus(400, "New Lead is not valid");
  125.         if (isset($data->token)) {
  126.             $product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneByToken($data->token);
  127.             // dump($product); exit;
  128.             if (!$product)
  129.                 return $this->sendStatus(404, "Product not found");
  130.             if (
  131.                 !empty($data->name) &&
  132.                 !empty($data->origem) &&
  133.                 !empty($data->group)
  134.             ) {
  135.                 // form de whatsapp não traz e-mail
  136.                 $emailLead = isset($data->email) ? $data->email : '';
  137.                 $phoneLead = isset($data->phone) ? $data->phone : '';
  138.                 $extraInfo = array();
  139.                 $to = $this->get('tupi.caster.service')->next($product, $emailLead, $phoneLead);
  140.                 //dd($to);
  141.                 // dump($to);exit;
  142.                 $newLead = new Lead();
  143.                 //Obrigatórios
  144.                 $newLead->setName($data->name);
  145.                 $newLead->setGroup($data->group);
  146.                 $newLead->setOrigem($data->origem);
  147.                 $newLead->setProduct($product);
  148.                 $newLead->setEmail($emailLead);
  149.                 $newLead->setPhone($phoneLead);
  150.                 //Opcionais
  151.                 if (isset($data->fixedPhone)) {
  152.                     $newLead->setFixedPhone(($data->fixedPhone ? $data->fixedPhone : ''));
  153.                 }
  154.                 if (isset($data->empreendimento))
  155.                     $newLead->setEmpreendimento(($data->empreendimento ? $data->empreendimento : ''));
  156.                 if (isset($data->utm_source))
  157.                     $newLead->setUtm_source(($data->utm_source ? $data->utm_source : ''));
  158.                 if (isset($data->utm_medium))
  159.                     $newLead->setUtm_medium(($data->utm_medium ? $data->utm_medium : ''));
  160.                 if (isset($data->utm_campaign))
  161.                     $newLead->setUtm_campaign(($data->utm_campaign ? $data->utm_campaign : ''));
  162.                 if (isset($data->message))
  163.                     $newLead->setMessage(($data->message ? $data->message : ''));
  164.                 // e-mail que a construtora configura para receber os leads deste produto.
  165.                 $productEmail = $product->getEmail();
  166.                 if (!empty($productEmail) || !is_null($to)) {
  167.                     // obter e-mails de lead da imobiliária da vez
  168.                     $realEstateLeadEmails = $this->getDoctrine()
  169.                         ->getRepository('ApplicationInternitLeadBundle:RealEstateEmail')
  170.                         ->findRealEstateLeadEmails($to['imob']);
  171.                     $realEstate = $this->getDoctrine()
  172.                         ->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
  173.                         ->findOneBy(['name' => $to['imob']]);
  174.                     //Chamar service de disparo para corretor
  175.                     $email1 = $this->get('admin.mail.service');
  176.                     $email2 = $this->get('admin.mail.service');
  177.                     // EMAILS COPY
  178.                     $emailCopySend = [];
  179.                     if ($realEstate) {
  180.                         if ($realEstate->getReceiveLead()) {
  181.                             $emailCopySend[] = $realEstate->getEmail();
  182.                             //$email->setMessage()->setBCC($realEstate->getEmail());
  183.                         }
  184.                     }
  185.                     if (! empty($productEmail)) {
  186.                         $emailsSend = explode(',', str_replace(' ', '', $productEmail));
  187.                         foreach ($emailsSend as $sendMail) {
  188.                             $emailCopySend[] = $sendMail;
  189.                             //$email->setMessage()->setBCC($sendMail);
  190.                         }
  191.                     }
  192.                     // se houver o e-mail do corretor, ele é o destinatário principal e
  193.                     // o e-mail padrão da campanha é cópia oculta
  194.                     if (!empty($to['email'])) {
  195.                         $email1->setMessage()->setTo($to['email']);
  196.                         //dd($realEstate);
  197.                         if (!empty($emailCopySend)) {
  198.                             $email2->setMessage()->setTo($emailCopySend);
  199.                         }
  200.                     }
  201.                     // se não houver nenhum corretor para receber e-mail, o e-mail padrão
  202.                     // da campanha é o destinatário principal
  203.                     else if (! empty($productEmail)) {
  204.                         $emailsSend = explode(',', str_replace(' ', '', $productEmail));
  205.                         foreach ($emailsSend as $sendMail) {
  206.                             $emailCopySend[] = $sendMail;
  207.                             //$email->setMessage()->setBCC($sendMail);
  208.                         }
  209.                         $email1->setMessage()->setTo($emailsSend);
  210.                         if (!empty($emailCopySend)) {
  211.                             $email2->setMessage()->setTo($emailCopySend);
  212.                         }
  213.                     }
  214.                     // if (!empty($realEstateLeadEmails)) {
  215.                     //     $email->setMessage()->setCC($realEstateLeadEmails);
  216.                     // }
  217.                     $newLead->setBrokerEmail(! empty($to['email']) ? $to['email'] : $productEmail); //Seta email do corretor que recebeu o lead
  218.                     $newLead->setBrokerRealState($to['imob']); //Seta Imobiliaria do corretor que recebeu o lead
  219.                     $extraInfo['broker_name'] = $to['name'];
  220.                     if ($to['phone'])
  221.                         $extraInfo['broker_phone'] = preg_replace('/[^0-9]/', '', $to['phone']);
  222.                     $entityManager = $this->getDoctrine()->getManager();
  223.                     $entityManager->persist($newLead);
  224.                     $entityManager->flush();
  225.                     $email1
  226.                         ->setMessage()
  227.                         ->setSubject("[Lead] " . $product->getName() . ' - ' . $newLead->getGroup())
  228.                         ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
  229.                             'data' => $newLead,
  230.                         )), 'text/html');
  231.                     $email1->send();
  232.                     $email2
  233.                         ->setMessage()
  234.                         ->setSubject("[Lead] " . $product->getName() . ' - ' . $newLead->getGroup())
  235.                         ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
  236.                             'data' => $newLead,
  237.                         )), 'text/html');
  238.                     $email2->send();
  239.                 }
  240.                 // dump($newLead);
  241.                 return $this->sendStatus(200, "Lead created", $extraInfo);
  242.             } else {
  243.                 return $this->sendStatus(400, "Invalid content");
  244.             }
  245.         }
  246.         return $this->sendStatus(400, "Token is required");
  247.     }
  248.     private function sendStatus($code = 401, $message = "Requisição não autorizada", $extra = array())
  249.     {
  250.         $array = array('message' => $message);
  251.         $array = array_merge($array, $extra);
  252.         $response = new Response(json_encode($array), $code);
  253.         $response->headers->set('Content-Type', 'application/json');
  254.         return $response;
  255.     }
  256.     private function handleBodyView($lead = null, $brokerName = null)
  257.     {
  258.         return $this->renderView('@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig', [
  259.             'data' => $lead ?? '',
  260.             'corretor' => $brokerName ?? '',
  261.         ]);
  262.     }
  263.     public function reDispatch($payload, MessageBusInterface $bus){
  264.         $data = json_decode($payload);
  265.         $emailLead = isset($data->email) ? $data->email : '';
  266.         $phoneLead = isset($data->phone) ? $data->phone : '';
  267.         $message = new LeadMessage(
  268.             $data->name,
  269.             $emailLead,
  270.             $phoneLead,
  271.             $data->group,
  272.             $data->origem,
  273.             $data->token,
  274.             $data->fixedPhone ?? '',
  275.             $data->empreendimento ?? '',
  276.             $data->utm_source ?? '',
  277.             $data->utm_medium ?? '',
  278.             $data->utm_campaign ?? '',
  279.             $data->id_pipe ?? ''
  280.         );
  281.         $bus->dispatch($message);
  282.         return $this->sendStatus(200, "Lead criado");
  283.     }
  284.     /**
  285.      * @Route("/resend", name="front_product_lead_resend")
  286.      * @Method("POST")
  287.      */
  288.     public function resendLead(Request $request, MessageBusInterface $bus)
  289.     {
  290.         $entityManager = $this->getDoctrine()->getManager();
  291.         $data = json_decode($request->getContent(), true);
  292.         $leadsNotSent = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findBySendStatusAndProduct('Não', $data['productId']);
  293.         $product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->find($data['productId']);
  294.         if(!$leadsNotSent){
  295.             return $this->sendStatus(200, "Nenhum lead para reenviar");
  296.         }
  297.         foreach ($leadsNotSent as $lead) {
  298.         //     $payload = [
  299.         //         'token' => $product->getToken(),
  300.         //         'name' => $lead->getName(),
  301.         //         'email' => $lead->getEmail(),
  302.         //         'phone' => $lead->getPhone(),
  303.         //         'group' => $lead->getGroup(),
  304.         //         'origem' => $lead->getOrigem(),
  305.         //         'id_pipe' => $lead->getIdPipe()
  306.         //     ];
  307.         //     $this->reDispatch(json_encode($payload), $bus);
  308.             $lead->setSendStatus('Enviando');
  309.             $entityManager->flush();
  310.             $brokerEmail = $lead->getBrokerEmail();
  311.             $broker = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneByEmail($brokerEmail);
  312.             $realEstate = $this->getDoctrine()
  313.                         ->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
  314.                         ->findOneBy(['name' => $lead->getBrokerRealState()]);
  315.             $product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->find($data['productId']);
  316.             $productEmail = $product->getEmail();
  317.             $emailCopySend = [];
  318.             if ($realEstate) {
  319.                 if ($realEstate->getReceiveLead()) {
  320.                     $emailCopySend[] = $realEstate->getEmail();
  321.                 }
  322.             }
  323.             if (! empty($productEmail)) {
  324.                 $emailsSend = explode(',', str_replace(' ', '', $productEmail));
  325.                 foreach ($emailsSend as $sendMail) {
  326.                     $emailCopySend[] = $sendMail;
  327.                 }
  328.             }
  329.             // se não houver nenhum corretor para receber e-mail, o e-mail padrão
  330.             // da campanha é o destinatário principal
  331.             else if (! empty($productEmail)) {
  332.                 $emailsSend = explode(',', str_replace(' ', '', $productEmail));
  333.                 foreach ($emailsSend as $sendMail) {
  334.                     $emailCopySend[] = $sendMail;
  335.                 }
  336.             }
  337.             $conn = $this->getDoctrine()->getConnection();
  338.             $conn->insert('lead_queue', [
  339.                 'lead_id' => $lead->getId(),
  340.                 'broker_name' => $broker->getFirstName(),
  341.                 'broker_email' => $brokerEmail,
  342.                 'copy_emails' => implode(',', $emailCopySend),
  343.                 'status' => 'pendente',
  344.                 'created_at' => date('Y-m-d H:i:s'),
  345.                 'updated_at' => date('Y-m-d H:i:s'),
  346.             ]);
  347.         }
  348.         
  349.         $projectRoot = $this->get('kernel')->getProjectDir();
  350.         $phpPath = '/opt/plesk/php/7.4/bin/php';
  351.         exec("nohup $phpPath $projectRoot/bin/console resend:lead:worker > $projectRoot/var/log/worker.log 2>&1 &");
  352.         return $this->sendStatus(200, "Leads Enviados");
  353.     }
  354.     /**
  355.      * @Route("/resend/cronjob1", name="front_product_lead_resend_cronjob1")
  356.      * @Method("POST")
  357.      */
  358.     public function resendLeadCron1()
  359.     {
  360.         return $this->sendStatus(200, "Leads Enviados");
  361.         $entityManager = $this->getDoctrine()->getManager();
  362.         $leadsNotSent = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findBy(['send_status' => 'Não']);
  363.         foreach ($leadsNotSent as $lead) {
  364.             $lead->setSendStatus('Enviando');
  365.             $entityManager->flush();
  366.             $brokerEmail = $lead->getBrokerEmail();
  367.             $broker = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findByEmail($brokerEmail);
  368.             $conn = $this->getDoctrine()->getConnection();
  369.             $conn->insert('lead_queue_cron', [
  370.                 'lead_id' => $lead->getId(),
  371.                 'broker_name' => $broker['firstname'],
  372.                 'broker_email' => $brokerEmail,
  373.                 'status' => 'pendente',
  374.                 'created_at' => date('Y-m-d H:i:s'),
  375.                 'updated_at' => date('Y-m-d H:i:s'),
  376.             ]);
  377.         }
  378.         $projectRoot = $this->get('kernel')->getProjectDir();
  379.         $phpPath = '/usr/local/bin/php';
  380.         exec("nohup $phpPath $projectRoot/bin/console resend:lead:workerCron1 > $projectRoot/var/log/worker.log 2>&1 &");
  381.         $entityManager->flush();
  382.         return $this->sendStatus(200, "Leads Enviados");
  383.     }
  384.     /**
  385.      * @Route("/resend/cronjob2", name="front_product_lead_resend_cronjob2")
  386.      * @Method("POST")
  387.      */
  388.     public function resendLeadCron2()
  389.     {
  390.         return $this->sendStatus(200, "Notificações Enviadas");
  391.         
  392.         $projectRoot = $this->get('kernel')->getProjectDir();
  393.         $phpPath = '/usr/local/bin/php';
  394.         exec("nohup $phpPath $projectRoot/bin/console resend:lead:workerCron2 > $projectRoot/var/log/worker.log 2>&1 &");
  395.         return $this->sendStatus(200, "Notificações Enviadas");
  396.     }
  397. }