Browse Source

[Administration] Envoi automatique d'emails

feature/rotating_product
Guillaume Bourgeois 5 months ago
parent
commit
1899224f6e
14 changed files with 431 additions and 366 deletions
  1. +35
    -67
      backend/controllers/CommunicateController.php
  2. +2
    -282
      backend/models/MailForm.php
  3. +3
    -1
      backend/views/communicate/email.php
  4. +7
    -6
      common/components/BulkMailer/BulkMailerBrevo.php
  5. +3
    -1
      common/components/BulkMailer/BulkMailerInterface.php
  6. +8
    -7
      common/components/BulkMailer/BulkMailerMailjet.php
  7. +3
    -2
      common/components/BulkMailer/BulkMailerProxy.php
  8. +1
    -0
      common/components/BusinessLogic.php
  9. +6
    -0
      common/components/BusinessLogicTrait.php
  10. +81
    -0
      domain/Communication/Email/ContactListResolver.php
  11. +67
    -0
      domain/Communication/Email/Email.php
  12. +27
    -0
      domain/Communication/Email/EmailBuilder.php
  13. +151
    -0
      domain/Communication/Email/EmailManager.php
  14. +37
    -0
      domain/Communication/Email/EmailModule.php

+ 35
- 67
backend/controllers/CommunicateController.php View File

@@ -40,8 +40,10 @@ namespace backend\controllers;

use backend\models\MailForm;
use common\helpers\GlobalParam;
use kartik\mpdf\Pdf;
use domain\Communication\Email\ContactListResolver;
use domain\Communication\Email\EmailManager;
use domain\PointSale\PointSale\PointSale;
use kartik\mpdf\Pdf;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

@@ -84,91 +86,57 @@ class CommunicateController extends BackendController
$usersPointSaleHasOrder = 0,
$idDistribution = 0)
{
$producerCurrent = $this->getProducerCurrent();
$userModule = $this->getUserModule();
$distributionModule = $this->getDistributionModule();
$emailModule = $this->getEmailModule();
$emailManager = $emailModule->getManager();
$mailForm = new MailForm();
// Sujet et message par défaut
$mailForm->subject = $this->getProducerModule()->getSolver()->getConfig('option_communicate_email_default_subject');
$mailForm->message = $this->getProducerModule()->getSolver()->getConfig('option_communicate_email_default_message');

if ($idPointSale && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
$usersPointSaleLink = 1;
}
if ($idDistribution && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
$usersPointSaleLink = 1;
}

if($idDistribution) {
$users = [];
$distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
if($distribution) {
$mailForm->id_distribution = $idDistribution;
foreach($distribution->pointSaleDistribution as $pointSaleDistribution) {
if($pointSaleDistribution->delivery) {
$usersPointSaleArray = $userModule->getRepository()->queryUsersBy([
'id_producer' => $producerCurrent->id,
'id_point_sale' => $pointSaleDistribution->id_point_sale,
'users_point_sale_link' => $usersPointSaleLink,
'users_point_sale_has_order' => $usersPointSaleHasOrder,
'newsletter' => true
])->all();

foreach($usersPointSaleArray as $user) {
$users[$user['id']] = $user;
}
}
}
}
}
else {
$users = $userModule->queryUsersBy([
'id_producer' => GlobalParam::getCurrentProducerId(),
'id_point_sale' => $idPointSale,
'users_point_sale_link' => $usersPointSaleLink,
'users_point_sale_has_order' => $usersPointSaleHasOrder,
'subscribers' => $sectionSubscribers,
'inactive' => $sectionInactiveUsers,
'newsletter' => true
])->all();
}

$usersArray = [];
foreach ($users as $key => $user) {
if (isset($user['email']) && strlen($user['email']) > 0) {
if($this->getProducerCurrent()->isDemoAccount()) {
$usersArray[] = \Yii::$app->faker->email();
}
else {
$usersArray[] = $user['email'];
}
} else {
unset($users[$key]);
}
}

$pointsSaleArray = PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId(), 'status' => 1])->all();

$pointSale = null;
if ($idPointSale) {
$pointSale = PointSale::findOne(['id' => $idPointSale]);
$pointSale = $idPointSale ? $this->getPointSaleModule()->getRepository()->findOnePointSaleById($idPointSale) : null;
$distribution = $idDistribution ? $this->getDistributionModule()->getRepository()->findOneDistributionById($idDistribution) : null;
if($distribution) {
$mailForm->id_distribution = $distribution->id;
}

$usersArray = $emailModule->getContactListResolver()->search(
$this->getProducerCurrent(),
$distribution,
$pointSale,
$usersPointSaleLink,
$usersPointSaleHasOrder,
$sectionSubscribers,
$sectionInactiveUsers
);

if ($mailForm->load(\Yii::$app->request->post()) && $mailForm->validate()) {

if($this->getProducerCurrent()->isDemoAccount()) {
$this->setFlash('error', "Fonctionnalité désactivée sur le compte de démo.");
}
else {
$mailForm->sendEmail($users);
$distribution = $mailForm->id_distribution
? $this->getDistributionModule()->getRepository()->findOneDistributionById($mailForm->id_distribution)
: null;

$email = $emailManager->createEmail(
$mailForm->subject,
$mailForm->message,
$mailForm->integrate_product_list,
$this->getProducerCurrent(),
$distribution
);
$emailManager->sendBulkEmail($email, $usersArray);

$this->setFlash('success', 'Votre email a bien été envoyé.');
}

return $this->redirect(['email', 'idPointSale' => $idPointSale]);
}

$incomingDistributionsArray = $distributionModule->findDistributionsIncoming();
$pointsSaleArray = PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId(), 'status' => 1])->all();

$incomingDistributionsArray = $this->getDistributionModule()->getRepository()->findDistributionsIncoming();
$incomingDistributionsDatesArray = ['0' => '--'];
foreach ($incomingDistributionsArray as $distribution) {
$incomingDistributionsDatesArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date));

+ 2
- 282
backend/models/MailForm.php View File

@@ -39,20 +39,10 @@ termes.
namespace backend\models;

use common\helpers\GlobalParam;
use common\helpers\Mailjet;
use common\helpers\Price;
use domain\Config\Unit\UnitDefinition;
use domain\Distribution\Distribution\Distribution;
use domain\Communication\Email\EmailManager;
use domain\Distribution\Distribution\DistributionModule;
use domain\Producer\Producer\ProducerModule;
use domain\Product\Product\Product;
use domain\Product\Product\ProductModule;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Yii;
use yii\base\Model;
use yii\helpers\Html;

/**
* ContactForm is the model behind the contact form.
@@ -62,7 +52,7 @@ class MailForm extends Model
public $id_distribution ;
public $subject;
public $message;
public $integrate_product_list = false;
public $integrate_product_list;

/**
* @inheritdoc
@@ -88,274 +78,4 @@ class MailForm extends Model
'integrate_product_list' => 'Intégrer la liste des produits au message'
];
}

public function sendEmail($contactsArray, $fromProducer = true)
{
$productModule = ProductModule::getInstance();
$producerModule = ProducerModule::getInstance();
$distributionModule = DistributionModule::getInstance();

$messageAutoText = '' ;
$messageAutoHtml = '' ;

$messageAutoHtml .= ' <style type="text/css">
h1, h2, h3, h4, h5, h6 {
padding: 0px;
margin: 0px;
margin-bottom: 10px;
}
p {
margin: 0px;
padding: 0px;
margin-bottom: 5px;
}
</style>';

if($this->id_distribution) {

$messageAutoText = '

' ;
$messageAutoHtml .= '<br /><br />' ;

$distribution = Distribution::searchOne(['id' => $this->id_distribution]) ;

if($distribution) {

$linkOrder = $distributionModule->getLinkOrder($distribution);
$dateOrder = strftime('%A %d %B %Y', strtotime($distribution->date)) ;
$messageAutoHtml .= '<a href="'.$linkOrder.'">Passer ma commande du '.$dateOrder.'</a>' ;
$messageAutoText .= 'Suivez ce lien pour passer votre commande du '.$dateOrder.' :
'.$linkOrder ;

if($this->integrate_product_list) {
$productsArray = Product::find()
->where([
'id_producer' => GlobalParam::getCurrentProducerId(),
])
->andWhere('status >= :status')
->addParams(['status' => Product::STATUS_OFFLINE])
->innerJoinWith(['productDistribution' => function($query) use($distribution) {
$query->andOnCondition([
'product_distribution.id_distribution' => $distribution->id,
'product_distribution.active' => 1
]);
}])
->orderBy('product.name ASC')
->all();

if(count($productsArray) > 1) {
$messageAutoHtml .= '<br /><br />Produits disponibles : <br /><ul>' ;
$messageAutoText .= '

Produits disponibles :
' ;
foreach($productsArray as $product) {

$productDescription = $product->name ;
if(strlen($product->description)) {
$productDescription .= ' / '.$product->description ;
}
if($product->price) {
$productDescription .= ' / '.Price::format($productModule->getPriceWithTax($product)) ;
$productDescription .= ' ('. $productModule->getSolver()->strUnit($product, UnitDefinition::WORDING_UNIT).')' ;
}

$messageAutoText .= '- '.$productDescription.'
' ;
$messageAutoHtml .= '<li>'.Html::encode($productDescription).'</li>' ;
}
$messageAutoHtml .= '</ul>' ;
}
}
}
}

if($fromProducer) {
$producer = GlobalParam::getCurrentProducer() ;
$fromEmail = $producerModule->getProducerEmailPlatform($producer) ;
$fromName = $producer->name ;

$linkProducer = 'https://'.$producer->slug.'.souke.fr';
$linkUnsubscribe = Yii::$app->urlManagerProducer->createAbsoluteUrl(['newsletter/unsubscribe', 'slug_producer' => $producer->slug]);

// Message inscription newsletter
$messageAutoText .= "

--
Boutique : ".$linkProducer."
Me désinscrire : ".$linkUnsubscribe;

$messageAutoHtml .= "<br /><br />--<br>";
$messageAutoHtml .= "Boutique : <a href=\"".$linkProducer."\">".$linkProducer."</a><br>";
$messageAutoHtml .= "Me désinscrire : <a href=\"".$linkUnsubscribe."\">".$linkUnsubscribe."</a>";
}
else {
$fromEmail = 'contact@souke.fr' ;
$fromName = 'Souke' ;
}

$subject = $this->subject;
$htmlContent = nl2br($this->message).$messageAutoHtml;
$textContent = $this->message.$messageAutoText;

Yii::$app->bulkMailer->sendEmails($contactsArray, $fromName, $fromEmail, $subject, $htmlContent, $textContent);
}

/*

public function sendEmailMailjet($usersArray, $fromProducer = true)
{
$productModule = ProductModule::getInstance();
$producerModule = ProducerModule::getInstance();
$distributionModule = DistributionModule::getInstance();

$mj = new \Mailjet\Client(
Mailjet::getApiKey('public'),
Mailjet::getApiKey('private'),
true,
['version' => 'v3.1']
);

$messageAutoText = '' ;
$messageAutoHtml = '' ;

$messageAutoHtml .= ' <style type="text/css">
h1, h2, h3, h4, h5, h6 {
padding: 0px;
margin: 0px;
margin-bottom: 10px;
}

p {
margin: 0px;
padding: 0px;
margin-bottom: 5px;
}
</style>';

if($this->id_distribution) {

$messageAutoText = '

' ;
$messageAutoHtml .= '<br /><br />' ;

$distribution = Distribution::searchOne(['id' => $this->id_distribution]) ;

if($distribution) {

$linkOrder = $distributionModule->getLinkOrder($distribution);
$dateOrder = strftime('%A %d %B %Y', strtotime($distribution->date)) ;
$messageAutoHtml .= '<a href="'.$linkOrder.'">Passer ma commande du '.$dateOrder.'</a>' ;
$messageAutoText .= 'Suivez ce lien pour passer votre commande du '.$dateOrder.' :
'.$linkOrder ;

if($this->integrate_product_list) {
$productsArray = Product::find()
->where([
'id_producer' => GlobalParam::getCurrentProducerId(),
])
->andWhere('status >= :status')
->addParams(['status' => Product::STATUS_OFFLINE])
->innerJoinWith(['productDistribution' => function($query) use($distribution) {
$query->andOnCondition([
'product_distribution.id_distribution' => $distribution->id,
'product_distribution.active' => 1
]);
}])
->orderBy('product.name ASC')
->all();

if(count($productsArray) > 1) {
$messageAutoHtml .= '<br /><br />Produits disponibles : <br /><ul>' ;
$messageAutoText .= '

Produits disponibles :
' ;
foreach($productsArray as $product) {

$productDescription = $product->name ;
if(strlen($product->description)) {
$productDescription .= ' / '.$product->description ;
}
if($product->price) {
$productDescription .= ' / '.Price::format($productModule->getPriceWithTax($product)) ;
$productDescription .= ' ('. $productModule->getSolver()->strUnit($product, UnitDefinition::WORDING_UNIT).')' ;
}

$messageAutoText .= '- '.$productDescription.'
' ;
$messageAutoHtml .= '<li>'.Html::encode($productDescription).'</li>' ;
}
$messageAutoHtml .= '</ul>' ;
}
}
}
}

if($fromProducer) {
$producer = GlobalParam::getCurrentProducer() ;
$fromEmail = $producerModule->getProducerEmailPlatform($producer) ;
$fromName = $producer->name ;

$linkProducer = 'https://'.$producer->slug.'.souke.fr';
$linkUnsubscribe = Yii::$app->urlManagerProducer->createAbsoluteUrl(['newsletter/unsubscribe', 'slug_producer' => $producer->slug]);

// Message inscription newsletter
$messageAutoText .= "

--
Boutique : ".$linkProducer."
Me désinscrire : ".$linkUnsubscribe;

$messageAutoHtml .= "<br /><br />--<br>";
$messageAutoHtml .= "Boutique : <a href=\"".$linkProducer."\">".$linkProducer."</a><br>";
$messageAutoHtml .= "Me désinscrire : <a href=\"".$linkUnsubscribe."\">".$linkUnsubscribe."</a>";
}
else {
$fromEmail = 'contact@souke.fr' ;
$fromName = 'Souke' ;
}

$body = ['Messages' => []] ;

foreach($usersArray as $user) {
$body['Messages'][] = [
'From' => [
'Email' => $fromEmail,
'Name' => $fromName
],
'To' => [
[
'Email' => $user['email'],
'Name' => $user['name'].' '.$user['lastname']
]
],
'Subject' => $this->subject,
'TextPart' => $this->message.$messageAutoText,
'HTMLPart' => nl2br($this->message).$messageAutoHtml
] ;

if(count($body['Messages']) == 50) {
$response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]);
$body['Messages'] = [] ;
}
}

if(count($body['Messages']) > 0) {
$response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]);
}

$success = (isset($response) && $response) ? $response->success() : false ;

if(!$success) {
Yii::error($response->getBody(), 'Mailjet');
}

return $response ;
}

*/
}

+ 3
- 1
backend/views/communicate/email.php View File

@@ -100,7 +100,9 @@ $this->render('@backend/views/user/_menu_filter.php',[
<br /><br />
<?php endif; ?>

<?= implode(', ', $usersArray); ?>
<?= implode(', ', array_map(function($user) {
return $user['email'];
}, $usersArray)); ?>
</div>
</div>
</div>

+ 7
- 6
common/components/BulkMailer/BulkMailerBrevo.php View File

@@ -2,27 +2,28 @@

namespace common\components\BulkMailer;

use domain\Communication\Email\Email;
use domain\User\User\UserSolver;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

class BulkMailerBrevo implements BulkMailerInterface
{
public function sendEmails(array $contactsArray, string $fromName, string $fromEmail, string $subject, string $htmlContent, string $textContent = null)
public function sendEmail(Email $email, array $usersArray)
{
$userSolver = UserSolver::getInstance();
$client = new Client();
$data = [
'sender' => [
'name' => $fromName,
'email' => $fromEmail
'name' => $email->getFromName(),
'email' => $email->getFromEmail()
],
'bcc' => [],
'subject' => $subject,
'htmlContent' => $htmlContent
'subject' => $email->getSubject(),
'htmlContent' => $email->getHtmlContent()
] ;

foreach($contactsArray as $user) {
foreach($usersArray as $user) {
$data['bcc'][] = [
'name' => $userSolver->getUsernameFromArray($user),
'email' => $user['email']

+ 3
- 1
common/components/BulkMailer/BulkMailerInterface.php View File

@@ -2,10 +2,12 @@

namespace common\components\BulkMailer;

use domain\Communication\Email\Email;

interface BulkMailerInterface
{
const MAILJET = 'mailjet';
const BREVO = 'brevo';

public function sendEmails(array $contactsArray, string $fromName, string $fromEmail, string $subject, string $htmlContent, string $textContent = null);
public function sendEmail(Email $email, array $usersArray);
}

+ 8
- 7
common/components/BulkMailer/BulkMailerMailjet.php View File

@@ -3,11 +3,12 @@
namespace common\components\BulkMailer;

use common\helpers\Mailjet;
use domain\Communication\Email\Email;
use Mailjet\Client;

class BulkMailerMailjet implements BulkMailerInterface
{
public function sendEmails(array $contactsArray, string $fromName, string $fromEmail, string $subject, string $htmlContent, string $textContent = null)
public function sendEmail(Email $email, array $usersArray)
{
$client = new Client(
Mailjet::getApiKey('public'),
@@ -18,11 +19,11 @@ class BulkMailerMailjet implements BulkMailerInterface

$data = ['Messages' => []] ;

foreach($contactsArray as $user) {
foreach($usersArray as $user) {
$data['Messages'][] = [
'From' => [
'Email' => $fromEmail,
'Name' => $fromName
'Email' => $email->getFromEmail(),
'Name' => $email->getFromName()
],
'To' => [
[
@@ -30,9 +31,9 @@ class BulkMailerMailjet implements BulkMailerInterface
'Name' => $user['name'].' '.$user['lastname']
]
],
'Subject' => $subject,
'HTMLPart' => $htmlContent,
'TextPart' => $textContent
'Subject' => $email->getSubject(),
'HTMLPart' => $email->getHtmlContent(),
'TextPart' => $email->getTextContent()
] ;

if(count($data['Messages']) == 50) {

+ 3
- 2
common/components/BulkMailer/BulkMailerProxy.php View File

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

namespace common\components\BulkMailer;

use domain\Communication\Email\Email;
use domain\Setting\AdminSettingBag;
use yii\base\ErrorException;

@@ -22,8 +23,8 @@ class BulkMailerProxy implements BulkMailerInterface
}
}

public function sendEmails(array $contactsArray, string $fromName, string $fromEmail, string $subject, string $htmlContent, string $textContent = null)
public function sendEmail(Email $email, array $usersArray)
{
$this->getBulkMailer()->sendEmails($contactsArray, $fromName, $fromEmail, $subject, $htmlContent, $textContent);
$this->getBulkMailer()->sendEmail($email, $usersArray);
}
}

+ 1
- 0
common/components/BusinessLogic.php View File

@@ -26,6 +26,7 @@ class BusinessLogic
$this->getUserProducerModule(),
$this->getUserPointSaleModule(),
$this->getUserModule(),
$this->getEmailModule(),
$this->getAutomaticEmailModule(),
$this->getUserMessageModule(),
$this->getPointSaleDistributionModule(),

+ 6
- 0
common/components/BusinessLogicTrait.php View File

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

namespace common\components;

use domain\Communication\Email\EmailModule;
use domain\Config\TaxRate\TaxRateModule;
use domain\Config\Unit\UnitModule;
use domain\Distribution\Distribution\DistributionModule;
@@ -45,6 +46,11 @@ use domain\User\UserUserGroup\UserUserGroupModule;

trait BusinessLogicTrait
{
public function getEmailModule(): EmailModule
{
return EmailModule::getInstance();
}

public function getAutomaticEmailModule(): AutomaticEmailModule
{
return AutomaticEmailModule::getInstance();

+ 81
- 0
domain/Communication/Email/ContactListResolver.php View File

@@ -0,0 +1,81 @@
<?php

namespace domain\Communication\Email;

use common\helpers\GlobalParam;
use domain\_\AbstractResolver;
use domain\Distribution\Distribution\Distribution;
use domain\PointSale\PointSale\PointSale;
use domain\Producer\Producer\Producer;
use domain\User\User\UserRepository;

class ContactListResolver extends AbstractResolver
{
protected UserRepository $userRepository;

public function loadDependencies(): void
{
$this->userRepository = $this->loadService(UserRepository::class);
}

public function search(
Producer $producer,
Distribution $distribution = null,
PointSale $pointSale = null,
bool $usersPointSaleLink = false,
bool $usersPointSaleHasOrder = false,
bool $isSubscriber = false,
bool $isInactive = false
): array
{
if ($pointSale && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
$usersPointSaleLink = 1;
}
if ($distribution && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
$usersPointSaleLink = 1;
}

if($distribution) {
$users = [];

foreach($distribution->pointSaleDistribution as $pointSaleDistribution) {
if($pointSaleDistribution->delivery) {
$usersPointSaleArray = $this->userRepository->queryUsersBy([
'id_producer' => $producer->id,
'id_point_sale' => $pointSaleDistribution->id_point_sale,
'users_point_sale_link' => $usersPointSaleLink,
'users_point_sale_has_order' => $usersPointSaleHasOrder,
'newsletter' => true
])->all();

foreach($usersPointSaleArray as $user) {
$users[$user['id']] = $user;
}
}
}
}
else {
$users = $this->userRepository->queryUsersBy([
'id_producer' => GlobalParam::getCurrentProducerId(),
'id_point_sale' => $pointSale ? $pointSale->id : null,
'users_point_sale_link' => $usersPointSaleLink,
'users_point_sale_has_order' => $usersPointSaleHasOrder,
'subscribers' => $isSubscriber,
'inactive' => $isInactive,
'newsletter' => true
])->all();
}

$usersArray = [];
foreach ($users as $user) {
if (isset($user['email']) && strlen($user['email']) > 0) {
if($producer->isDemoAccount()) {
$user['email'] = \Yii::$app->faker->email();
}
$usersArray[] = $user;
}
}

return $usersArray;
}
}

+ 67
- 0
domain/Communication/Email/Email.php View File

@@ -0,0 +1,67 @@
<?php

namespace domain\Communication\Email;

class Email
{
protected string $fromName;
protected string $fromEmail;
protected string $subject;
protected string $htmlContent;
protected string $textContent;

public function getFromName(): string
{
return $this->fromName;
}

public function setFromName(string $fromName): self
{
$this->fromName = $fromName;
return $this;
}

public function getFromEmail(): string
{
return $this->fromEmail;
}

public function setFromEmail(string $fromEmail): self
{
$this->fromEmail = $fromEmail;
return $this;
}

public function getSubject(): string
{
return $this->subject;
}

public function setSubject(string $subject): self
{
$this->subject = $subject;
return $this;
}

public function getHtmlContent(): string
{
return $this->htmlContent;
}

public function setHtmlContent(string $htmlContent): self
{
$this->htmlContent = $htmlContent;
return $this;
}

public function getTextContent(): string
{
return $this->textContent;
}

public function setTextContent(string $textContent): self
{
$this->textContent = $textContent;
return $this;
}
}

+ 27
- 0
domain/Communication/Email/EmailBuilder.php View File

@@ -0,0 +1,27 @@
<?php

namespace domain\Communication\Email;

use domain\_\AbstractBuilder;

class EmailBuilder extends AbstractBuilder
{
public function instanciateEmail(
string $fromName,
string $fromEmail,
string $subject,
string $htmlContent,
string $textContent
): Email
{
$email = new Email();

$email->setFromName($fromName);
$email->setFromEmail($fromEmail);
$email->setSubject($subject);
$email->setHtmlContent($htmlContent);
$email->setTextContent($textContent);

return $email;
}
}

+ 151
- 0
domain/Communication/Email/EmailManager.php View File

@@ -0,0 +1,151 @@
<?php

namespace domain\Communication\Email;

use common\helpers\GlobalParam;
use common\helpers\Price;
use domain\_\AbstractResolver;
use domain\Config\Unit\UnitDefinition;
use domain\Distribution\Distribution\Distribution;
use domain\Distribution\Distribution\DistributionSolver;
use domain\Producer\Producer\Producer;
use domain\Producer\Producer\ProducerSolver;
use domain\Product\Product\Product;
use domain\Product\Product\ProductSolver;
use yii\helpers\Html;

class EmailManager extends AbstractResolver
{
protected EmailBuilder $emailBuilder;
protected ProductSolver $productSolver;
protected DistributionSolver $distributionSolver;
protected ProducerSolver $producerSolver;

public function loadDependencies(): void
{
$this->emailBuilder = $this->loadService(EmailBuilder::class);
$this->productSolver = $this->loadService(ProductSolver::class);
$this->distributionSolver = $this->loadService(DistributionSolver::class);
$this->producerSolver = $this->loadService(ProducerSolver::class);
}

public function sendBulkEmail(Email $email, array $usersArray)
{
\Yii::$app->bulkMailer->sendEmail($email, $usersArray);
}

public function createEmail(
string $subject,
string $message,
bool $integrateProductList,
Producer $producer = null,
Distribution $distribution = null
): Email
{
$messageAutoText = '' ;
$messageAutoHtml = '' ;

$messageAutoHtml .= ' <style type="text/css">
h1, h2, h3, h4, h5, h6 {
padding: 0px;
margin: 0px;
margin-bottom: 10px;
}
p {
margin: 0px;
padding: 0px;
margin-bottom: 5px;
}
</style>';

if($distribution) {
$messageAutoText = '

' ;
$messageAutoHtml .= '<br /><br />' ;

$linkOrder = $this->distributionSolver->getLinkOrder($distribution);
$dateOrder = strftime('%A %d %B %Y', strtotime($distribution->date)) ;
$messageAutoHtml .= '<a href="'.$linkOrder.'">Passer ma commande du '.$dateOrder.'</a>' ;
$messageAutoText .= 'Suivez ce lien pour passer votre commande du '.$dateOrder.' :
'.$linkOrder ;

if($integrateProductList) {
$productsArray = Product::find()
->where([
'id_producer' => $producer->id,
])
->andWhere('status >= :status')
->addParams(['status' => Product::STATUS_OFFLINE])
->innerJoinWith(['productDistribution' => function($query) use($distribution) {
$query->andOnCondition([
'product_distribution.id_distribution' => $distribution->id,
'product_distribution.active' => 1
]);
}])
->orderBy('product.name ASC')
->all();

if(count($productsArray) > 0) {

$messageAutoHtml .= '<br /><br />Produits disponibles : <br /><ul>' ;
$messageAutoText .= '

Produits disponibles :
' ;
foreach($productsArray as $product) {

$productDescription = $product->name ;
if(strlen($product->description)) {
$productDescription .= ' / '.$product->description ;
}
if($product->price) {
$productDescription .= ' / '.Price::format($this->productSolver->getPriceWithTax($product)) ;
$productDescription .= ' ('. $this->productSolver->strUnit($product, UnitDefinition::WORDING_UNIT).')' ;
}

$messageAutoText .= '- '.$productDescription.'
' ;
$messageAutoHtml .= '<li>'.Html::encode($productDescription).'</li>' ;
}
$messageAutoHtml .= '</ul>' ;
}
}
}

if($producer) {
$fromEmail = $this->producerSolver->getProducerEmailPlatform($producer) ;
$fromName = $producer->name ;

$linkProducer = 'https://'.$producer->slug.'.souke.fr';
$linkUnsubscribe = \Yii::$app->urlManagerProducer->createAbsoluteUrl(['newsletter/unsubscribe', 'slug_producer' => $producer->slug]);

// Message inscription newsletter
$messageAutoText .= "

--
Boutique : ".$linkProducer."
Me désinscrire : ".$linkUnsubscribe;

$messageAutoHtml .= "<br /><br />--<br>";
$messageAutoHtml .= "Boutique : <a href=\"".$linkProducer."\">".$linkProducer."</a><br>";
$messageAutoHtml .= "Me désinscrire : <a href=\"".$linkUnsubscribe."\">".$linkUnsubscribe."</a>";
}
else {
$fromEmail = 'contact@souke.fr' ;
$fromName = 'Souke' ;
}

$htmlContent = nl2br($message).$messageAutoHtml;
$textContent = $message.$messageAutoText;

return $this->emailBuilder->instanciateEmail(
$fromName,
$fromEmail,
$subject,
$htmlContent,
$textContent
);
}
}

+ 37
- 0
domain/Communication/Email/EmailModule.php View File

@@ -0,0 +1,37 @@
<?php

namespace domain\Communication\Email;

use domain\_\AbstractService;

class EmailModule extends AbstractService
{
public function getEntityFqcn(): string
{
return '';
}

public function getServices(): array
{
return [
EmailBuilder::class,
ContactListResolver::class,
EmailManager::class,
];
}

public function getBuilder(): EmailBuilder
{
return EmailBuilder::getInstance();
}

public function getManager(): EmailManager
{
return EmailManager::getInstance();
}

public function getContactListResolver(): ContactListResolver
{
return ContactListResolver::getInstance();
}
}

Loading…
Cancel
Save