src/Application/Internit/LeadBundle/Service/ResendLeadWorkerCommand.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Application\Internit\LeadBundle\Service;
  3. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use App\Application\Internit\LeadBundle\Entity\LeadErrorLog;
  7. class ResendLeadWorkerCommand extends ContainerAwareCommand
  8. {
  9.     protected function configure()
  10.     {
  11.         $this
  12.             ->setName('resend:lead:worker')
  13.             ->setDescription('Consome fila de leads e envia e-mail');
  14.     }
  15.    protected function execute(InputInterface $inputOutputInterface $output)
  16.     {
  17.         $conn $this->getContainer()->get('doctrine')->getConnection();
  18.         $entityManager $this->getContainer()->get('doctrine')->getManager();
  19.         $rows $conn->fetchAllAssociative("SELECT * FROM lead_queue WHERE status = 'pendente'");
  20.         foreach ($rows as $row) {
  21.             
  22.             $entityManager->beginTransaction(); // Inicia a transação
  23.             
  24.             try {
  25.                 // 1. LIMPEZA DOS EMAILS DE CÓPIA
  26.                 $copyEmailsRaw explode(','$row['copy_emails']);
  27.                 // Filtra e-mails vazios ou nulos (soluciona o Address in mailbox given [] error)
  28.                 $copyEmails array_filter($copyEmailsRaw, function($email) {
  29.                     return !empty(trim($email));
  30.                 });
  31.                 $lead $entityManager->getRepository('ApplicationInternitLeadBundle:Lead')->find($row['lead_id']);
  32.                 if (!$lead) {
  33.                     $conn->update('lead_queue', ['status' => 'falhou''updated_at' => date('Y-m-d H:i:s')], ['id' => $row['id']]);
  34.                     $entityManager->commit(); 
  35.                     continue;
  36.                 }
  37.                 $html $this->getContainer()->get('templating')->render(
  38.                     '@ApplicationInternit/SettingBundle/Resources/views/Mail/emailLead.html.twig',
  39.                     ['data' => $lead'corretor' => $row['broker_name']]
  40.                 );
  41.                 $enviado false;
  42.                 // Primeira tentativa
  43.                 try {
  44.                     $mailer1 $this->getContainer()->get('admin.mail.service');
  45.                     $mailer1->setMessage()
  46.                         ->setTo($row['broker_email'] ?? $lead->getProduct()->getEmail())
  47.                         ->setCC($copyEmails// Array filtrado!
  48.                         // ... (restante do setSubject e setBody) ...
  49.                         ->setSubject("[leadcalper] " $lead->getProduct()->getName() . ' - ' $lead->getGroup() . ' - ' $row['broker_name'])
  50.                         ->setBody($html'text/html');
  51.                     $mailer1->send();
  52.                     $lead->setSendStatus('Sim 1');
  53.                     $enviado true;
  54.                 } catch (\Exception $e1) {
  55.                     // ... (log de erro 1) ...
  56.                     try {
  57.                         $mailer2 $this->getContainer()->get('admin.mail.service2');
  58.                         $mailer2->setMessage()
  59.                             ->setTo($row['broker_email'] ?? $lead->getProduct()->getEmail())
  60.                             ->setCc($copyEmails// Array filtrado!
  61.                             // ... (restante do setSubject e setBody) ...
  62.                             ->setSubject("[leadcalper] " $lead->getProduct()->getName() . ' - ' $lead->getGroup() . ' - ' $row['broker_name'])
  63.                             ->setBody($html'text/html')
  64.                             ->send();
  65.                         $lead->setSendStatus('Sim 2');
  66.                         $enviado true;
  67.                     } catch (\Exception $e2) {
  68.                         // Ambos falharam
  69.                         $lead->setSendStatus('Não');
  70.                         $output->writeln("Lead {$row['lead_id']} falhou nos dois envios.");
  71.                         $output->writeln($e2); // Log da última exceção
  72.                     }
  73.                 }
  74.                 
  75.                 // Persiste o status final do Lead
  76.                 $entityManager->persist($lead);
  77.                 if ($enviado) {
  78.                     $conn->delete('lead_queue', ['id' => $row['id']]);
  79.                     $output->writeln("Lead {$row['lead_id']} enviado com sucesso. Status: {$lead->getSendStatus()}");
  80.                 } else {
  81.                      // Atualiza o status da fila como falhou
  82.                     $conn->update('lead_queue', [
  83.                         'status' => 'falhou',
  84.                         'updated_at' => date('Y-m-d H:i:s')
  85.                     ], ['id' => $row['id']]);
  86.                 }
  87.                 // Finaliza a transação e salva Lead e Fila
  88.                 $entityManager->flush();
  89.                 $entityManager->commit();
  90.                 
  91.             } catch (\Exception $e) {
  92.                 // Em caso de qualquer erro inesperado, faça rollback
  93.                 if ($entityManager->getConnection()->isTransactionActive()) {
  94.                     $entityManager->rollback();
  95.                 }
  96.                 
  97.                 // Atualiza a fila como falha
  98.                 $conn->update('lead_queue', ['status' => 'falhou''updated_at' => date('Y-m-d H:i:s')], ['id' => $row['id']]);
  99.                 $output->writeln("Erro inesperado no lead ID {$row['lead_id']}: " $e->getMessage());
  100.             }
  101.         }
  102.         $output->writeln("Processamento finalizado.");
  103.         
  104.         return 0
  105.     }
  106. }