<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 17/01/2018
* Time: 18:52
*/
namespace App\Controller;
use App\Entity\Client;
use App\Entity\ClientContact;
use App\Entity\ClientGroupContact;
use App\Entity\SendMail;
use App\Entity\Supplier;
use App\Entity\User;
use App\Form\SendMailType;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalAgents;
use App\MDS\EventsBundle\Entity\ProposalTracing;
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\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
class SendMailController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/*
* ATENCION LAS RAIZ DE @Route POR DEFECTO DEL BUNDLE: EventsBundle ES /events/, NO PONERLO EN LA @Route("")
*
* */
/**
* @Route("/mail/invoice/{id}", name="proposal_mail_Invoice_form")
*/
public function Invoiceaction($id, Request $request)
{
$mail = new SendMail();
$mail->setProposalId($id);
$mail->setType('Invoice');
$form = $this->createProposalMailCreateForm($mail);
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$clientcontact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$data_contact[] = array(
'name' => $clientcontact->getName(),
'lastname' => $clientcontact->getLastName(),
'email' => $clientcontact->getEmail()
);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$grupo_contact = $em->getRepository(ClientGroupContact::class)->findByGroupId($client->getGroupId());
$data_groupContact = array();
foreach($grupo_contact as $grupocontact){
$data_groupContact[] = array(
'name' => $grupocontact->getName(),
'lastname' => $grupocontact->getLastName(),
'email' => $grupocontact->getEmail()
);
}
$data_agents = $this->findMailsAgentsProposal($id);
$data_correos = array_merge($data_contact, $data_groupContact, $data_agents);
return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'subjectAndMessage' => $proposal->getId().' - '.$proposal->getTitle(),
'correos' => $data_correos,
'mcp' => $proposal->getMcp(),
'form' => $form->createView()
)
);
}
/**
* @Route("/mail/proforma/{id}", name="proposal_mail_proforma_form")
*/
public function Proformaction($id, Request $request)
{
$mail = new SendMail();
$mail->setProposalId($id);
$mail->setType('Proforma');
$form = $this->createProposalMailCreateForm($mail);
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$clientcontact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$data_contact[] = array(
'name' => $clientcontact->getName(),
'lastname' => $clientcontact->getLastName(),
'email' => $clientcontact->getEmail()
);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$grupo_contact = $em->getRepository(ClientGroupContact::class)->findByGroupId($client->getGroupId());
$data_groupContact = array();
foreach($grupo_contact as $grupocontact){
$data_groupContact[] = array(
'name' => $grupocontact->getName(),
'lastname' => $grupocontact->getLastName(),
'email' => $grupocontact->getEmail()
);
}
$data_agents = $this->findMailsAgentsProposal($id);
$data_correos = array_merge($data_contact, $data_groupContact, $data_agents);
return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'correos' => $data_correos,
'mcp' => $proposal->getMcp(),
'subjectAndMessage' => $proposal->getId().' - '.$proposal->getTitle(),
'form' => $form->createView()
)
);
}
/**
* @Route("/mail/presentation/{id}", name="proposal_mail_presentation_form")
*/
public function Presentationaction($id, Request $request)
{
$mail = new SendMail();
$mail->setProposalId($id);
$mail->setType('Presentation');
$form = $this->createProposalMailCreateForm($mail);
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$clientcontact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$data_contact[] = array(
'name' => $clientcontact->getName(),
'lastname' => $clientcontact->getLastName(),
'email' => $clientcontact->getEmail()
);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$grupo_contact = $em->getRepository(ClientGroupContact::class)->findByGroupId($client->getGroupId());
$data_groupContact = array();
foreach($grupo_contact as $grupocontact){
$data_groupContact[] = array(
'name' => $grupocontact->getName(),
'lastname' => $grupocontact->getLastName(),
'email' => $grupocontact->getEmail()
);
}
$data_agents = $this->findMailsAgentsProposal($id);
$data_correos = array_merge($data_contact, $data_groupContact, $data_agents);
return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'correos' => $data_correos,
'subjectAndMessage' => $proposal->getId().' - '.$proposal->getTitle(),
'mcp' => $proposal->getMcp(),
'form' => $form->createView()
)
);
}
/**
* @Route("/mail/normal/{id}", name="proposal_mail_form")
*/
public function NormalAction($id, Request $request)
{
$mail = new SendMail();
$mail->setProposalId($id);
$mail->setType('Normal');
$form = $this->createProposalMailCreateForm($mail);
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$clientcontact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$data_contact[] = array(
'name' => $clientcontact->getName(),
'lastname' => $clientcontact->getLastName(),
'email' => $clientcontact->getEmail()
);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$grupo_contact = $em->getRepository(ClientGroupContact::class)->findByGroupId($client->getGroupId());
$data_groupContact = array();
foreach($grupo_contact as $grupocontact){
$data_groupContact[] = array(
'name' => $grupocontact->getName(),
'lastname' => $grupocontact->getLastName(),
'email' => $grupocontact->getEmail()
);
}
$data_agents = $this->findMailsAgentsProposal($id);
$data_correos = array_merge($data_contact, $data_groupContact, $data_agents);
return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'subjectAndMessage' => $proposal->getId().' - '.$proposal->getTitle(),
'correos' => $data_correos,
'mcp' => $proposal->getMcp(),
'form' => $form->createView()
)
);
}
private function createProposalMailCreateForm(SendMail $entity)
{
$form = $this->createForm(SendMailType::class, $entity, array(
'action' => $this->generateUrl('proposal_mail_create'),
'method' => 'PUT'));
return $form;
}
/**
* @Route("/mail/create", name="proposal_mail_create")
*/
public function createProposalMailAction(Request $request, \Swift_Mailer $mailer)
{
$proposalsendmail = $request->request->get('sendmail');
$proposalsendmail_mail = $request->request->get('sendmail_mail')['mail'];
$proposalsendmail_admail = $request->request->get('sendmail_admail')['mail'];
$arraysendmail_admail = explode(",", $proposalsendmail_admail);
foreach ($arraysendmail_admail as $key => $value) {
if (empty($value)) {
unset($arraysendmail_admail[$key]);
}
}
if(empty($proposalsendmail['body'])){ $proposalsendmail['body'] = $proposalsendmail['subject']; }
$mail = new SendMail();
$form = $this->createProposalMailCreateForm($mail);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if($form->isValid())
{
$proposal = $em->getRepository(Proposal::class)->findOneById($proposalsendmail['proposalId']);
$proposal->setSent('Yes');
$em->persist($proposal);
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$data = array();
if ($proposalsendmail['type'] == "Normal" ){
$data = array(
'body' => $proposalsendmail['body'],
'firm' => $firmGmail,
);
}elseif ($proposalsendmail['type'] == "Proforma" ){
$data = array(
'body' => $proposalsendmail['body'],
'nameurl' => "Proforma, Proposal: ".$proposal->getTitle(),
'urlPdf' => "http://inout.mante.solutions/pdf/pro/".$proposal->getId(),
'firm' => $firmGmail,
);
}elseif ($proposalsendmail['type'] == "Invoice" ){
$data = array(
'body' => $proposalsendmail['body'],
'nameurl' => "Factura, Proposal: ".$proposal->getTitle(),
'urlPdf' => "http://inout.mante.solutions/pdf/inv/".$proposal->getId(),
'firm' => $firmGmail,
);
}elseif ($proposalsendmail['type'] == "Presentation" ){
$data = array(
'body' => $proposalsendmail['body'],
'nameurl' => "Presentación, Proposal: ".$proposal->getTitle(),
'urlPdf' => "http://inout.mante.solutions/presentation/home/".$proposal->getAccessKey(),
'firm' => $firmGmail,
);
// Guardo en historico de seguimiento
$textHistory = $this->translator->trans('Send Mail Presentation');
$history = $this->TracingHistoryOperations($proposal->getId(), $textHistory);
}elseif ($proposalsendmail['type'] == "Available" ){
$data = array(
'body' => $proposalsendmail['body'],
'firm' => $firmGmail,
);
}
// Buscamos los correos de los administradores
$emailarray = array();
$usermails = $em->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach($usermails as $usermail){
$emailarray[] = $usermail->getEmail();
}
// $mailpruebas[] = '';
// $mailpruebas[] = 'jorge.defreitas@develup.solutions';
if (is_null($proposalsendmail_mail)){
// $mailTodos = array_merge($emailarray, $mailAgent, $proposalsendmail_mail, $arraysendmail_admail);
$mailTodos = array_merge($mailAgent, $arraysendmail_admail);
}else{
// $mailTodos = array_merge($emailarray, $mailAgent, $proposalsendmail_mail);
$mailTodos = array_merge($mailAgent, $proposalsendmail_mail, $arraysendmail_admail);
}
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl') //ssl / tls
->setPort(465) // 465 / 587
->setUsername($agentMail)
->setPassword($passGmail);
$mailer = new Swift_Mailer($transporter);
// $message = (new \Swift_Message())
$message = new Swift_Message();
$message->setSubject($proposalsendmail['subject'])
// ->setFrom(array("desarrollo@develup.solutions" => "Prueba"))
->setSender($agentMail)
->setFrom($mailAgentSent)
->setReplyTo($mailAgentSent)
->setTo($mailTodos)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
)
;
$mailer->send($message);
$mailTodos = implode(",", $mailTodos);
$mail->setMail($mailTodos);
$mail->setBody($proposalsendmail['body']);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$mail->setCreatedId($user_id);
$mail->setUpdatedId($user_id);
$em->persist($mail);
$em->flush();
$event = 'Sent the mail and registered.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeMailSend', $successMessage);
return $this->redirectToRoute('list_SentMail_Proposal',
array(
'id' => $mail->getProposalId(),
)
);
}else{
$errorMessagebase = $this->translator->trans('Error, some fields are empty');
$errorMessage = $errorMessagebase;
$this->addFlash('mensajeMailSenderror', $errorMessage);
}
$proposal = $em->getRepository(Proposal::class)->findOneById($mail->getProposalId());
return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig', array(
'id' => $mail->getProposalId(),
'token' => $proposal->getAccessKey(),
'subjectAndMessage' => $proposal->getId().' - '.$proposal->getTitle(),
'correos' => null,
'mcp' => $proposal->getMcp(),
'form' => $form->createView()
)
);
}
/**
* @Route("/mail/searchcreate", name="proposal_mail_create_search")
*/
public function createProposalMailSearchAction(Request $request, \Swift_Mailer $mailer)
{
$proposalsendmail = $request->request->get('sendmail');
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($proposalsendmail['proposalId']);
$proposalsendmail_mail = $request->request->get('sendmail_mail')['mail'];
$mailnew = new SendMail();
$form = $this->createProposalMailCreateForm($mailnew);
$form->handleRequest($request);
if($form->isValid())
{
$proposal = $em->getRepository(Proposal::class)->findOneById($proposalsendmail['proposalId']);
$proposal->setSent('Yes');
$em->persist($proposal);
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$data = array(
'body' => $proposalsendmail['body'],
'firm' => $firmGmail,
);
// Buscamos los correos de los administradores
$emailarray = array();
$usermails = $em->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach($usermails as $usermail){
$emailarray[] = $usermail->getEmail();
}
foreach($proposalsendmail_mail as $key => $proposalsendmailmail){
$supplier = $em->getRepository(Supplier::class)->findOneById($key);
$supplierName = $supplier->getName();
$subject = $proposalsendmail['subject']." / ".$supplierName;
$mailTodos = array_merge($mailAgent, $proposalsendmailmail);
// d($subject, $mailTodos);
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl') //ssl / tls
->setPort(465) // 465 / 587
->setUsername($agentMail)
->setPassword($passGmail);
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject($subject)
->setSender($agentMail)
->setFrom($mailAgentSent)
->setReplyTo($mailAgentSent)
->setTo($mailTodos)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
)
;
$mailer->send($message);
$mail = new SendMail();
$mailTodos = implode(",", $mailTodos);
$mail->setMail($mailTodos);
$mail->setType('Available');
$mail->setProposalId($proposalsendmail['proposalId']);
$mail->setSubject($subject);
$mail->setBody($proposalsendmail['body']);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$mail->setCreatedId($user_id);
$mail->setUpdatedId($user_id);
$em->persist($mail);
$em->flush();
$event = 'Sent the mail and registered. / '.$subject;
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajesenmail', $successMessage);
}
// Guardo en historico de seguimiento
$textHistory = $this->translator->trans('Send mail request hotels');
$history = $this->TracingHistoryOperations($proposal->getId(), $textHistory);
// return $this->redirectToRoute('list_SentMail_Proposal',
// array(
// 'id' => $mail->getProposalId(),
// )
// );
}else{
$errorMessagebase = $this->translator->trans('Error, some fields are empty');
$errorMessage = $errorMessagebase;
$this->addFlash('mensajesenmailerror', $errorMessage);
}
return $this->redirectToRoute('list_SentMail_Proposal',
array(
'id' => $proposal->getId(),
)
);
// return $this->render('MDS/EventsBundle/proposal/send-mail.html.twig', array(
// 'id' => $proposal->getId(),
// 'token' => $proposal->getAccessKey(),
// 'mcp' => $proposal->getMcp(),
// 'form' => $form->createView()
// )
// );
}
// Funcion para insertar historico de seguimiento
// $textHistory = $this->translator->trans('');
// $history = $this->TracingHistoryOperations($proposal->getId(), $text);
private function TracingHistoryOperations($id, $text)
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$history = new ProposalTracing();
$history->setDateAt(new \DateTime('now'));
$history->setText($text);
$history->setAgentId($user_id);
$history->setProposalId($id);
$history->setViewed('no');
$history->setCreatedId($user_id);
$history->setUpdatedId($user_id);
$em->persist($history);
$em->flush();
$success = 'success';
return $success;
}
private function findMailsAgentsProposal($id)
{
// INCIO: Buscamos los agentes del proposal para que todos esten informados
$em = $this->getDoctrine()->getManager();
$prop_agents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
$data = array();
if (($prop_agents->getAgOne() !=0) and !empty($prop_agents->getAgOne())) {
$agent = $em->getRepository(User::class)->findOneById($prop_agents->getAgOne());
$data[] = array(
'name' => $agent->getName(),
'lastname' => $agent->getLastName(),
'email' => $agent->getEmail()
);
}
if (($prop_agents->getAgTwo() !=0) and !empty($prop_agents->getAgTwo())) {
$agent = $em->getRepository(User::class)->findOneById($prop_agents->getAgTwo());
$data[] = array(
'name' => $agent->getName(),
'lastname' => $agent->getLastName(),
'email' => $agent->getEmail()
);
}
if (($prop_agents->getAgThree() !=0) and !empty($prop_agents->getAgThree())) {
$agent = $em->getRepository(User::class)->findOneById($prop_agents->getAgThree());
$data[] = array(
'name' => $agent->getName(),
'lastname' => $agent->getLastName(),
'email' => $agent->getEmail()
);
}
if (($prop_agents->getAgFour() !=0) and !empty($prop_agents->getAgFour())) {
$agent = $em->getRepository(User::class)->findOneById($prop_agents->getAgFour());
$data[] = array(
'name' => $agent->getName(),
'lastname' => $agent->getLastName(),
'email' => $agent->getEmail()
);
}
// FIN: Buscamos los agentes del proposal para que todos esten informados
return $data;
}
}