<?php
namespace App\MDS\GreenPatioBundle\Controller;
use App\MDS\GreenPatioBundle\Entity\ReservationDeposit;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;
use App\MDS\GreenPatioBundle\Entity\Reservation;
use DateTime;
use App\Entity\Client;
use App\Entity\ClientContact;
use App\Entity\User;
use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class ReservationsScheduleTaskController extends AbstractController
{
/**
* @Route("/remindernodeposit", name="reservations_reminder_no_deposit")
* Recordatorio de expedientes confirmados sin depositos
*/
public function reminderNoDepositAction(EntityManagerInterface $em)
{
// Los días lunes se enviará un recordatorio por correo
$today = new DateTime('now');
$reminder = ($today->format('N') == 1);
if (!$reminder){ return new JsonResponse('Done'); }
$resConfirmed = $em->getRepository(Reservation::class)->findBy(array('status' => 'Confirmed'));
$arrayNotify = array(); // array( 'Id de agente a notificar' =>'Info del agente', array ('Id del expediente pendiente' => expediente, cliente y contacto del cliente ) )
foreach ($resConfirmed as $item){
$idCreator = $item->getCreatedBy();
$agentCreator = $em->getRepository(User::class)->findOneById($idCreator);
$idUpdator = $item->getUpdatedBy();
$agentUpdator = $em->getRepository(User::class)->findOneById($idUpdator);
if(!empty($item->getClient())){ $client = $em->getRepository(Client::class)->findOneById($item->getClient()); } else { $client = null; }
if(!empty($client)){ $clientContact = $em->getRepository(ClientContact::class)->findOneByClientId($client->getId()); } else { $clientContact = null; }
$resDeposits = $em->getRepository(ReservationDeposit::class)->findByReservationId($item->getId());
if (empty($resDeposits)) {
$arrayNotify[$idCreator]['agente'] = $agentCreator;
$arrayNotify[$idCreator]['expedientes'][$item->getId()] = array('expediente' => $item, 'Cliente' => $client, 'ClientContact' => $clientContact,);
$arrayNotify[$idUpdator]['agente'] = $agentUpdator;
$arrayNotify[$idUpdator]['expedientes'][$item->getId()] = array('expediente' => $item, 'Cliente' => $client, 'ClientContact' => $clientContact,);
}
}
// Enviamos los correos a los agentes
$texto = ''; $textoSimple = '';
foreach ($arrayNotify as $item){
//Creamos el texto con la lista de reservas
foreach ($item['expedientes'] as $elem){
$clientName = (!empty($elem['Cliente'])) ? $elem['Cliente']->getName() : 'No se encontró información del cliente';
$clientContactName = (!empty($elem['ClientContact'])) ? $elem['ClientContact']->getName() .' '. $elem['ClientContact']->getLastName().'( '.$elem['ClientContact']->getEmail().' )' : 'No se encontró información del contacto';
$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;
$texto = $texto .'<br>';
$textoSimple = $textoSimple . '<a href="//' . $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' . $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>'. ' || '. $elem['expediente']->getTitle();
$textoSimple = $textoSimple .'<br>';
}
$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;
$textoSimple = 'Estos son los expedientes que requieren de su atención<br><br>Id exp || Nombre del expediente <br>'. $textoSimple;
// Alertar por Telegram y correo al agente, cc a Esteban y admin
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
if (!empty($item['agente'])){ $nombreAgente = $item['agente']->getName().' '.$item['agente']->getLastName(); } else { $nombreAgente = 'No se pudo determinar el nombre del agente'; }
$this->sendTelegramMailSimple(31, 'Expedientes de Green Patio confirmados sin deposito del agente: '. $nombreAgente, $texto, $textoSimple); // Notificacion a Esteban
$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 )
$texto = '';
}
return new JsonResponse('Done');
}
/**
* @Route("/remindernoinvoiced", name="reservations_reminder_no_invoiced")
* Recordatorio de expedientes sin factura
*/
public function reminderNoInvoicedAction(EntityManagerInterface $em)
{
// El primer día del mes se enviará un recordatorio por correo
$today = new DateTime('now');
$oneYearAgo = (clone $today)->modify('-1 year');
$reminder = ($today->format('d') == 1);
if (!$reminder){ return new JsonResponse('Done'); }
$queryBuilder = $em->getRepository(Reservation::class)->createQueryBuilder('r');
$queryBuilder->where('r.status IN (:statuses)')
->andWhere('r.dateEnd < :today')
->andWhere('r.dateEnd > :oneYearAgo')
->setParameter('statuses', ['Confirmed', 'Bloqueo'])
->setParameter('today', $today)
->setParameter('oneYearAgo', $oneYearAgo);
$resConfirmed = $queryBuilder->getQuery()->getResult();
$arrayNotify = array(); // array( 'Id de agente a notificar' =>'Info del agente', array ('Id del expediente pendiente' => expediente, cliente y contacto del cliente ) )
foreach ($resConfirmed as $item){
$idCreator = $item->getCreatedBy();
$agentCreator = $em->getRepository(User::class)->findOneById($idCreator);
$idUpdator = $item->getUpdatedBy();
$agentUpdator = $em->getRepository(User::class)->findOneById($idUpdator);
if(!empty($item->getClient())){ $client = $em->getRepository(Client::class)->findOneById($item->getClient()); } else { $client = null; }
if(!empty($client)){ $clientContact = $em->getRepository(ClientContact::class)->findOneByClientId($client->getId()); } else { $clientContact = null; }
$resDeposits = $em->getRepository(ReservationDeposit::class)->findByReservationId($item->getId());
if (empty($resDeposits)) {
$arrayNotify[$idCreator]['agente'] = $agentCreator;
$arrayNotify[$idCreator]['expedientes'][$item->getId()] = array('expediente' => $item, 'Cliente' => $client, 'ClientContact' => $clientContact,);
$arrayNotify[$idUpdator]['agente'] = $agentUpdator;
$arrayNotify[$idUpdator]['expedientes'][$item->getId()] = array('expediente' => $item, 'Cliente' => $client, 'ClientContact' => $clientContact,);
}
}
// Enviamos los correos a los agentes
$texto = ''; $textoSimple = '';
foreach ($arrayNotify as $item){
//Creamos el texto con la lista de reservas
foreach ($item['expedientes'] as $elem){
$clientName = (!empty($elem['Cliente'])) ? $elem['Cliente']->getName() : 'No se encontró información del cliente';
$clientContactName = (!empty($elem['ClientContact'])) ? $elem['ClientContact']->getName() .' '. $elem['ClientContact']->getLastName().'( '.$elem['ClientContact']->getEmail().' )' : 'No se encontró información del contacto';
$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;
$texto = $texto .'<br>';
$textoSimple = $textoSimple . '<a href="//' . $_SERVER['HTTP_HOST'] . '/reservations-greenpatio/editsimple/' . $elem['expediente']->getId().'">'.$elem['expediente']->getId().'</a>'. ' || '. $elem['expediente']->getTitle();
$textoSimple = $textoSimple .'<br>';
}
$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;
$textoSimple = 'Estos son los expedientes que requieren de su atención<br><br>Id exp || Nombre del expediente <br>'. $textoSimple;
// Alertar por Telegram y correo al agente, cc a Esteban y admin
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
if (!empty($item['agente'])){ $nombreAgente = $item['agente']->getName().' '.$item['agente']->getLastName(); } else { $nombreAgente = 'No se pudo determinar el nombre del agente'; }
$this->sendTelegramMailSimple(31, 'Expedientes de Green Patio sin facturar del agente: '. $nombreAgente, $texto, $textoSimple); // Notificacion a Esteban
$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 )
$texto = '';
}
return new JsonResponse('Done');
}
private function sendTelegramMailSimple($id, $subject, $text, $textTelegram)
{
$em = $this->getDoctrine()->getManager();
$telegUser = $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
// if (!empty($telegUser)) {
if (false) {
// $xbody = '<a href="//' . $_SERVER['HTTP_HOST'] . '/higotrigo/ht/file/' . $idProp . '/edit"></a> ' . $text;
// $text = 'NUEVO EXPEDIENTE - ' . 'https://' . $_SERVER['HTTP_HOST'] . '/higotrigo/ht/file/' . $idProp . '/edit';
$parameters = array('chat_id' => $telegUser->getChatId(), 'text' => $textTelegram,);
$bot_token = $telegUser->getBotToken();
$url = "https://api.telegram.org/bot$bot_token/sendMessage";
if (!$curl = curl_init()) { exit(); }
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
curl_close($curl);
}
$agent = $em->getRepository(User::class)->findOneById($id);
$agentMail = ($agent->getEmail() == 33) ? 'administracion@greenpatio.es' : $agent->getEmail(); // Notificacion a admin (mail admon@avexpress.tv, pero se notificará a administracion@greenpatio.es )
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $text,
'firm' => $firmGmail,
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('utvh hzoi wfdo ztjs');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject($subject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
return true;
}
}