src/MDS/GreenPatioBundle/Controller/ReservationsScheduleTaskController.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\MDS\GreenPatioBundle\Controller;
  3. use App\MDS\GreenPatioBundle\Entity\ReservationDeposit;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use App\MDS\GreenPatioBundle\Entity\Reservation;
  7. use DateTime;
  8. use App\Entity\Client;
  9. use App\Entity\ClientContact;
  10. use App\Entity\User;
  11. use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
  12. use Swift_Mailer;
  13. use Swift_Message;
  14. use Swift_SmtpTransport;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. class ReservationsScheduleTaskController extends AbstractController
  18. {
  19.     /**
  20.      * @Route("/remindernodeposit", name="reservations_reminder_no_deposit")
  21.      * Recordatorio de expedientes confirmados sin depositos
  22.      */
  23.     public function reminderNoDepositAction(EntityManagerInterface $em)
  24.     {
  25.         // Los días lunes se enviará un recordatorio por correo
  26.         $today = new DateTime('now');
  27.         $reminder = ($today->format('N') == 1);
  28.         if (!$reminder){ return new JsonResponse('Done'); }
  29.         $resConfirmed $em->getRepository(Reservation::class)->findBy(array('status' => 'Confirmed'));
  30.         $arrayNotify = array();     // array( 'Id de agente a notificar' =>'Info del agente', array ('Id del expediente pendiente' => expediente, cliente y contacto del cliente  ) )
  31.         foreach ($resConfirmed as $item){
  32.             $idCreator $item->getCreatedBy();
  33.             $agentCreator $em->getRepository(User::class)->findOneById($idCreator);
  34.             $idUpdator $item->getUpdatedBy();
  35.             $agentUpdator $em->getRepository(User::class)->findOneById($idUpdator);
  36.             if(!empty($item->getClient())){ $client $em->getRepository(Client::class)->findOneById($item->getClient()); } else { $client null; }
  37.             if(!empty($client)){ $clientContact $em->getRepository(ClientContact::class)->findOneByClientId($client->getId()); } else { $clientContact null; }
  38.             $resDeposits $em->getRepository(ReservationDeposit::class)->findByReservationId($item->getId());
  39.             if (empty($resDeposits)) {
  40.                 $arrayNotify[$idCreator]['agente'] = $agentCreator;
  41.                 $arrayNotify[$idCreator]['expedientes'][$item->getId()] = array('expediente' => $item'Cliente' => $client'ClientContact' => $clientContact,);
  42.                 $arrayNotify[$idUpdator]['agente'] = $agentUpdator;
  43.                 $arrayNotify[$idUpdator]['expedientes'][$item->getId()] = array('expediente' => $item'Cliente' => $client'ClientContact' => $clientContact,);
  44.             }
  45.         }
  46.         // Enviamos los correos a los agentes
  47.         $texto ''$textoSimple '';
  48.         foreach ($arrayNotify as $item){
  49.             //Creamos el texto con la lista de reservas
  50.             foreach ($item['expedientes'] as $elem){
  51.                 $clientName = (!empty($elem['Cliente'])) ? $elem['Cliente']->getName() : 'No se encontró información del cliente';
  52.                 $clientContactName = (!empty($elem['ClientContact'])) ? $elem['ClientContact']->getName() .' '$elem['ClientContact']->getLastName().'( '.$elem['ClientContact']->getEmail().' )' 'No se encontró información del contacto';
  53.                 $texto $texto '<a href="//' $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>''  ||  '$elem['expediente']->getTitle() . '  ||  '$elem['expediente']->getDateStart()->format('d/m/Y') .'  ||  '$clientName.'  ||  '$clientContactName;
  54.                 $texto $texto .'<br>';
  55.                 $textoSimple $textoSimple '<a href="//' $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>''  ||  '$elem['expediente']->getTitle();
  56.                 $textoSimple $textoSimple .'<br>';
  57.             }
  58.             $texto 'Estos son los expedientes creados o modificados por el agente, que requieren de su atención<br><br>Id exp  ||  Nombre del expediente  ||  Fecha de inicio  ||  Cliente  ||  Contacto del cliente<br>'$texto;
  59.             $textoSimple 'Estos son los expedientes que requieren de su atención<br><br>Id exp  ||  Nombre del expediente <br>'$textoSimple;
  60.             // Alertar por Telegram y correo al agente, cc a Esteban y admin
  61.             if (!empty($item['agente'])){ $this->sendTelegramMailSimple($item['agente']->getId(), 'Expedientes confirmados sin deposito del agente: '$item['agente']->getName().' '.$item['agente']->getLastName(), $texto$textoSimple); } // El agente puede estar de baja o ya fuera de la empresa
  62.             if (!empty($item['agente'])){ $nombreAgente $item['agente']->getName().' '.$item['agente']->getLastName(); } else { $nombreAgente 'No se pudo determinar el nombre del agente'; }
  63.             $this->sendTelegramMailSimple(31'Expedientes de Green Patio confirmados sin deposito del agente: '$nombreAgente$texto$textoSimple);         // Notificacion a Esteban
  64.             $this->sendTelegramMailSimple(33'Expedientes de Green Patio confirmados sin deposito del agente: '$nombreAgente$texto$textoSimple);         // Notificacion a admin (mail admon@avexpress.tv, pero se notificará a administracion@greenpatio.es )
  65.             $texto '';
  66.         }
  67.         return new JsonResponse('Done');
  68.     }
  69.     /**
  70.      * @Route("/remindernoinvoiced", name="reservations_reminder_no_invoiced")
  71.      * Recordatorio de expedientes sin factura
  72.      */
  73.     public function reminderNoInvoicedAction(EntityManagerInterface $em)
  74.     {
  75.         // El primer día del mes se enviará un recordatorio por correo
  76.         $today = new DateTime('now');
  77.         $oneYearAgo = (clone $today)->modify('-1 year');
  78.         $reminder = ($today->format('d') == 1);
  79.         if (!$reminder){ return new JsonResponse('Done'); }
  80.         $queryBuilder $em->getRepository(Reservation::class)->createQueryBuilder('r');
  81.         $queryBuilder->where('r.status IN (:statuses)')
  82.             ->andWhere('r.dateEnd < :today')
  83.             ->andWhere('r.dateEnd > :oneYearAgo')
  84.             ->setParameter('statuses', ['Confirmed''Bloqueo'])
  85.             ->setParameter('today'$today)
  86.             ->setParameter('oneYearAgo'$oneYearAgo);
  87.         $resConfirmed $queryBuilder->getQuery()->getResult();
  88.         $arrayNotify = array();     // array( 'Id de agente a notificar' =>'Info del agente', array ('Id del expediente pendiente' => expediente, cliente y contacto del cliente  ) )
  89.         foreach ($resConfirmed as $item){
  90.             $idCreator $item->getCreatedBy();
  91.             $agentCreator $em->getRepository(User::class)->findOneById($idCreator);
  92.             $idUpdator $item->getUpdatedBy();
  93.             $agentUpdator $em->getRepository(User::class)->findOneById($idUpdator);
  94.             if(!empty($item->getClient())){ $client $em->getRepository(Client::class)->findOneById($item->getClient()); } else { $client null; }
  95.             if(!empty($client)){ $clientContact $em->getRepository(ClientContact::class)->findOneByClientId($client->getId()); } else { $clientContact null; }
  96.             $resDeposits $em->getRepository(ReservationDeposit::class)->findByReservationId($item->getId());
  97.             if (empty($resDeposits)) {
  98.                 $arrayNotify[$idCreator]['agente'] = $agentCreator;
  99.                 $arrayNotify[$idCreator]['expedientes'][$item->getId()] = array('expediente' => $item'Cliente' => $client'ClientContact' => $clientContact,);
  100.                 $arrayNotify[$idUpdator]['agente'] = $agentUpdator;
  101.                 $arrayNotify[$idUpdator]['expedientes'][$item->getId()] = array('expediente' => $item'Cliente' => $client'ClientContact' => $clientContact,);
  102.             }
  103.         }
  104.         // Enviamos los correos a los agentes
  105.         $texto ''$textoSimple '';
  106.         foreach ($arrayNotify as $item){
  107.             //Creamos el texto con la lista de reservas
  108.             foreach ($item['expedientes'] as $elem){
  109.                 $clientName = (!empty($elem['Cliente'])) ? $elem['Cliente']->getName() : 'No se encontró información del cliente';
  110.                 $clientContactName = (!empty($elem['ClientContact'])) ? $elem['ClientContact']->getName() .' '$elem['ClientContact']->getLastName().'( '.$elem['ClientContact']->getEmail().' )' 'No se encontró información del contacto';
  111.                 $texto $texto '<a href="//' $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>''  ||  '$elem['expediente']->getTitle() . '  ||  '$elem['expediente']->getDateStart()->format('d/m/Y') .'  ||  '$clientName.'  ||  '$clientContactName;
  112.                 $texto $texto .'<br>';
  113.                 $textoSimple $textoSimple '<a href="//' $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>''  ||  '$elem['expediente']->getTitle();
  114.                 $textoSimple $textoSimple .'<br>';
  115.             }
  116.             $texto 'Estos son los expedientes creados o modificados por el agente, que requieren de su atención<br><br>Id exp  ||  Nombre del expediente  ||  Fecha de inicio  ||  Cliente  ||  Contacto del cliente<br>'$texto;
  117.             $textoSimple 'Estos son los expedientes que requieren de su atención<br><br>Id exp  ||  Nombre del expediente <br>'$textoSimple;
  118.             // Alertar por Telegram y correo al agente, cc a Esteban y admin
  119.             if (!empty($item['agente'])){ $this->sendTelegramMailSimple($item['agente']->getId(), 'Expedientes sin facturar del agente: '$item['agente']->getName().' '.$item['agente']->getLastName(), $texto$textoSimple); }  // El agente puede estar de baja o ya fuera de la empresa
  120.             if (!empty($item['agente'])){ $nombreAgente $item['agente']->getName().' '.$item['agente']->getLastName(); } else { $nombreAgente 'No se pudo determinar el nombre del agente'; }
  121.             $this->sendTelegramMailSimple(31'Expedientes de Green Patio sin facturar del agente: '$nombreAgente$texto$textoSimple);     // Notificacion a Esteban
  122.             $this->sendTelegramMailSimple(33'Expedientes de Green Patio sin facturar del agente: '$nombreAgente$texto$textoSimple);     // Notificacion a admin (mail admon@avexpress.tv, pero se notificará a administracion@greenpatio.es )
  123.             $texto '';
  124.         }
  125.         return new JsonResponse('Done');
  126.     }
  127.     private function sendTelegramMailSimple($id$subject$text$textTelegram)
  128.     {
  129.         $em $this->getDoctrine()->getManager();
  130.         $telegUser $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
  131. //        if (!empty($telegUser)) {
  132.         if (false) {
  133. //            $xbody = '<a href="//' . $_SERVER['HTTP_HOST'] . '/higotrigo/ht/file/' . $idProp . '/edit"></a> ' . $text;
  134. //            $text = 'NUEVO EXPEDIENTE - ' . 'https://' . $_SERVER['HTTP_HOST'] . '/higotrigo/ht/file/' . $idProp . '/edit';
  135.             $parameters = array('chat_id' => $telegUser->getChatId(), 'text' => $textTelegram,);
  136.             $bot_token $telegUser->getBotToken();
  137.             $url "https://api.telegram.org/bot$bot_token/sendMessage";
  138.             if (!$curl curl_init()) { exit(); }
  139.             curl_setopt($curlCURLOPT_POSTtrue);
  140.             curl_setopt($curlCURLOPT_POSTFIELDS$parameters);
  141.             curl_setopt($curlCURLOPT_URL$url);
  142.             curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  143.             $output curl_exec($curl);
  144.             curl_close($curl);
  145.         }
  146.         $agent $em->getRepository(User::class)->findOneById($id);
  147.         $agentMail = ($agent->getEmail() == 33) ? 'administracion@greenpatio.es' $agent->getEmail();      // Notificacion a admin (mail admon@avexpress.tv, pero se notificará a administracion@greenpatio.es )
  148.         $mailAgent $agentMail;
  149.         //Se prepara el correo con los agentes a notificar
  150.         $firmGmail $agent->getFirmGmail();
  151.         $data = array(
  152.             'body' => $text,
  153.             'firm' => $firmGmail,
  154.         );
  155.         // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  156.         $transporter = new Swift_SmtpTransport();
  157.         $transporter->setHost('smtp.gmail.com')
  158.             ->setEncryption('ssl')//ssl / tls
  159.             ->setPort(465)// 465 / 587
  160.             ->setUsername('desarrollo@develup.solutions')
  161.             ->setPassword('utvh hzoi wfdo ztjs');
  162.         $mailer = new Swift_Mailer($transporter);
  163.         $message = new Swift_Message();
  164.         $message->setSubject($subject)
  165.             ->setSender($agentMail)
  166.             ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  167.             ->setReplyTo($agentMail)
  168.             ->setTo($mailAgent)
  169.             ->setBody(
  170.                 $this->renderView(
  171.                     'mail/structure-mail.html.twig',
  172.                     array('data' => $data)
  173.                 ),
  174.                 'text/html'
  175.             );
  176.         $mailer->send($message);
  177.         return true;
  178.     }
  179. }