<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 19/03/2018
* Time: 15:32
*/
namespace App\MDS\AdministrationBundle\Controller;
use App\Entity\Client;
use App\Entity\User;
use App\MDS\EventsBundle\Entity\Proposal;
use Doctrine\ORM\EntityManagerInterface;
use App\MDS\EventsBundle\Entity\ProposalAgents;
use App\MDS\GreenPatioBundle\Entity\Reservation;
use Psr\Log\LoggerInterface;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
class BlockedProposalController extends AbstractController
{
/**
* @Route("/block/proposals/", name="block_proposals")
*/
public function blockProposalAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposals = $em->getRepository(Proposal::class)->findAll();
$hoymenostreinta = date('Y-m-d', strtotime('-31 day'));
$hoymenostreinta = strtotime($hoymenostreinta);
foreach ($proposals as $proposal){
//Solo expiran los proposal confirmados
$expiredTime = ((strtotime(($proposal->getDateEventEndAt())->format('Y-m-d'))< $hoymenostreinta) and (($proposal->getStatus()== 'Confirmed')));
if ($expiredTime){
// Remover los asistentes de In-Out
// $propSupServ = $em->getRepository('EventsBundle:ProposalsSupplierServices')->findByPrpoposalId($proposal->getId());
// foreach ($propSupServ as $item) {
// if(($item->getServiceCatId() == 15) and ($item->getSupplierId() == 4)){
// //Si es un asistente y el proveedor es In-Out
// $em->remove($item);
// $em->flush();
// }
// }
//Buscamos los agentes a notificar
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$agentMail = $agent->getEmail();
$mailAgent = null;
$propAgntsPer = $em->getRepository(ProposalAgents::class)->findByIdProp($proposal->getId());
if (($propAgntsPer[0]->getAgTwo()!=null) and ($propAgntsPer[0]->getAgTwo()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgTwo())->getEmail();}
if (($propAgntsPer[0]->getAgThree()!=null) and ($propAgntsPer[0]->getAgThree()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgThree())->getEmail();}
if (($propAgntsPer[0]->getAgFour()!=null) and ($propAgntsPer[0]->getAgFour()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgFour())->getEmail();}
//Se bloquea el proposal
$proposal->setStatus('Blocked');
$em->persist($proposal);
$em->flush();
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a> - <a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/summary/prices/' . $proposal->getId() . '">Ver Resumen</a><br><br>Notificación de Proposal: Este Proposal ha sido Bloqueado debido a que no ha sido facturado en el plazo establecido.' . '<br><br>',
'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($agentMail)
// ->setPassword($passGmail)//;
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alerta de Proposal Bloqueado')
->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);
} else {
if (($proposal->getStatus()== 'Confirmed')) {
//Verifico si esta a 10 dias de expirar para enviar notificación
$hoymenosveinte = date('Y-m-d', strtotime('-19 day'));
$hoymenosveinte = strtotime($hoymenosveinte);
// Hoy > ffin +19 dias -- Enviar correo de notificacion al agente
if ($hoymenosveinte > strtotime(($proposal->getDateEventEndAt())->format('Y-m-d'))) {
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$agentMail = $agent->getEmail();
// $mailAgent[] = $agent->getEmail();
$mailAgent = null;
$propAgntsPer = $em->getRepository(ProposalAgents::class)->findByIdProp($proposal->getId());
if (($propAgntsPer[0]->getAgTwo()!=null) and ($propAgntsPer[0]->getAgTwo()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgTwo())->getEmail();}
if (($propAgntsPer[0]->getAgThree()!=null) and ($propAgntsPer[0]->getAgThree()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgThree())->getEmail();}
if (($propAgntsPer[0]->getAgFour()!=null) and ($propAgntsPer[0]->getAgFour()!=0))
{$mailAgent[] = $em->getRepository(User::class)->findOneById($propAgntsPer[0]->getAgFour())->getEmail();}
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a> - <a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/summary/prices/' . $proposal->getId() . '">Ver Resumen</a><br><br>Alerta de Proposal: Este Proposal será Bloqueado al pasar 30 días de finalizado el evento si no ha sido facturado.' . '<br><br>',
'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($agentMail)
// ->setPassword($passGmail)//;
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alerta de Proposal a Bloquear')
->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 new JsonResponse('Done');
}
/**
* @Route("/update/proposals/agents", name="update_proposals_agents")
*/
public function updateProposalAgentsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposals = $em->getRepository(Proposal::class)->findAll();
foreach ($proposals as $proposal){
$propAgents = new ProposalAgents();
$propAgents->setAgOne(0);
$propAgents->setAgTwo(0);
$propAgents->setAgThree(0);
$propAgents->setAgFour(0);
$propAgents->setAgOnePerc(0);
$propAgents->setAgTwoPerc(0);
$propAgents->setAgThreePerc(0);
$propAgents->setAgFourPerc(0);
$propAgents->setIdProp($proposal->getId());
$propAgents->setAgOne($proposal->getAgentId());
if ($proposal->getAgentTwoId() != null){
$str_array_agents = explode(",", $proposal->getAgentTwoId());
if($str_array_agents[0]!=999999){
$propAgents->setAgTwo($str_array_agents[0]);
}
if ((sizeof($str_array_agents)>1) and ($str_array_agents[1]!=999999)){
$propAgents->setAgThree($str_array_agents[1]);
}
if ((sizeof($str_array_agents)>2) and ($str_array_agents[2]!=999999)){
$propAgents->setAgFour($str_array_agents[2]);
}
}
$propsearch = $em->getRepository(ProposalAgents::class)->findByIdProp($proposal->getId());
if ($propsearch == null){
$em->persist($propAgents);
$em->flush();
}
}
return new JsonResponse('Done update Proposal Agents');
}
/**
* @Route("/reservations-greenpatio/sendalertmail/", name="send_alert_mail")
* Cuando hay un bloqueo, se envia un correo al cliente. Al pasar 5 días se le recuerda. A la semana se cancela el bloqueo si no hay confirmacion
*/
public function sendAlertMailAction(Request $request){
$em = $this->getDoctrine()->getManager();
$parameters = array(
'id' => 0,
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationMailAlertClient i
WHERE i.reservationId != :id';
$query = $em->createQuery($dql)->setParameters($parameters);
$alertas = $query->getResult();
$hoy = new \DateTime("now", NULL);
foreach ($alertas as $alerta){
// Verificamos si es necesario alertar
if (!$alerta->getAlertSended()){
$reserva = $em->getRepository(Reservation::class)->findOneById($alerta->getReservationId());
if ($alerta->getAlertDateTime()<$hoy){
//INICIO: Enviamos la notificacion de 48 horas al cliente y al agente
$agent = $em->getRepository(User::class)->findOneById($alerta->getAgentId());
$client = $em->getRepository(Client::class)->findOneById($alerta->getClientId());
$mailAddressTo = $alerta->getClientMail();
$mailAddressFrom = $alerta->getAgentMail();
$replyTo = array(
$alerta->getClientMail() => $client->getName(),
$alerta->getAgentMail() => $agent->getName().' '. $agent->getLastName(),
);
$mailSubject = 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
$mailBody = 'Estimado cliente,'.
'<br><br> Nos ponemos en contacto con usted para recordarle que su reserva expira en 48 horas. Si pasado este tiempo no hemos recibido confirmación por su parte, procederemos a la cancelación de la misma.'.
'<br><br>Reserva: ' . $reserva->getId() .' - '. $reserva->getTitle();
if (!empty($reserva->getDays())){ $mailBody = $mailBody . '<br>Días bloqueados: '.$reserva->getDays(); }
$mailBody = $mailBody . '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
$agentMail = $mailAddressFrom;
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $mailBody,
'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('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject($mailSubject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "Green Patio"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
//FIN: Enviamos la notificacion de 48 horas al cliente y al agente
$alerta->setAlertSended(true);
$em->persist($alerta);
$em->flush();
} else {
// d('NO hemos pasado la fecha de alerta');
}
} else {
// Verificamos si es necesario cancelar
if ($alerta->getCancelDateTime()<$hoy){
//INICIO: Enviamos la notificacion de cancelacion al cliente y al agente
$reserva = $em->getRepository(Reservation::class)->findOneById($alerta->getReservationId());
$agent = $em->getRepository(User::class)->findOneById($alerta->getAgentId());
$client = $em->getRepository(Client::class)->findOneById($alerta->getClientId());
$mailAddressTo = $alerta->getClientMail();
$mailAddressFrom = $alerta->getAgentMail();
$replyTo = array(
$alerta->getClientMail() => $client->getName(),
$alerta->getAgentMail() => $agent->getName().' '. $agent->getLastName(),
);
$mailSubject = 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
$mailBody = 'Estimado cliente,'.
// '<br><br>Le informamos que hemos procedido al desbloqueo del evento en la fecha en referencia, al no haber recibido ninguna confirmación de dicho evento en la fecha reservada. Para cualquier consulta por favor póngase en contacto con nuestro Departamento Comercial.'.
'<br><br>Le informamos que hemos procedido al desbloqueo de la fecha del evento en referencia, al no haber recibido ninguna noticia por su parte. Para cualquier consulta por favor póngase en contacto con nuestro Departamento Comercial.'.
'<br><br>Reserva: ' . $reserva->getId() .' - '. $reserva->getTitle();
// if (!empty($reserva->getDays())){ $mailBody = $mailBody . '<br>Días bloqueados: '.$reserva->getDays(); }
$mailBody = $mailBody . '<br>Días bloqueados: '.$reserva->getDays(); // El mensaje hace referencia a este campo por eso se quita el condicional
$mailBody = $mailBody . '<br><br><br>Atentamente<br><br>';
$agentMail = $mailAddressFrom;
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $mailBody,
'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('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject($mailSubject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "Green Patio"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
//FIN: Enviamos la notificacion de cancelacion al cliente y al agente
$alerta->setCancelSended(true);
$alerta->setOldReservationId($alerta->getReservationId());
$alerta->setReservationId(0);
$em->persist($alerta);
$em->flush();
$reserva = $em->getRepository(Reservation::class)->findOneById($alerta->getOldReservationId());
$reserva->setStatus('Cotizado');
$em->persist($reserva);
$em->flush();
}
}
}
return new JsonResponse('Done');
}
}