<?php
namespace App\Event;
use App\Entity\Communication\Message;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Templating\EngineInterface;
class MailSubscriber implements EventSubscriberInterface
{
private $em;
private $tokenStorage;
private $params;
private $templating;
private $mailer;
private $router;
public function __construct(EntityManagerInterface $entityManager, TokenStorageInterface $tokenStorage, ParameterBagInterface $params, EngineInterface $templating, \Swift_Mailer $mailer, RouterInterface $router)
{
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
$this->params = $params;
$this->templating = $templating;
$this->mailer = $mailer;
$this->router = $router;
}
public static function getSubscribedEvents()
{
return [
ContractUpdatedEvent::NAME => ['onContractUpdated', 10],
SendPurchaseLinkEvent::NAME => ['onSendPurchaseLink', 10],
SendSubscriptionLinkEvent::NAME => ['onSendSubscriptionLink', 10],
SendRenewalReminderEvent::NAME => ['onSendRenewalReminder', 10],
SendInvoiceReminderEvent::NAME => ['onSendInvoiceReminder', 10],
];
}
public function onContractUpdated(ContractUpdatedEvent $event)
{
$contract = $event->getContract();
$client = $contract->getUser();
$user = $this->tokenStorage->getToken()->getUser();
if ($client) {
try {
$message = new Message();
$message->setTitle('Contrato subido');
$message->setMessage($contract->getSigned() ? 'El contrato firmado ha sido subido a tu sección de Mis Contratos' : 'Un contrato ha sido subido a tu sección de Mis Contratos');
$message->setRecipient($client);
$message->setSender($user);
$this->em->persist($message);
$this->em->flush();
$msgParams = [
'user' => $user,
'subject' => 'Nuevo mensaje recibido.',
'recipient' => $user->getEmail(),
'object' => $contract,
];
$this->sendMessage($msgParams);
} catch (\Exception $e) {
dump($e->getMessage());
exit;
}
}
}
public function onSendSubscriptionLink(SendSubscriptionLinkEvent $event)
{
$subscription = $event->getSubscription();
$client = $subscription->getUser();
$user = $this->tokenStorage->getToken()->getUser();
if ($client) {
try {
$message = new Message();
$message->setTitle('Suscripción personalizado');
$url = $this->router->generate('shop_cart_addSub', ['subscriptionId' => $subscription->getId()]);
$message->setMessage('<p>Su servicio personalizado ya esta disponible para comprar.</p><p>Pinche <a href="'.$url.'" target="_blank">aquí</a> para efectuar la compra.</p>');
$message->setRecipient($client);
$message->setSender($user);
$this->em->persist($message);
$this->em->flush();
$msgParams = [
'user' => $user,
'subject' => 'NOMASPAPEL.ES: Enlace de compra',
'recipient' => $client->getEmail(),
'object' => $subscription,
];
$this->sendMessage($msgParams);
} catch (\Exception $e) {
dump($e->getMessage());
exit;
}
}
}
public function onSendPurchaseLink(SendPurchaseLinkEvent $event)
{
$purchase = $event->getPurchase();
$client = $purchase->getUser();
$user = $this->tokenStorage->getToken()->getUser();
if ($client) {
try {
$message = new Message();
$message->setTitle('Compra personalizada');
$url = $this->router->generate('shop_cart_addPurchase', ['purchaseId' => $purchase->getId()]);
$message->setMessage('<p>Su servicio personalizado ya esta disponible para comprar.</p><p>Pinche <a href="'.$url.'" target="_blank">aquí</a> para efectuar la compra.</p>');
$message->setRecipient($client);
$message->setSender($user);
$purchase->setNotifiedOn(new \DateTime());
$this->em->persist($purchase);
$this->em->persist($message);
$this->em->flush();
$msgParams = [
'user' => $user,
'subject' => 'NOMASPAPEL.ES: Enlace de compra',
'recipient' => $client->getEmail(),
'object' => $purchase,
];
$this->sendMessage($msgParams);
} catch (\Exception $e) {
dump($e->getMessage());
exit;
}
}
}
public function onSendRenewalReminder(SendRenewalReminderEvent $event)
{
$subscription = $event->getSubscription();
$client = $this->em->getRepository('App\Entity\Profile\User')->findOneBy(['id' => $subscription->getUserId()]);
$user = $this->em->getRepository('App\Entity\Profile\User')->findOneBy(['id' => 1]);
$templates = ['html' => 'email/renewalReminder.html.twig', 'text' => 'email/renewalReminder.txt.twig'];
if ($client) {
try {
$msgParams = [
'client' => $client,
'subject' => 'NOMASPAPEL.ES: Suscripción trimestral a punto de caducar',
'recipient' => $client->getEmail(),
'object' => $subscription,
'templates' => $templates,
];
$message = new Message();
$message->setTitle('Suscripción trimestral a punto de caducar');
$messageBody = $this->templating->render(
$templates['html'],
['client' => $client, 'data' => $msgParams]
);
$message->setMessage($messageBody);
$message->setRecipient($client);
$message->setSender($user);
$this->em->persist($message);
$this->em->flush();
$this->sendReminderMessage($msgParams);
} catch (\Exception $e) {
dump($e->getMessage());
exit;
}
}
}
public function onSendInvoiceReminder(SendInvoiceReminderEvent $event)
{
$subscription = $event->getSubscription();
$client = $this->em->getRepository('App\Entity\Profile\User')->findOneBy(['id' => $subscription->getUserId()]);
$user = $this->em->getRepository('App\Entity\Profile\User')->findOneBy(['id' => 2]);
$template = $this->getTemplateForDate(date('d-m'));
if (false !== $template) {
$templates = ['html' => $template, 'text' => str_replace('.html.', '.txt.', $template)];
if ($client) {
try {
$msgParams = [
'client' => $client,
'subject' => 'NOMASPAPEL.ES: Recordatorio de envio de facturas',
'recipient' => $client->getEmail(),
'object' => $subscription,
'templates' => $templates,
];
$message = new Message();
$message->setTitle('Recordatorio de envio de facturas');
$messageBody = $this->templating->render(
$templates['html'],
['client' => $client, 'data' => $msgParams]
);
$message->setMessage($messageBody);
$message->setRecipient($client);
$message->setSender($user);
$this->em->persist($message);
$this->em->flush();
$this->sendReminderMessage($msgParams);
} catch (\Exception $e) {
dump($e->getMessage());
exit;
}
}
} else {
return false;
}
}
/**
* Send email to user.
*
* @param [type] $data
*/
public function sendMessage($data)
{
$em = $this->em;
$entityName = $em->getMetadataFactory()->getMetadataFor(get_class($data['object']))->getName();
switch ($entityName) {
case 'App\Entity\Accounting\Certificate':
$data['section'] = 'Certificados';
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Accounting\Document':
switch ($data['object']->getDocumentType()) {
default:
case '':
case 'document':
$data['section'] = 'Documentos';
break;
case 'model':
$data['section'] = 'Modelos';
break;
}
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Accounting\Invoice':
$data['section'] = 'Facturas';
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Accounting\Salary':
$data['section'] = 'Nóminas';
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Profile\Contract':
$data['section'] = 'Contratos';
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Accounting\TaxReturn':
$data['section'] = 'IRPF';
$templates = ['html' => 'email/uploadNotification.html.twig', 'text' => 'email/uploadNotification.txt.twig'];
break;
case 'App\Entity\Product\SinglePurchase':
case 'App\Entity\Product\Subscription':
$data['class'] = $entityName;
$templates = ['html' => 'email/sendLink.html.twig', 'text' => 'email/sendLink.txt.twig'];
break;
case '':
default:
$templates = ['html' => 'email/notification.html.twig', 'text' => 'email/notification.txt.twig'];
break;
}
$recipient = $this->params->get('admin_email');
$msg = (new \Swift_Message())
->setSubject('' != $data['subject'] ? $data['subject'] : 'Sin asunto.')
->setFrom($this->params->get('from_email'))
->setTo('' != $data['recipient'] ? $data['recipient'] : $recipient)
->setBody(
$this->templating->render(
$templates['html'],
['user' => $data['user'], 'data' => $data]
),
'text/html'
)
->addPart(
$this->templating->render(
$templates['text'],
['user' => $data['user'], 'data' => $data]
),
'text/plain'
)
;
if (isset($data['attachment'])) {
$attachment = new \Swift_Attachment(file_get_contents($data['attachment']), $data['attachment_filename'], 'application/pdf');
$msg->attach($attachment);
}
return $this->mailer->send($msg);
}
public function sendReminderMessage($data)
{
$recipient = $this->params->get('admin_email');
$templates = $data['templates'];
$msg = (new \Swift_Message())
->setSubject('' != $data['subject'] ? $data['subject'] : 'Sin asunto.')
->setFrom($this->params->get('from_email'))
->setTo('' != $data['recipient'] ? $data['recipient'] : $recipient)
->setBody(
$this->templating->render(
$templates['html'],
['user' => $data['client'], 'data' => $data]
),
'text/html'
)
->addPart(
$this->templating->render(
$templates['text'],
['user' => $data['client'], 'data' => $data]
),
'text/plain'
)
;
if (isset($data['attachment'])) {
$attachment = new \Swift_Attachment(file_get_contents($data['attachment']), $data['attachment_filename'], 'application/pdf');
$msg->attach($attachment);
}
return $this->mailer->send($msg);
}
public function getTemplateForDate($date)
{
$folder = 'email/reminders/';
$schedule = [
'01-01' => ['template' => 'jan-01.html.twig'],
'04-01' => ['template' => 'jan-04.html.twig'],
'28-01' => ['template' => 'jan-28.html.twig'],
'04-02' => ['template' => 'feb-04.html.twig'],
'23-02' => ['template' => 'feb-23.html.twig'],
'04-03' => ['template' => 'mar-04.html.twig'],
'28-03' => ['template' => 'mar-28.html.twig'],
'01-04' => ['template' => 'apr-01.html.twig'],
'04-04' => ['template' => 'apr-04.html.twig'],
'27-04' => ['template' => 'apr-27.html.twig'],
'04-05' => ['template' => 'may-04.html.twig'],
'28-05' => ['template' => 'may-28.html.twig'],
'04-06' => ['template' => 'jun-04.html.twig'],
'27-06' => ['template' => 'jun-27.html.twig'],
'01-07' => ['template' => 'jul-01.html.twig'],
'04-07' => ['template' => 'jul-04.html.twig'],
'28-07' => ['template' => 'jul-28.html.twig'],
'04-08' => ['template' => 'aug-04.html.twig'],
'28-08' => ['template' => 'aug-28.html.twig'],
'04-09' => ['template' => 'sep-04.html.twig'],
'27-09' => ['template' => 'sep-27.html.twig'],
'01-10' => ['template' => 'oct-01.html.twig'],
'04-10' => ['template' => 'oct-04.html.twig'],
'28-10' => ['template' => 'oct-28.html.twig'],
'04-11' => ['template' => 'nov-04.html.twig'],
'27-11' => ['template' => 'nov-27.html.twig'],
'04-12' => ['template' => 'dec-04.html.twig'],
'28-12' => ['template' => 'dec-28.html.twig'],
];
return array_key_exists($date, $schedule) ? $folder.$schedule[$date]['template'] : false;
}
}