Browse Source

Adaptations newsletters + MailjetSMS

develop
Guillaume 3 years ago
parent
commit
de75266686
11 changed files with 340 additions and 200 deletions
  1. +73
    -63
      ShopBundle/Controller/Backend/NewsController.php
  2. +41
    -0
      ShopBundle/Form/DataTransformer/NewsletterSignupToBooleanTransformer.php
  3. +14
    -8
      ShopBundle/Form/Frontend/RegistrationType.php
  4. +9
    -3
      ShopBundle/Manager/EntityManager.php
  5. +6
    -2
      ShopBundle/Model/Merchant.php
  6. +17
    -0
      ShopBundle/Model/Newsletter.php
  7. +1
    -0
      ShopBundle/Resources/translations/lcshop.fr.yaml
  8. +60
    -0
      ShopBundle/Services/MailjetSMS.php
  9. +104
    -123
      ShopBundle/Services/UserUtils.php
  10. +13
    -0
      ShopBundle/Services/Utils.php
  11. +2
    -1
      ShopBundle/Twig/FrontendTwigExtension.php

+ 73
- 63
ShopBundle/Controller/Backend/NewsController.php View File

public function sendTestAction() public function sendTestAction()
{ {
$newsletter = $this->getNewsletter() ; $newsletter = $this->getNewsletter() ;
$news = $this->getNews() ;


$merchantCurrent = $this->merchantUtils->getMerchantCurrent() ;
$merchantConfigEmailContact = $merchantCurrent->getMerchantConfig('email-contact');
if($newsletter) {
$news = $this->getNews() ;

$merchantCurrent = $this->merchantUtils->getMerchantCurrent() ;
$merchantConfigEmailContact = $merchantCurrent->getMerchantConfig('email-contact');


if($merchantConfigEmailContact && strlen($merchantConfigEmailContact)) {
if($merchantConfigEmailContact && strlen($merchantConfigEmailContact)) {
$this->mailUtils->send([ $this->mailUtils->send([
MailUtils::SUBJECT => $news->getTitle(),
MailUtils::TO_EMAIL => $merchantConfigEmailContact,
MailUtils::TO_NAME => $this->parameterBag->get('app.site_name'),
MailUtils::CONTENT_TEMPLATE => 'mail/news',
MailUtils::CONTENT_DATA => [
'news' => $news,
'newsletter' => $newsletter,
'user' => $this->security->getUser()
],
MailUtils::SUBJECT => $news->getTitle(),
MailUtils::TO_EMAIL => $merchantConfigEmailContact,
MailUtils::TO_NAME => $this->parameterBag->get('app.site_name'),
MailUtils::CONTENT_TEMPLATE => 'mail/news',
MailUtils::CONTENT_DATA => [
'news' => $news,
'newsletter' => $newsletter,
'user' => $this->security->getUser()
],
]); ]);


$this->addFlash('success', 'Actualité de test envoyée à '.$merchantConfigEmailContact); $this->addFlash('success', 'Actualité de test envoyée à '.$merchantConfigEmailContact);
}
else {
}
else {
throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ; throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ;
}
} }


return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ; return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;


$currentMerchant = $this->merchantUtils->getMerchantCurrent() ; $currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
$newsletter = $this->getNewsletter() ; $newsletter = $this->getNewsletter() ;
$news = $this->getNews() ;
$users = $this->em->getRepository($this->em->getClassMetadata(UserInterface::class)->getName())->findAllByNewsletter($newsletter) ;


$countUsers = count($users) ;
if($newsletter) {
$news = $this->getNews() ;
$users = $this->em->getRepository($this->em->getClassMetadata(UserInterface::class)->getName())->findAllByNewsletter($newsletter) ;


$packageMessagesArray = [];
$packageMessageLimit = 50 ;
$countUsers = count($users) ;


$paramsTemplate = [
$packageMessagesArray = [];
$packageMessageLimit = 50 ;

$paramsTemplate = [
'news' => $news, 'news' => $news,
'newsletter' => $newsletter, 'newsletter' => $newsletter,
'user' => $this->security->getUser() 'user' => $this->security->getUser()
] ;
] ;


$i = 0 ;
$i = 0 ;


foreach ($users as $user) {
foreach ($users as $user) {
$paramsTemplate['user'] =$user; $paramsTemplate['user'] =$user;


if(!isset($packageMessagesArray[$i])) { if(!isset($packageMessagesArray[$i])) {
$packageMessagesArray[$i] = [] ;
$packageMessagesArray[$i] = [] ;
} }


if($user->getEmail() && strlen($user->getEmail())) { if($user->getEmail() && strlen($user->getEmail())) {
$packageMessagesArray[$i][] = [
'To' => [
[
'Email' => $user->getEmail(),
'Name' => $user->getFirstname().' '.$user->getLastname(),
]
],
'From' => [
'Email' => $this->getParameter('app.noreply_email'),
'Name' => $this->getParameter('app.site_name')
],
'Subject' => $currentMerchant->getMerchantConfig('email-subject-prefix').' '.$news->getTitle(),
'TextPart' => $this->renderView('mail/news-text.html.twig', $paramsTemplate),
'HTMLPart' => $this->renderView('mail/news-html.html.twig', $paramsTemplate),
'CustomCampaign' => $news->getTitle(),
'DeduplicateCampaign' => true
] ;
if(count($packageMessagesArray[$i]) >= $packageMessageLimit) {
$i ++ ;
}
$packageMessagesArray[$i][] = [
'To' => [
[
'Email' => $user->getEmail(),
'Name' => $user->getFirstname().' '.$user->getLastname(),
]
],
'From' => [
'Email' => $this->getParameter('app.noreply_email'),
'Name' => $this->getParameter('app.site_name')
],
'Subject' => $currentMerchant->getMerchantConfig('email-subject-prefix').' '.$news->getTitle(),
'TextPart' => $this->renderView('mail/news-text.html.twig', $paramsTemplate),
'HTMLPart' => $this->renderView('mail/news-html.html.twig', $paramsTemplate),
'CustomCampaign' => $news->getTitle(),
'DeduplicateCampaign' => true
] ;
if(count($packageMessagesArray[$i]) >= $packageMessageLimit) {
$i ++ ;
}
} }
}
}


if($countUsers > 0) {
if($countUsers > 0) {
$mj = new \Mailjet\Client($this->mailjetTransport->getApiKey(), $this->mailjetTransport->getApiSecret(),true,['version' => 'v3.1']); $mj = new \Mailjet\Client($this->mailjetTransport->getApiKey(), $this->mailjetTransport->getApiSecret(),true,['version' => 'v3.1']);


foreach($packageMessagesArray as $messagesArray) { foreach($packageMessagesArray as $messagesArray) {
$body = [
'Messages' => $messagesArray
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$body = [
'Messages' => $messagesArray
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
} }


if(isset($response) && $response->success()) { if(isset($response) && $response->success()) {
$this->addFlash('success', 'Actualité envoyée à '.$countUsers.' utilisateurs.');
$this->addFlash('success', 'Actualité envoyée à '.$countUsers.' utilisateurs.');


$news->setIsSent(true) ;
$this->em->persist($news);
$this->em->flush() ;
$news->setIsSent(true) ;
$this->em->persist($news);
$this->em->flush() ;
} }
else { else {
$this->addFlash('error', "Une erreur est survenue lors de l'envoi de l'actualité.");
$this->addFlash('error', "Une erreur est survenue lors de l'envoi de l'actualité.");
} }
}
else {
}
else {
$this->addFlash('error', 'Aucun utilisateur inscrit à la newsletter.'); $this->addFlash('error', 'Aucun utilisateur inscrit à la newsletter.');
}
} }


return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ; return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;


public function getNewsletter() public function getNewsletter()
{ {
$newsletter = $this->merchantUtils->getMerchantCurrent()->getNewsletter() ;
$news = $this->getNews() ;


if($newsletter) {
return $newsletter ;
if($news) {
$newsletter = $news->getNewsletter() ;
}

if(isset($newsletter) && $newsletter) {
return $newsletter ;
} }
else { else {
throw new \ErrorException('Aucune newsletter n\'est liée à ce Merchant.') ;
$this->utils->addFlash('error', 'Aucune newsletter n\'est liée à l\'actualité.');
} }
} }



+ 41
- 0
ShopBundle/Form/DataTransformer/NewsletterSignupToBooleanTransformer.php View File

<?php

namespace Lc\ShopBundle\Form\DataTransformer;

use Lc\ShopBundle\Context\ProductInterface;
use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Services\UtilsManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Security\Core\Security;

class NewsletterSignupToBooleanTransformer implements DataTransformerInterface
{
private $security ;
private $userUtils ;

public function __construct(Security $security, UtilsManager $utilsManager)
{
$this->security = $security;
$this->userUtils = $utilsManager->getUserUtils() ;
}

public function transform($newsletter)
{
$user = $this->security->getUser() ;

if($user && $newsletter) {
return $this->userUtils->isSubscribedToNewsletter($user, $newsletter) ;
}

return false ;
}

public function reverseTransform($isSubscribed)
{
// Impossible de retrouver la newsletter depuis sa valeur booléenne.
//throw new TransformationFailedException('Impossible de retrouver la newsletter depuis sa valeur booléenne.') ;

return false ;
}
}

+ 14
- 8
ShopBundle/Form/Frontend/RegistrationType.php View File

public function __construct(UtilsManager $utilsManager) public function __construct(UtilsManager $utilsManager)
{ {
$this->utils = $utilsManager->getUtils() ; $this->utils = $utilsManager->getUtils() ;
$this->merchantUtils = $utilsManager->getMerchantUtils() ;
} }


public function getParent() public function getParent()


public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$newsletters = $this->merchantUtils->getMerchantCurrent()->getNewsletters() ;

$builder->remove('username') $builder->remove('username')
->add('gender', ChoiceType::class, [ ->add('gender', ChoiceType::class, [
'label' => 'field.default.title', 'label' => 'field.default.title',
->add('phone', TextType::class, [ ->add('phone', TextType::class, [
'label' => 'field.default.phone', 'label' => 'field.default.phone',
'translation_domain' => 'lcshop', 'translation_domain' => 'lcshop',
])
->add('subscribeNewsletter', CheckboxType::class, [
'data' => true,
'label' => 'field.default.subscribeNewsletter',
'required' => false,
'mapped' => false,
'translation_domain' => 'lcshop',
'help' => 'Un seul mail par semaine qui annonce l’ouverture des ventes, les nouveautés et promotions de la semaine ainsi que des informations utiles.'
]); ]);


foreach($newsletters as $newsletter) {
$builder->add('newsletter_'.$newsletter->getId(), CheckboxType::class, [
//'label' => 'field.default.subscribeNewsletter',
'label' => $newsletter->getTitle(),
'required' => false,
'mapped' => false,
'translation_domain' => 'lcshop',
'help' => $newsletter->getDescription()
]);
}

// captcha // captcha
$this->utils->addCaptchaType($builder); $this->utils->addCaptchaType($builder);
} }

+ 9
- 3
ShopBundle/Manager/EntityManager.php View File

protected $security; protected $security;
protected $userSystem = null; protected $userSystem = null;


public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager, Security $security)
public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager,
Security $security)
{ {
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
{ {


if ($this->security->getUser() === null) { if ($this->security->getUser() === null) {
$entity->setUpdatedBy($this->getUserSystem());
$entity->setCreadtedBy($this->getUserSystem());
if(method_exists($entity, 'setUpdatedBy')) {
$entity->setUpdatedBy($this->getUserSystem());
}
if(method_exists($entity, 'setCreadtedBy')) {
$entity->setCreadtedBy($this->getUserSystem());
}
} }

$this->persist($entity); $this->persist($entity);
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT); $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
return $this; return $this;

+ 6
- 2
ShopBundle/Model/Merchant.php View File

public function getNewsletter() public function getNewsletter()
{ {
$newsletters = $this->getNewsletters() ; $newsletters = $this->getNewsletters() ;
if(isset($newsletters[0])) {
return $newsletters[0] ;

foreach($newsletters as $newsletter) {
if($newsletter->getIsMain()) {
return $newsletter ;
}
} }

return false ; return false ;
} }



+ 17
- 0
ShopBundle/Model/Newsletter.php View File

*/ */
protected $users; protected $users;


/**
* @ORM\Column(type="boolean", nullable=true)
*/
protected $isMain;

public function __toString() public function __toString()
{ {
return $this->getTitle() ; return $this->getTitle() ;


return $this; return $this;
} }

public function getIsMain(): ?bool
{
return $this->isMain;
}

public function setIsMain(?bool $isMain): self
{
$this->isMain = $isMain;

return $this;
}
} }

+ 1
- 0
ShopBundle/Resources/translations/lcshop.fr.yaml View File

displaySpecificDay: Disponible un jour spécifique displaySpecificDay: Disponible un jour spécifique
groupUsers: Groupes groupUsers: Groupes
ticketTypesNotification: Catégorie ticket ticketTypesNotification: Catégorie ticket
newsletter: Newsletter


PointSale: PointSale:
code: Code code: Code

+ 60
- 0
ShopBundle/Services/MailjetSMS.php View File

<?php

namespace Lc\ShopBundle\Services ;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class MailjetSMS
{
protected $client ;
protected $parameterBag ;

public function __construct(HttpClientInterface $client, ParameterBagInterface $parameterBag)
{
$this->client = $client ;
$this->parameterBag = $parameterBag ;
}

public function send($to, $message)
{
$token = $this->parameterBag->get('mailjet.sms.token') ;
$from = $this->parameterBag->get('mailjet.sms.from') ;

if($token && strlen($token) > 0) {
$response = $this->client->request(
'POST',
'https://api.mailjet.com/v4/sms-send',
[
'headers' => [
'Authorization' => 'Bearer '.$token,
//'Content-Type' => 'application/json',
],
'json' => [
'From' => $from,
'To' => $to,
'Text' => $message,
]
]
);

$statusCode = $response->getStatusCode();

if($statusCode == 200) {
$content = $response->getContent();
$content = $response->toArray();
return $content ;
}
else {
// log
}

return false ;
}
else {
throw new \ErrorException('Le token SMS Mailjet n\'est pas défini.') ;
}

}
}

+ 104
- 123
ShopBundle/Services/UserUtils.php View File



class UserUtils class UserUtils
{ {
protected $parameterBag;
protected $em;
protected $utils;
protected $requestStack;
protected $visitorRepository;
protected $merchantUtils;
protected $cookieChecker;
protected $visitor;

public function __construct(ParameterBagInterface $parameterBag, EntityManagerInterface $em, Utils $utils,
RequestStack $requestStack, MerchantUtilsInterface $merchantUtils, CookieChecker $cookieChecker,
Security $security)
{
$this->em = $em;
$this->parameterBag = $parameterBag;
$this->utils = $utils;
$this->requestStack = $requestStack;
$this->visitorRepository = $this->em->getRepository($this->em->getClassMetadata(VisitorInterface::class)->getName());
$this->merchantUtils = $merchantUtils;
$this->cookieChecker = $cookieChecker;
$this->security = $security;
}

public function getCookieNameVisitor()
{
return $this->parameterBag->get('app.cookie_name_visitor');
}

public function cryptCookie($data)
{
return base64_encode($data);
}

public function decryptCookie($data)
{
return base64_decode($data);
}

public function setCookieVisitor($response, $cookie)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($cookie), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));
}

public function updateVisitorCookie($response)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($this->getVisitorCurrent()->getCookie()), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));

}

public function getVisitor($cookie)
{
if (!isset($this->visitor[$cookie])) {
$this->visitor[$cookie] = $this->visitorRepository->findOneBy(['cookie' => $cookie]);
protected $parameterBag;
protected $em;
protected $utils;
protected $requestStack;
protected $visitorRepository;
protected $merchantUtils;
protected $cookieChecker;
protected $visitor;

public function __construct(ParameterBagInterface $parameterBag, EntityManagerInterface $em, Utils $utils,
RequestStack $requestStack, MerchantUtilsInterface $merchantUtils, CookieChecker $cookieChecker,
Security $security)
{
$this->em = $em;
$this->parameterBag = $parameterBag;
$this->utils = $utils;
$this->requestStack = $requestStack;
$this->visitorRepository = $this->em->getRepository($this->em->getClassMetadata(VisitorInterface::class)->getName());
$this->merchantUtils = $merchantUtils;
$this->cookieChecker = $cookieChecker;
$this->security = $security;
} }
return $this->visitor[$cookie];
}

public function getVisitorCurrent()
{
$cookie = $this->requestStack->getCurrentRequest()->cookies->get($this->getCookieNameVisitor());
return $this->getVisitor($cookie);
}

public function addVisitor($cookie, $ip)
{
$classVisitor = $this->em->getClassMetadata(VisitorInterface::class)->getName();
$visitor = new $classVisitor;

$visitor->setCookie($cookie);
$visitor->setIp($ip);
$visitor->setTotalVisit(1);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function updateVisitor($visitor)
{
$totalVisit = $visitor->getTotalVisit() + 1;
$visitor->setTotalVisit($totalVisit);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function setNewsletter($user, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent();
$newsletters = $currentMerchant->getNewsletters();

if($newsletters && count($newsletters) > 0) {
if ($subscribeNewsletter) {
$user->addNewsletter($newsletters[0]);
}
else {
$user->removeNewsletter($newsletters[0]);
}

public function getCookieNameVisitor()
{
return $this->parameterBag->get('app.cookie_name_visitor');
}

public function cryptCookie($data)
{
return base64_encode($data);
}

public function decryptCookie($data)
{
return base64_decode($data);
}

public function setCookieVisitor($response, $cookie)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($cookie), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));
}

public function updateVisitorCookie($response)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($this->getVisitorCurrent()->getCookie()), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));

}

public function getVisitor($cookie)
{
if (!isset($this->visitor[$cookie])) {
$this->visitor[$cookie] = $this->visitorRepository->findOneBy(['cookie' => $cookie]);
}
return $this->visitor[$cookie];
}

public function getVisitorCurrent()
{
$cookie = $this->requestStack->getCurrentRequest()->cookies->get($this->getCookieNameVisitor());
return $this->getVisitor($cookie);
}

public function addVisitor($cookie, $ip)
{
$classVisitor = $this->em->getClassMetadata(VisitorInterface::class)->getName();
$visitor = new $classVisitor;

$visitor->setCookie($cookie);
$visitor->setIp($ip);
$visitor->setTotalVisit(1);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function updateVisitor($visitor)
{
$totalVisit = $visitor->getTotalVisit() + 1;
$visitor->setTotalVisit($totalVisit);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
} }


$this->em->persist($user);
$this->em->flush();
}

/*public function setNewsletter($user, $newsletter, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
$newsletters = $currentMerchant->getNewsletters() ;

foreach($newsletters as $newsletterMerchant) {
if($newsletterMerchant == $newsletter) {
if($subscribeNewsletter) {
$user->addNewsletter($newsletter) ;
}
else {
$user->removeNewsletter($newsletter) ;
}
public function setNewsletter($user, $newsletter, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent();
$newsletters = $currentMerchant->getNewsletters();

foreach ($newsletters as $newsletterMerchant) {
if ($newsletterMerchant->getId() == $newsletter->getId()) {
if ($subscribeNewsletter) {
$user->addNewsletter($newsletter);
} else {
$user->removeNewsletter($newsletter);
}
}
} }
}


$this->em->persist($user) ;
$this->em->flush() ;
}*/
$this->em->persist($user);
$this->em->flush();
}


public function isSubscribedToNewsletter($user, $newsletter)
{
return $user->getNewsletters()->contains($newsletter);
}
public function isSubscribedToNewsletter($user, $newsletter)
{
return $user->getNewsletters()->contains($newsletter);
}


} }

+ 13
- 0
ShopBundle/Services/Utils.php View File

return round((($price * 100)) / 100, $precision); return round((($price * 100)) / 100, $precision);
} }


public function formatPhoneNumber($phone)
{
$phone = preg_replace('`[^0-9]`', '', $phone);
if(strlen($phone) == 10) {
$phone = '+33'.substr($phone, 1, 9) ;
}
elseif(strlen($phone) == 11 && substr($phone, 0, 2) == '33') {
$phone = '+'.$phone ;
}

return $phone ;
}



} }

+ 2
- 1
ShopBundle/Twig/FrontendTwigExtension.php View File



namespace Lc\ShopBundle\Twig; namespace Lc\ShopBundle\Twig;


use App\Services\NotificationUtils;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\MerchantInterface; use Lc\ShopBundle\Context\MerchantInterface;
use Lc\ShopBundle\Context\MerchantUtilsInterface; use Lc\ShopBundle\Context\MerchantUtilsInterface;
new TwigFunction('get_merchants', [$this, 'getMerchants']), new TwigFunction('get_merchants', [$this, 'getMerchants']),
new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']), new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']),
new TwigFunction('lc_format_price', [$this, 'formatPrice']), new TwigFunction('lc_format_price', [$this, 'formatPrice']),
new TwigFunction('get_form_manage_notifications', [$this, 'getFormManageNotifications']),
); );
} }


{ {
return $this->merchantRepository->findAll(); return $this->merchantRepository->findAll();
} }

} }

Loading…
Cancel
Save