<?php
namespace App\Application\Internit\LeadBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Application\Internit\LeadBundle\Entity\Lead;
use App\Application\Internit\LeadBundle\Entity\LeadErrorLog;
use App\Application\Internit\LeadBundle\Entity\ChatbotLead;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Swift_SmtpTransport;
use Swift_Mailer;
use Swift_Message;
/**
* Product Front controller.
*
* @Route("/api/leads")
*/
class ProductFrontController extends Controller
{
public function getBundleName()
{
return 'ApplicationInternitLeadBundle';
}
public function getEntityName()
{
return 'Product';
}
public function getFormType()
{
return 'App\Application\Internit\LeadBundle\Form\ProductType';
}
/**
* @Route("/send", name="front_product_lead_send")
* @Method("POST")
*/
public function send(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent());
$statusCode = 400;
$result = [];
if (!$data) {
// $this->handleLeadError(null, null, null, 'Novo Lead não é válido.');
return $this->sendStatus(400, "New Lead is not valid");
}
if (isset($data->token)) {
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneByToken($data->token);
if (!$product) {
// $this->handleLeadError(null, null, null, 'ID da campanha não encontrado.');
return $this->sendStatus(404, "Product not found");
}
if (
!empty($data->name) &&
!empty($data->origem) &&
!empty($data->group)
) {
// form de whatsapp não traz e-mail
$emailLead = isset($data->email) ? $data->email : '';
$phoneLead = isset($data->phone) ? $data->phone : '';
$extraInfo = array();
$to = $this->get('tupi.caster.service')->next($product, $emailLead, $phoneLead);
//dd($to);
// dump($to);exit;
$newLead = new Lead();
//Obrigatórios
$newLead->setName($data->name);
$newLead->setGroup($data->group);
$newLead->setOrigem($data->origem);
$newLead->setProduct($product);
$newLead->setEmail($emailLead);
$newLead->setPhone($phoneLead);
if (!empty($this->getDoctrine()->getRepository("ApplicationInternitLeadBundle:Lead")->attended($emailLead, $phoneLead, $product->getCorretores()))) {
$newLead->setLoyalty(true);
}
//Opcionais
if (isset($data->fixedPhone)) {
$newLead->setFixedPhone(($data->fixedPhone ? $data->fixedPhone : ''));
}
if (isset($data->empreendimento))
$newLead->setEmpreendimento(($data->empreendimento ? $data->empreendimento : ''));
if (isset($data->utm_source))
$newLead->setUtm_source(($data->utm_source ? $data->utm_source : ''));
if (isset($data->utm_medium))
$newLead->setUtm_medium(($data->utm_medium ? $data->utm_medium : ''));
if (isset($data->utm_campaign))
$newLead->setUtm_campaign(($data->utm_campaign ? $data->utm_campaign : ''));
if (isset($data->message))
$newLead->setMessage(($data->message ? $data->message : ''));
// e-mail que a construtora configura para receber os leads deste produto.
$productEmail = $product->getEmail();
if (!empty($productEmail) || !is_null($to)) {
// obter e-mails de lead da imobiliária da vez
$realEstateLeadEmails = $this->getDoctrine()
->getRepository('ApplicationInternitLeadBundle:RealEstateEmail')
->findRealEstateLeadEmails($to['imob']);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $to['imob']]);
//Chamar service de disparo para corretor
$email1 = $this->get('admin.mail.service');
//$email2 = $this->get('admin.mail.service');
// EMAILS COPY
$emailCopySend = [];
$emailToSend = [];
if ($realEstate) {
if ($realEstate->getReceiveLead()) {
$emailCopySend[] = $realEstate->getEmail();
//$email->setMessage()->setBCC($realEstate->getEmail());
}
}
if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
}
// se houver o e-mail do corretor, ele é o destinatário principal e
// o e-mail padrão da campanha é cópia oculta
if (!empty($to['email'])) {
// $email1->setMessage()->setTo($to['email']);
$emailToSend[] = $to['email'];
//dd($realEstate);
// if (!empty($emailCopySend)) {
// $email1->setMessage()->setCC($emailCopySend);
// }
}
// se não houver nenhum corretor para receber e-mail, o e-mail padrão
// da campanha é o destinatário principal
else if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
// $email1->setMessage()->setTo($emailsSend);
$emailToSend[] = $emailsSend;
// if (!empty($emailCopySend)) {
// $email1->setMessage()->setCC($emailCopySend);
// }
}
// if (!empty($realEstateLeadEmails)) {
// $email->setMessage()->setCC($realEstateLeadEmails);
// }
$newLead->setBrokerEmail(! empty($to['email']) ? $to['email'] : $productEmail); //Seta email do corretor que recebeu o lead
$newLead->setBrokerRealState($to['imob']); //Seta Imobiliaria do corretor que recebeu o lead
$extraInfo['broker_name'] = $to['name'];
//if($to['phone'])
// $extraInfo['broker_phone'] = preg_replace('/[^0-9]/', '', $to['phone']);
$extraInfo['realstate_name'] = $to['imob']; //strtoupper()
$newLead->setSendStatus('Enviando');
$entityManager->persist($newLead);
$entityManager->flush();
$this->get('tupi.caster.service')->gerarLogDistribuicao($product);
// Insere na fila
$conn = $this->getDoctrine()->getConnection();
$conn->insert('lead_queue', [
'lead_id' => $newLead->getId(),
'broker_name' => $to['name'],
'broker_email' => $to['email'] ?? $productEmail,
'copy_emails' => implode(',', $emailCopySend),
'status' => 'pendente',
'created_at' => date('Y-m-d H:i:s'),
]);
// Inicia o worker em background (se quiser garantir que ele esteja rodando)
$projectRoot = $this->get('kernel')->getProjectDir();
$phpPath = '/usr/local/bin/php';
exec("nohup $phpPath $projectRoot/bin/console resend:lead:worker > $projectRoot/var/log/worker.log 2>&1 &");
return $this->sendStatus(200, "Lead criado ", $extraInfo);
// try {
// $this->get('tupi.caster.service')->gerarLogDistribuicao($product);
// $email1
// ->setMessage()
// ->setSubject("[leadcalper] " . $product->getName() . ' - ' . $newLead->getGroup() . ' - ' . $to['name'])
// ->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
// 'data' => $newLead,
// 'corretor' => $to['name'],
// )), 'text/html');
// $email1->send();
// $newLead->setSendStatus('Sim 1');
// $entityManager->persist($newLead);
// $entityManager->flush();
// } catch (\Exception $e) {
// $this->handleLeadError($newLead, $to['name'], $to['email'], 'Erro ao enviar o e-mail: ');
// $entityManager->flush();
// return $this->sendStatus(200, "Lead created", $extraInfo);
// }
/* $email2
->setMessage()
->setSubject("[Lead] ".$product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email2->send();*/
}
// dump($newLead);
// return $this->sendStatus(200, "Lead created", $extraInfo);
} else {
// $this->handleLeadError(null, null, null, 'Conteúdo inválido, preencha os campos obrigatórios.');
return $this->sendStatus(400, "Invalid content");
}
}
// $this->handleLeadError(null, null, null, 'O token é obrigatório.');
return $this->sendStatus(400, "Token is required");
}
public function sendLast(Request $request)
{
$data = json_decode($request->getContent());
$statusCode = 400;
$result = [];
if (!$data)
return $this->sendStatus(400, "New Lead is not valid");
if (isset($data->token)) {
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->findOneByToken($data->token);
// dump($product); exit;
if (!$product)
return $this->sendStatus(404, "Product not found");
if (
!empty($data->name) &&
!empty($data->origem) &&
!empty($data->group)
) {
// form de whatsapp não traz e-mail
$emailLead = isset($data->email) ? $data->email : '';
$phoneLead = isset($data->phone) ? $data->phone : '';
$extraInfo = array();
$to = $this->get('tupi.caster.service')->next($product, $emailLead, $phoneLead);
//dd($to);
// dump($to);exit;
$newLead = new Lead();
//Obrigatórios
$newLead->setName($data->name);
$newLead->setGroup($data->group);
$newLead->setOrigem($data->origem);
$newLead->setProduct($product);
$newLead->setEmail($emailLead);
$newLead->setPhone($phoneLead);
//Opcionais
if (isset($data->fixedPhone)) {
$newLead->setFixedPhone(($data->fixedPhone ? $data->fixedPhone : ''));
}
if (isset($data->empreendimento))
$newLead->setEmpreendimento(($data->empreendimento ? $data->empreendimento : ''));
if (isset($data->utm_source))
$newLead->setUtm_source(($data->utm_source ? $data->utm_source : ''));
if (isset($data->utm_medium))
$newLead->setUtm_medium(($data->utm_medium ? $data->utm_medium : ''));
if (isset($data->utm_campaign))
$newLead->setUtm_campaign(($data->utm_campaign ? $data->utm_campaign : ''));
if (isset($data->message))
$newLead->setMessage(($data->message ? $data->message : ''));
// e-mail que a construtora configura para receber os leads deste produto.
$productEmail = $product->getEmail();
if (!empty($productEmail) || !is_null($to)) {
// obter e-mails de lead da imobiliária da vez
$realEstateLeadEmails = $this->getDoctrine()
->getRepository('ApplicationInternitLeadBundle:RealEstateEmail')
->findRealEstateLeadEmails($to['imob']);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $to['imob']]);
//Chamar service de disparo para corretor
$email1 = $this->get('admin.mail.service');
$email2 = $this->get('admin.mail.service');
// EMAILS COPY
$emailCopySend = [];
if ($realEstate) {
if ($realEstate->getReceiveLead()) {
$emailCopySend[] = $realEstate->getEmail();
//$email->setMessage()->setBCC($realEstate->getEmail());
}
}
if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
}
// se houver o e-mail do corretor, ele é o destinatário principal e
// o e-mail padrão da campanha é cópia oculta
if (!empty($to['email'])) {
$email1->setMessage()->setTo($to['email']);
//dd($realEstate);
if (!empty($emailCopySend)) {
$email2->setMessage()->setTo($emailCopySend);
}
}
// se não houver nenhum corretor para receber e-mail, o e-mail padrão
// da campanha é o destinatário principal
else if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
//$email->setMessage()->setBCC($sendMail);
}
$email1->setMessage()->setTo($emailsSend);
if (!empty($emailCopySend)) {
$email2->setMessage()->setTo($emailCopySend);
}
}
// if (!empty($realEstateLeadEmails)) {
// $email->setMessage()->setCC($realEstateLeadEmails);
// }
$newLead->setBrokerEmail(! empty($to['email']) ? $to['email'] : $productEmail); //Seta email do corretor que recebeu o lead
$newLead->setBrokerRealState($to['imob']); //Seta Imobiliaria do corretor que recebeu o lead
$extraInfo['broker_name'] = $to['name'];
if ($to['phone'])
$extraInfo['broker_phone'] = preg_replace('/[^0-9]/', '', $to['phone']);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($newLead);
$entityManager->flush();
$email1
->setMessage()
->setSubject("[Lead] " . $product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email1->send();
$email2
->setMessage()
->setSubject("[Lead] " . $product->getName() . ' - ' . $newLead->getGroup())
->setBody($this->renderView("@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig", array(
'data' => $newLead,
)), 'text/html');
$email2->send();
}
// dump($newLead);
return $this->sendStatus(200, "Lead created", $extraInfo);
} else {
return $this->sendStatus(400, "Invalid content");
}
}
return $this->sendStatus(400, "Token is required");
}
private function sendStatus($code = 401, $message = "Requisição não autorizada", $extra = array())
{
$array = array('message' => $message);
$array = array_merge($array, $extra);
$response = new Response(json_encode($array), $code);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
private function handleBodyView($lead = null, $brokerName = null)
{
return $this->renderView('@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig', [
'data' => $lead ?? '',
'corretor' => $brokerName ?? '',
]);
}
private function handleLeadError($lead = null, $brokerName = null, $brokerEmail = null, $errorMessage = null)
{
$entityManager = $this->getDoctrine()->getManager();
$html = $this->handleBodyView($lead, $brokerName);
if (empty($lead) && empty($brokerEmail)) {
$log = new LeadErrorLog();
$log->setLead($lead ?? null);
$log->setErrorMessage($errorMessage);
$log->setErrorType('Server Error');
$log->setCreatedAt(new \DateTime());
$entityManager->persist($log);
$lead->setSendStatus('Não');
$entityManager->persist($lead);
$entityManager->flush();
return;
}
// // Tentativa 1
try {
$mailer1 = $this->get('admin.mail.service');
$mailer1->setMessage()
->setTo($brokerEmail ?? $lead->getProduct()->getEmail())
->setSubject("[leadcalper] " . $lead->getProduct()->getName() . ' -' . $lead->getGroup() . ' - ' . $brokerName)
->setBody(
$html,
'text/html'
);
$mailer1->send();
$lead->setSendStatus('Sim 1');
$entityManager->persist($lead);
} catch (\Exception $e) {
// Tentativa 2
try{
$mailer2 = $this->get('admin.mail.service2');
$mailer2->setMessage()
->setTo($brokerEmail ?? $lead->getProduct()->getEmail())
->setSubject("[leadcalper] " . $lead->getProduct()->getName() . $lead->getGroup() . ' - ' . $brokerName)
->setBody($html, 'text/html')
->send();
$lead->setSendStatus('Sim 2');
$entityManager->persist($lead);
}catch(\Exception $e){
$log = new LeadErrorLog();
$log->setLead($lead ?? null);
$log->setErrorMessage($errorMessage);
$log->setErrorType('Email');
$log->setCreatedAt(new \DateTime());
$entityManager->persist($log);
$lead->setSendStatus('Não');
$entityManager->persist($lead);
}
}
}
/**
* @Route("/resend", name="front_product_lead_resend")
* @Method("POST")
*/
public function resendLead(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), true);
$leadsNotSent = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findBySendStatusAndProduct('Não', $data['productId']);
foreach ($leadsNotSent as $lead) {
$lead->setSendStatus('Enviando');
$entityManager->flush();
$brokerEmail = $lead->getBrokerEmail();
$broker = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findByEmail($brokerEmail);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $lead->getBrokerRealState()]);
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->find($data['productId']);
$productEmail = $product->getEmail();
// COPY EMAILS
$emailCopySend = [];
if ($realEstate) {
if ($realEstate->getReceiveLead()) {
$emailCopySend[] = $realEstate->getEmail();
}
}
if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
}
}
// se não houver nenhum corretor para receber e-mail, o e-mail padrão
// da campanha é o destinatário principal
else if (! empty($productEmail)) {
$emailsSend = explode(',', str_replace(' ', '', $productEmail));
foreach ($emailsSend as $sendMail) {
$emailCopySend[] = $sendMail;
}
}
$conn = $this->getDoctrine()->getConnection();
$conn->insert('lead_queue', [
'lead_id' => $lead->getId(),
'broker_name' => $broker['firstname'],
'broker_email' => $brokerEmail,
'copy_emails' => implode(',', $emailCopySend),
'status' => 'pendente',
'created_at' => date('Y-m-d H:i:s'),
]);
}
$projectRoot = $this->get('kernel')->getProjectDir();
$phpPath = '/usr/local/bin/php';
exec("nohup $phpPath $projectRoot/bin/console resend:lead:worker > $projectRoot/var/log/worker.log 2>&1 &");
$entityManager->flush();
return $this->sendStatus(200, "Leads Enviados");
}
/**
* @Route("/resend/cronjob1", name="front_product_lead_resend_cronjob1")
* @Method("POST")
*/
public function resendLeadCron1()
{
$entityManager = $this->getDoctrine()->getManager();
$leadsNotSent = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findBy(['send_status' => 'Não']);
foreach ($leadsNotSent as $lead) {
$lead->setSendStatus('Enviando');
$entityManager->flush();
$brokerEmail = $lead->getBrokerEmail();
$broker = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findByEmail($brokerEmail);
$conn = $this->getDoctrine()->getConnection();
$conn->insert('lead_queue_cron', [
'lead_id' => $lead->getId(),
'broker_name' => $broker['firstname'],
'broker_email' => $brokerEmail,
'status' => 'pendente',
'created_at' => date('Y-m-d H:i:s'),
]);
}
$projectRoot = $this->get('kernel')->getProjectDir();
$phpPath = '/usr/local/bin/php';
exec("nohup $phpPath $projectRoot/bin/console resend:lead:workerCron1 > $projectRoot/var/log/worker.log 2>&1 &");
$entityManager->flush();
return $this->sendStatus(200, "Leads Enviados");
}
/**
* @Route("/resend/cronjob2", name="front_product_lead_resend_cronjob2")
* @Method("POST")
*/
public function resendLeadCron2()
{
$projectRoot = $this->get('kernel')->getProjectDir();
$phpPath = '/usr/local/bin/php';
exec("nohup $phpPath $projectRoot/bin/console resend:lead:workerCron2 > $projectRoot/var/log/worker.log 2>&1 &");
return $this->sendStatus(200, "Notificações Enviadas");
}
}