<?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\Message\LeadMessage;
use Symfony\Component\Messenger\MessageBusInterface;
use App\Application\Internit\LeadBundle\Entity\ChatbotLead;
use App\Application\Internit\LeadBundle\Entity\TemporaryLead;
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("/getLead", name="front_product_lead_send_get")
* @Method("GET")
*/
public function getLead(Request $request)
{
$id_pipe = $request->get('id_pipe');
$response = [];
if($id_pipe){
try {
$lead = $this->getDoctrine()
->getRepository('ApplicationInternitLeadBundle:Lead')
->findByIdPipe(intval($id_pipe));
if (!$lead) {
return $this->sendStatus(404, "Lead não encontrado.");
}
$broker = $this->getDoctrine()
->getRepository('ApplicationSonataUserBundle:User')
->findOneByEmail($lead->getBrokerEmail());
if (!$broker) {
return $this->sendStatus(404, "Corretor associado não encontrado.");
}
$response = [
'Broker_Name' => $broker->getFirstName(),
'Realstate_Name' => $lead->getBrokerRealState()
];
return $this->sendStatus(200, "Dados recuperados com sucesso.", $response);
} catch (\Exception $e) {
return new \Symfony\Component\HttpFoundation\JsonResponse([
'status' => 500,
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
], 500);
}
}
}
/**
* @Route("/send", name="front_product_lead_send")
* @Method("POST")
*/
public function send(Request $request, MessageBusInterface $bus)
{
$data = json_decode($request->getContent());
if (!$data) {
return $this->sendStatus(400, "New Lead is not valid");
}
if (isset($data->token)) {
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 : '';
$id_pipe = isset($data->id_pipe) ? intval($data->id_pipe) : '';
$message = new LeadMessage(
$data->name,
$emailLead,
$phoneLead,
$data->group,
$data->origem,
$data->token,
$data->fixedPhone ?? '',
$data->empreendimento ?? '',
$data->utm_source ?? '',
$data->utm_medium ?? '',
$data->utm_campaign ?? '',
$id_pipe
);
$bus->dispatch($message);
return $this->sendStatus(200, "Lead criado");
} else {
return $this->sendStatus(400, "Invalid content");
}
}
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 ?? '',
]);
}
public function reDispatch($payload, MessageBusInterface $bus){
$data = json_decode($payload);
$emailLead = isset($data->email) ? $data->email : '';
$phoneLead = isset($data->phone) ? $data->phone : '';
$message = new LeadMessage(
$data->name,
$emailLead,
$phoneLead,
$data->group,
$data->origem,
$data->token,
$data->fixedPhone ?? '',
$data->empreendimento ?? '',
$data->utm_source ?? '',
$data->utm_medium ?? '',
$data->utm_campaign ?? '',
$data->id_pipe ?? ''
);
$bus->dispatch($message);
return $this->sendStatus(200, "Lead criado");
}
/**
* @Route("/resend", name="front_product_lead_resend")
* @Method("POST")
*/
public function resendLead(Request $request, MessageBusInterface $bus)
{
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), true);
$leadsNotSent = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Lead')->findBySendStatusAndProduct('Não', $data['productId']);
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->find($data['productId']);
if(!$leadsNotSent){
return $this->sendStatus(200, "Nenhum lead para reenviar");
}
foreach ($leadsNotSent as $lead) {
// $payload = [
// 'token' => $product->getToken(),
// 'name' => $lead->getName(),
// 'email' => $lead->getEmail(),
// 'phone' => $lead->getPhone(),
// 'group' => $lead->getGroup(),
// 'origem' => $lead->getOrigem(),
// 'id_pipe' => $lead->getIdPipe()
// ];
// $this->reDispatch(json_encode($payload), $bus);
$lead->setSendStatus('Enviando');
$entityManager->flush();
$brokerEmail = $lead->getBrokerEmail();
$broker = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')->findOneByEmail($brokerEmail);
$realEstate = $this->getDoctrine()
->getRepository('ApplicationInternitRealEstateBundle:RealEstate')
->findOneBy(['name' => $lead->getBrokerRealState()]);
$product = $this->getDoctrine()->getRepository('ApplicationInternitLeadBundle:Product')->find($data['productId']);
$productEmail = $product->getEmail();
$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->getFirstName(),
'broker_email' => $brokerEmail,
'copy_emails' => implode(',', $emailCopySend),
'status' => 'pendente',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
$projectRoot = $this->get('kernel')->getProjectDir();
$phpPath = '/opt/plesk/php/7.4/bin/php';
exec("nohup $phpPath $projectRoot/bin/console resend:lead:worker > $projectRoot/var/log/worker.log 2>&1 &");
return $this->sendStatus(200, "Leads Enviados");
}
/**
* @Route("/resend/cronjob1", name="front_product_lead_resend_cronjob1")
* @Method("POST")
*/
public function resendLeadCron1()
{
return $this->sendStatus(200, "Leads Enviados");
$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'),
'updated_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()
{
return $this->sendStatus(200, "Notificações Enviadas");
$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");
}
}