浏览代码

Adaptations newsletters + MailjetSMS

develop
Guillaume 3 年前
父节点
当前提交
de75266686
共有 11 个文件被更改,包括 340 次插入200 次删除
  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 查看文件

@@ -31,28 +31,31 @@ class NewsController extends AdminController
public function sendTestAction()
{
$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([
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);
}
else {
}
else {
throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ;
}
}

return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;
@@ -65,77 +68,80 @@ class NewsController extends AdminController

$currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
$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,
'newsletter' => $newsletter,
'user' => $this->security->getUser()
] ;
] ;

$i = 0 ;
$i = 0 ;

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

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

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']);

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()) {
$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 {
$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.');
}
}

return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;
@@ -143,13 +149,17 @@ class NewsController extends AdminController

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 {
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 查看文件

@@ -0,0 +1,41 @@
<?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 查看文件

@@ -17,6 +17,7 @@ class RegistrationType extends AbstractType
public function __construct(UtilsManager $utilsManager)
{
$this->utils = $utilsManager->getUtils() ;
$this->merchantUtils = $utilsManager->getMerchantUtils() ;
}

public function getParent()
@@ -26,6 +27,8 @@ class RegistrationType extends AbstractType

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

$builder->remove('username')
->add('gender', ChoiceType::class, [
'label' => 'field.default.title',
@@ -48,16 +51,19 @@ class RegistrationType extends AbstractType
->add('phone', TextType::class, [
'label' => 'field.default.phone',
'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
$this->utils->addCaptchaType($builder);
}

+ 9
- 3
ShopBundle/Manager/EntityManager.php 查看文件

@@ -20,7 +20,8 @@ class EntityManager
protected $security;
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->entityManager = $entityManager;
@@ -46,9 +47,14 @@ class EntityManager
{

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->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
return $this;

+ 6
- 2
ShopBundle/Model/Merchant.php 查看文件

@@ -349,9 +349,13 @@ abstract class Merchant extends AbstractDocumentEntity
public function getNewsletter()
{
$newsletters = $this->getNewsletters() ;
if(isset($newsletters[0])) {
return $newsletters[0] ;

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

return false ;
}


+ 17
- 0
ShopBundle/Model/Newsletter.php 查看文件

@@ -24,6 +24,11 @@ abstract class Newsletter extends AbstractDocumentEntity implements FilterMercha
*/
protected $users;

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

public function __toString()
{
return $this->getTitle() ;
@@ -73,4 +78,16 @@ abstract class Newsletter extends AbstractDocumentEntity implements FilterMercha

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 查看文件

@@ -307,6 +307,7 @@ field:
displaySpecificDay: Disponible un jour spécifique
groupUsers: Groupes
ticketTypesNotification: Catégorie ticket
newsletter: Newsletter

PointSale:
code: Code

+ 60
- 0
ShopBundle/Services/MailjetSMS.php 查看文件

@@ -0,0 +1,60 @@
<?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 查看文件

@@ -13,134 +13,115 @@ use Symfony\Component\Security\Core\Security;

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 查看文件

@@ -602,5 +602,18 @@ class Utils
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 查看文件

@@ -2,6 +2,7 @@

namespace Lc\ShopBundle\Twig;

use App\Services\NotificationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\MerchantInterface;
use Lc\ShopBundle\Context\MerchantUtilsInterface;
@@ -59,6 +60,7 @@ class FrontendTwigExtension extends AbstractExtension
new TwigFunction('get_merchants', [$this, 'getMerchants']),
new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']),
new TwigFunction('lc_format_price', [$this, 'formatPrice']),
new TwigFunction('get_form_manage_notifications', [$this, 'getFormManageNotifications']),
);
}

@@ -104,5 +106,4 @@ class FrontendTwigExtension extends AbstractExtension
{
return $this->merchantRepository->findAll();
}

}

正在加载...
取消
保存