Browse Source

Gestion déliverabilité emails

feature/rotating_product
Guillaume 5 months ago
parent
commit
823303513b
24 changed files with 711 additions and 17 deletions
  1. +39
    -0
      backend/controllers/UserAdminController.php
  2. +28
    -0
      backend/controllers/UserController.php
  3. +29
    -12
      backend/views/dashboard-admin/index.php
  4. +6
    -0
      backend/views/layouts/left.php
  5. +124
    -0
      backend/views/user-admin/email_deliverability.php
  6. +11
    -1
      backend/views/user-admin/index.php
  7. +3
    -1
      backend/views/user/_form.php
  8. +2
    -0
      backend/views/user/_menu_navigation.php
  9. +2
    -2
      backend/views/user/index.php
  10. +101
    -0
      backend/views/user/messages.php
  11. +9
    -0
      backend/views/user/view.php
  12. +1
    -0
      common/components/BusinessLogic.php
  13. +6
    -0
      common/components/BusinessLogicTrait.php
  14. +37
    -0
      console/migrations/m240611_125313_create_table_user_message.php
  15. +12
    -0
      domain/User/User/UserRepository.php
  16. +6
    -0
      domain/User/User/UserRepositoryQuery.php
  17. +10
    -1
      domain/User/User/UserSearch.php
  18. +108
    -0
      domain/User/UserMessage/UserMessage.php
  19. +20
    -0
      domain/User/UserMessage/UserMessageBuilder.php
  20. +13
    -0
      domain/User/UserMessage/UserMessageDefinition.php
  21. +29
    -0
      domain/User/UserMessage/UserMessageManager.php
  22. +38
    -0
      domain/User/UserMessage/UserMessageModule.php
  23. +49
    -0
      domain/User/UserMessage/UserMessageRepository.php
  24. +28
    -0
      domain/User/UserMessage/UserMessageRepositoryQuery.php

+ 39
- 0
backend/controllers/UserAdminController.php View File

@@ -41,6 +41,7 @@ namespace backend\controllers;
use domain\User\User\UserSearch;
use Yii;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;

class UserAdminController extends BackendController
{
@@ -81,6 +82,35 @@ class UserAdminController extends BackendController
]);
}

public function actionEmailDeliverability()
{
$searchModel = new UserSearch();
$searchModel->problem_receiving_emails = true;
$dataProvider = $searchModel->search([
'UserSearch' => isset(\Yii::$app->request->queryParams['UserSearch']) ?
Yii::$app->request->queryParams['UserSearch'] : []
]);

return $this->render('email_deliverability', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
}

public function actionReportProblemReceivingEmails(int $id)
{
$user = $this->findModel($id);

if($this->getUserModule()->getManager()->reportProblemReceivingEmails($user)) {
$this->setFlash('success', "L'utilisateur <strong>".$this->getUserModule()->getSolver()->getUsername($user)."</strong> a bien été signalé comme ayant des problèmes dans la réception de vos emails. L'administrateur débloquera la situation dès que possible et préviendra l'utilisateur.");
}
else {
$this->setFlash('error', "Une erreur est survenue.");
}

return $this->redirect('index');
}

public function actionRedirectView(int $idUserProducer)
{
$userCurrent = $this->getUserCurrent();
@@ -96,4 +126,13 @@ class UserAdminController extends BackendController
return $this->redirectReferer();
}
}

protected function findModel($id)
{
if (($user = $this->getUserModule()->findOneUserById($id)) !== null) {
return $user;
} else {
throw new NotFoundHttpException("Utilisateur introuvable");
}
}
}

+ 28
- 0
backend/controllers/UserController.php View File

@@ -258,6 +258,34 @@ class UserController extends BackendController
]));
}

public function actionMessages(int $id)
{
$userMessageModule = $this->getUserMessageModule();
$user = $this->findModel($id);
$userMessageModel = $userMessageModule->getBuilder()->instanciateUserMessage(
$user,
$this->getUserCurrent()
);

if($userMessageModel->load(\Yii::$app->request->post()) && $userMessageModel->validate()) {
$userMessageModule->getManager()->createUserMessage(
$user,
$userMessageModel->getMessage(),
$this->getUserCurrent()
);
$this->setFlash('success', "Le message a bien été envoyé à l'utilisateur.");
return $this->redirect(['messages', 'id' => $id]);
}

return $this->render('messages', [
'user' => $user,
'userMessageModel' => $userMessageModel,
'userMessagesDataProvider' => $userMessageModule->getRepository()
->queryUserMessagesByUser($user)
->getDataProvider(20)
]);
}

public function actionReportProblemReceivingEmails(int $id)
{
$user = $this->findModel($id);

+ 29
- 12
backend/views/dashboard-admin/index.php View File

@@ -10,18 +10,13 @@ $this->setMetaRefresh(true);
?>

<div class="dashboard-admin-index">
<div class="row">
<div class="col-lg-6 col-xs-6">
<?= AdminLTE::smallBox(
$countUsersOnline,
'En ligne',
$countUsersOnline ? 'green' : 'blue',
'wifi',
Yii::$app->urlManager->createUrl('online-admin/index')
) ?>

<div id="producers-online" class="box box-solid">
<div class="box-header with-border">
<i class="fa fa-bookmark"></i>
<h3 class="box-title">Producteurs en ligne</h3>
</div>
<div class="col-lg-6 col-xs-6" id="producers-online">
<!--<h3>Producteurs en ligne :</h3>-->
<div class="box-body">
<?php if($usersWithStatusProducerOnlineArray && count($usersWithStatusProducerOnlineArray) > 0): ?>
<?php foreach ($usersWithStatusProducerOnlineArray as $userWithStatusProducerOnline): ?>
<?php $producer = $userWithStatusProducerOnline->producer; ?>
@@ -33,10 +28,32 @@ $this->setMetaRefresh(true);
<?php endforeach; ?>
<div class="clr"></div>
<?php else: ?>
<div class="alert alert-info">Aucun producteur en ligne actuellement.</div>
<p><em>Aucun producteur en ligne actuellement.</em></p>
<?php endif; ?>
</div>
</div>

<div class="row">
<div class="col-lg-6 col-xs-6">
<?= AdminLTE::smallBox(
$countUsersOnline,
'Utilisateurs en ligne',
$countUsersOnline ? 'green' : 'blue',
'wifi',
Yii::$app->urlManager->createUrl('online-admin/index')
) ?>
</div>
<div class="col-lg-6 col-xs-6">
<?php $countUsersWithProblemReceivingEmails = $this->getUserModule()->getRepository()->countUsersWithProblemReceivingEmails(); ?>
<?= AdminLTE::smallBox(
$countUsersWithProblemReceivingEmails,
'Problèmes réception emails',
$countUsersWithProblemReceivingEmails ? 'red' : 'green',
'send',
Yii::$app->urlManager->createUrl('user-admin/email-deliverability')
) ?>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-xs-6">
<?= AdminLTE::smallBox(

+ 6
- 0
backend/views/layouts/left.php View File

@@ -145,6 +145,12 @@ $isUserCurrentGrantedAsProducer = $userModule->getAuthorizationChecker()->isGran
'url' => ['/user-admin/index'],
'visible' => $isUserCurrentGrantedAsAdministrator
],
[
'label' => 'Deliverabilité emails',
'icon' => 'paper-plane',
'url' => ['/user-admin/email-deliverability'],
'visible' => $isUserCurrentGrantedAsAdministrator
],
[
'label' => 'Statistiques',
'icon' => 'line-chart',

+ 124
- 0
backend/views/user-admin/email_deliverability.php View File

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

/**
* Copyright Souke (2018)
*
* contact@souke.fr
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/

use common\helpers\GlobalParam;
use common\helpers\Price;
use domain\Order\Order\Order;
use domain\Producer\Producer\ProducerModule;
use domain\User\User\User;
use domain\User\User\UserModule;
use domain\User\UserProducer\UserProducer;
use domain\User\UserProducer\UserProducerModule;
use yii\grid\GridView;
use yii\helpers\Html;
use domain\User\UserGroup\UserGroupModule;

$userModule = UserModule::getInstance();
$producerModule = ProducerModule::getInstance();
$userCurrent = GlobalParam::getCurrentUser();
$userGroupModule = UserGroupModule::getInstance();
$userProducerModule = UserProducerModule::getInstance();

$this->setTitle('Déliverabilité des emails');
$this->addBreadcrumb($this->getTitle());

?>

<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'summary' =>
'Affichage de <b>{begin, number}-{end, number}</b> sur <b>{totalCount, number}</b> {totalCount, plural, one{élément} other{éléments}}.',
'columns' => [
[
'attribute' => 'username',
'label' => 'Nom',
'value' => function ($user) use ($userModule) {
return $userModule->getUsername($user);
}
],
[
'attribute' => 'type',
'label' => 'Type',
'headerOptions' => ['class' => 'column-hide-on-mobile'],
'filterOptions' => ['class' => 'column-hide-on-mobile'],
'contentOptions' => ['class' => 'column-hide-on-mobile'],
'filter' => $userModule->getTypeChoicesArray(),
'value' => function ($user) use ($userModule) {
return $userModule->getTypeLabel($user['type']);
}
],
[
'attribute' => 'contacts',
'header' => 'Contacts',
'format' => 'raw',
'headerOptions' => ['class' => 'column-hide-on-mobile'],
'filterOptions' => ['class' => 'column-hide-on-mobile'],
'contentOptions' => ['class' => 'column-hide-on-mobile'],
'value' => function ($user) {
$html = '';
if (strlen($user['phone'])) {
$html .= $user['phone'];
}
if (strlen($user['phone']) && strlen($user['email'])) {
$html .= '<br />';
}
if (strlen($user['email'])) {
$html .= $user['email'];
}
return $html;
}
],
[
'attribute' => 'producers',
'label' => 'Producteurs',
'format' => 'raw',
'contentOptions' => ['class' => 'column-hide-on-mobile align-center'],
'value' => function ($user) use ($userProducerModule) {
$html = '';
$userProducersArray = $userProducerModule->getRepository()->findUserProducersByUser($user);

foreach($userProducersArray as $userProducer) {
$html .= '<a href="'.Yii::$app->urlManager->createUrl(['user-admin/redirect-view', 'idUserProducer' => $userProducer->id]).'" class="btn btn-default"><span class="glyphicon glyphicon-eye-open"></span> '.$userProducer->producer->name.'</a> ';
}

return $html;
}
]
],
]); ?>

+ 11
- 1
backend/views/user-admin/index.php View File

@@ -122,7 +122,7 @@ $this->addBreadcrumb($this->getTitle());
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{switch} ',
'template' => '{problemReceivingEmails} {switch}',
'headerOptions' => ['class' => 'column-actions'],
'contentOptions' => ['class' => 'column-actions'],
'buttons' => [
@@ -142,6 +142,16 @@ $this->addBreadcrumb($this->getTitle());
'class' => 'btn btn-default'
]);
},
'problemReceivingEmails' => function($url, $model) use ($userModule, $userCurrent) {
if(!$model->getProblemReceivingEmails()) {
return Html::a('<i class="fa fa-life-ring"></i>',
Yii::$app->urlManager->createUrl(['user-admin/report-problem-receiving-emails', 'id' => $model->id]),
[
'title' => ((int) $model->getProblemReceivingEmails()).' Signaler comme ayant des problèmes de réception des emails',
'class' => 'btn btn-default',
]);
}
},
'switch' => function($url, $model) use ($userModule, $userCurrent) {
if($userModule->getAuthorizationChecker()->isGrantedAsAdministrator($userCurrent)) {
return Html::a('<i class="fa fa-fw fa-user-secret"></i>',

+ 3
- 1
backend/views/user/_form.php View File

@@ -190,7 +190,7 @@ $distributionModule = DistributionModule::getInstance();
'data-on' => 'Oui',
'data-off' => 'Non',
'data-onstyle' => 'danger',
'data-offstyle' => 'success',
'data-offstyle' => 'default',
],
]
); ?>
@@ -212,6 +212,8 @@ $distributionModule = DistributionModule::getInstance();
'data-id' => $model->id,
'data-on' => 'Oui',
'data-off' => 'Non',
'data-onstyle' => 'danger',
'data-offstyle' => 'default',
],
]
)->hint('Si activé, le nom du client sera mis en avant dans la liste des commandes'); ?>

+ 2
- 0
backend/views/user/_menu_navigation.php View File

@@ -10,6 +10,7 @@ $orderModule = OrderModule::getInstance();

$credit = $userModule->getRepository()->getCredit($user);
$countOrders = $orderModule->getRepository()->countOrdersByUser($user);
$countUserMessagesUnread = $this->getUserMessageModule()->getRepository()->countUserMessagesUnreadByUser($user);

?>

@@ -18,6 +19,7 @@ $countOrders = $orderModule->getRepository()->countOrdersByUser($user);
<?= menu_navigation_item('update', 'Profil', $action, $user) ?>
<?= menu_navigation_item('credit', 'Cagnotte <span class="label label-default badge">'.Price::format($credit).'</span>', $action, $user) ?>
<?= menu_navigation_item('orders', 'Commandes <span class="label label-default badge">'.$countOrders.'</span>', $action, $user) ?>
<?= menu_navigation_item('messages', 'Messages <span class="label label-default badge">'.$countUserMessagesUnread.'</span>', $action, $user) ?>
</ul>



+ 2
- 2
backend/views/user/index.php View File

@@ -231,8 +231,8 @@ $this->render('_menu_filter', [
return Html::a('<i class="fa fa-life-ring"></i> Réception emails',
Yii::$app->urlManager->createUrl(['user/report-problem-receiving-emails', 'id' => $model->id]),
[
'title' => 'Signaler comme ayant des problèmes de réception des emails',
'class' => ''
'title' => ((int) $model->getProblemReceivingEmails()).' Signaler comme ayant des problèmes de réception des emails',
'class' => '',
]);
}
},

+ 101
- 0
backend/views/user/messages.php View File

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

/**
* Copyright Souke (2018)
*
* contact@souke.fr
*
* Ce logiciel est un programme informatique servant à aider les producteurs
* à distribuer leur production en circuits courts.
*
* Ce logiciel est régi par la licence CeCILL soumise au droit français et
* respectant les principes de diffusion des logiciels libres. Vous pouvez
* utiliser, modifier et/ou redistribuer ce programme sous les conditions
* de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
* sur le site "http://www.cecill.info".
*
* En contrepartie de l'accessibilité au code source et des droits de copie,
* de modification et de redistribution accordés par cette licence, il n'est
* offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
* seule une responsabilité restreinte pèse sur l'auteur du programme, le
* titulaire des droits patrimoniaux et les concédants successifs.
*
* A cet égard l'attention de l'utilisateur est attirée sur les risques
* associés au chargement, à l'utilisation, à la modification et/ou au
* développement et à la reproduction du logiciel par l'utilisateur étant
* donné sa spécificité de logiciel libre, qui peut le rendre complexe à
* manipuler et qui le réserve donc à des développeurs et des professionnels
* avertis possédant des connaissances informatiques approfondies. Les
* utilisateurs sont donc invités à charger et tester l'adéquation du
* logiciel à leurs besoins dans des conditions permettant d'assurer la
* sécurité de leurs systèmes et ou de leurs données et, plus généralement,
* à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
*
* Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
* pris connaissance de la licence CeCILL, et que vous en avez accepté les
* termes.
*/

use domain\User\User\UserModule;
use yii\grid\GridView;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$userModule = $this->getUserModule();
$orderModule = $this->getOrderModule();
$userModule = $this->getUserModule();
$username = Html::encode($userModule->getSolver()->getUsername($user));
$this->setTitle($username.' (#'.$user->id.')') ;
$this->addBreadcrumb(['label' => 'Utilisateurs', 'url' => ['index']]) ;
$this->addBreadcrumb(['label' => $username]) ;
$this->addBreadcrumb('Messages') ;

?>

<?= $this->render('_menu_navigation', [
'action' => 'messages',
'user' => $user
]); ?>

<div class="user-messages tab-content">

<?php $form = ActiveForm::begin([
'enableClientValidation' => false
]); ?>
<?= $form->field($userMessageModel, 'message')->textarea(['rows' => 4]) ?>
<?= Html::submitButton('Envoyer', ['class' => 'btn btn-primary', 'name' => 'save']) ?>
<?php ActiveForm::end(); ?>
<br />

<?= GridView::widget([
'dataProvider' => $userMessagesDataProvider,
'columns' => [
[
'label' => 'Message',
'format' => 'raw',
'value' => function ($userMessage) {
return nl2br(Html::encode($userMessage->getMessage())).'<br /><br /><em>'.$userMessage->getCreatedAt()->format('\L\e d/m/Y à H:i').'</em>';
}
],
/*[
'label' => 'Création',
'format' => 'raw',
'value' => function ($userMessage) {
return $userMessage->getCreatedAt()->format('d/m/Y à H:i');
}
],*/
[
'label' => 'Lu',
'format' => 'raw',
'value' => function ($userMessage) {
if($userMessage->getReadAt()) {
return '<span class="label label-success" title="'.$userMessage->getReadAt()->format('\L\e d/m/Y à H:i').'">Oui</span>';
}
else {
return '<span class="label label-default">Non</span>';
}
}
],
],
]); ?>
</div>

+ 9
- 0
backend/views/user/view.php View File

@@ -139,6 +139,15 @@ $this->addBreadcrumb('Récapitulatif') ;
</span>
</li>
<?php endif; ?>
<li class="list-group-item">
<strong>Problème réception emails</strong>
<span class="pull-right">
<?php $hasProblemReceivingEmails = $model->problem_receiving_emails; ?>
<span class="label label-<?= $hasProblemReceivingEmails ? 'danger' : 'default' ?>">
<?= $hasProblemReceivingEmails ? 'Oui' : 'Non' ?>
</span>
</span>
</li>
<?php if($model->userPointSale): ?>
<li class="list-group-item">
<strong>Points de vente</strong>

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

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

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

@@ -36,6 +36,7 @@ use domain\Ticket\TicketMessage\TicketMessageModule;
use domain\Ticket\TicketUser\TicketUserModule;
use domain\User\User\UserModule;
use domain\User\UserGroup\UserGroupModule;
use domain\User\UserMessage\UserMessageModule;
use domain\User\UserProducer\UserProducerModule;
use domain\User\UserUserGroup\UserUserGroupModule;

@@ -181,6 +182,11 @@ trait BusinessLogicTrait
return UserModule::getInstance();
}

public function getUserMessageModule(): UserMessageModule
{
return UserMessageModule::getInstance();
}

public function getUserGroupModule(): UserGroupModule
{
return UserGroupModule::getInstance();

+ 37
- 0
console/migrations/m240611_125313_create_table_user_message.php View File

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

use yii\db\Migration;
use yii\db\Schema;

/**
* Class m240611_125313_create_table_user_message
*/
class m240611_125313_create_table_user_message extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('user_message', [
'id' => 'pk',
'id_user' => Schema::TYPE_INTEGER,
'message' => Schema::TYPE_TEXT,
'created_at' => Schema::TYPE_DATETIME,
'created_by' => Schema::TYPE_INTEGER,
'read_at' => Schema::TYPE_DATETIME,
]);
$this->addForeignKey('fk_user_message_id_user', 'user_message', 'id_user', 'user', 'id');
$this->addForeignKey('fk_user_message_created_by', 'user_message', 'created_by', 'user', 'id');
}

/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('user_message');
$this->dropForeignKey('fk_user_message_id_user', 'user_message');
$this->dropForeignKey('fk_user_message_created_by', 'user_message');
}
}

+ 12
- 0
domain/User/User/UserRepository.php View File

@@ -312,4 +312,16 @@ class UserRepository extends AbstractRepository

return $userSystem;
}

public function findUsersWithProblemReceivingEmails()
{
return $this->createQuery()
->filterHasProblemReceivingEmails()
->find();
}

public function countUsersWithProblemReceivingEmails(): int
{
return count($this->findUsersWithProblemReceivingEmails());
}
}

+ 6
- 0
domain/User/User/UserRepositoryQuery.php View File

@@ -61,4 +61,10 @@ class UserRepositoryQuery extends AbstractRepositoryQuery
->addParams(['date' => $date->format('Y-m-d H:i:s')]);
return $this;
}

public function filterHasProblemReceivingEmails(): self
{
$this->andWhere(['problem_receiving_emails' => true]);
return $this;
}
}

+ 10
- 1
domain/User/User/UserSearch.php View File

@@ -54,7 +54,9 @@ class UserSearch extends User
public function rules()
{
return [
[['no_mail', 'mail_distribution_monday', 'mail_distribution_tuesday', 'mail_distribution_wednesday', 'mail_distribution_thursday', 'mail_distribution_friday', 'mail_distribution_saturday', 'mail_distribution_sunday'], 'boolean'],
[['no_mail', 'mail_distribution_monday', 'mail_distribution_tuesday', 'mail_distribution_wednesday',
'mail_distribution_thursday', 'mail_distribution_friday', 'mail_distribution_saturday',
'mail_distribution_sunday', 'problem_receiving_emails'], 'boolean'],
[['lastname', 'name', 'phone', 'address', 'type', 'newsletter', 'contacts'], 'string'],
[['id_point_sale', 'inactive', 'subscribers', 'id_user_user_group'], 'integer'],
[['date_last_connection', 'id_point_sale', 'username'], 'safe'],
@@ -91,6 +93,7 @@ class UserSearch extends User
. '`user`.date_last_connection, '
. '`user`.name_legal_person, '
. '`user`.type, '
. '`user`.problem_receiving_emails, '
. '(SELECT COUNT(*) FROM `order` WHERE `user`.id = `order`.id_user) AS count_orders');

if($producer) {
@@ -181,6 +184,12 @@ class UserSearch extends User
]);
}

if(isset($this->problem_receiving_emails)) {
$query->andWhere([
'user.problem_receiving_emails' => (bool) $this->problem_receiving_emails
]);
}

return $dataProvider;
}
}

+ 108
- 0
domain/User/UserMessage/UserMessage.php View File

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

namespace domain\User\UserMessage;

use common\components\ActiveRecordCommon;
use domain\User\User\User;

class UserMessage extends ActiveRecordCommon
{
public static function tableName()
{
return 'user_message';
}

public function rules()
{
return [
[['id_user', 'message', 'created_at', 'created_by'], 'required'],
[['message'], 'string'],
[['id_user', 'created_by'], 'integer'],
[['created_at', 'read_at'], 'safe']
];
}

public function attributeLabels()
{
return [
'id_user' => 'Utilisateur',
'message' => 'Message',
'created_at' => 'Date de création',
'created_by' => 'Créé par',
'read_at', 'Date de lecture'
];
}

/* Getters / Setters */

public function getId(): ?int
{
return $this->id;
}

public function getUser(): User
{
return $this->userRelation;
}

public function setUser(User $user): self
{
$this->populateFieldObject('id_user', 'userRelation', $user);
return $this;
}

public function getMessage(): string
{
return $this->message;
}

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

public function getCreatedAt(): \DateTime
{
return new \DateTime($this->created_at);
}

public function setCreatedAt(\DateTime $createdAt): self
{
$this->created_at = $createdAt->format('Y-m-d H:i:s');
return $this;
}

public function getCreatedBy(): User
{
return $this->createdByRelation;
}

public function setCreatedBy(User $createdBy): self
{
$this->populateFieldObject('created_by', 'createdByRelation', $createdBy);
return $this;
}

public function getReadAt(): ?\DateTime
{
if($this->read_at) {
return new \DateTime($this->read_at);
}

return null;
}

public function setReadAt(\DateTime $readAt): self
{
$this->read_at = $readAt->format('Y-m-d H:i:s');
return $this;
}

/* Relations */

public function getCreatedByRelation()
{
return $this->hasOne(User::class, ['id' => 'created_by']);
}
}

+ 20
- 0
domain/User/UserMessage/UserMessageBuilder.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractBuilder;
use domain\User\User\User;

class UserMessageBuilder extends AbstractBuilder
{
public function instanciateUserMessage(User $user, User $createdBy): UserMessage
{
$userMessage = new UserMessage();

$userMessage->setUser($user);
$userMessage->setCreatedAt(new \DateTime());
$userMessage->setCreatedBy($createdBy);

return $userMessage;
}
}

+ 13
- 0
domain/User/UserMessage/UserMessageDefinition.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractDefinition;

class UserMessageDefinition extends AbstractDefinition
{
public function getEntityFqcn(): string
{
return UserMessage::class;
}
}

+ 29
- 0
domain/User/UserMessage/UserMessageManager.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractManager;
use domain\User\User\User;

class UserMessageManager extends AbstractManager
{
protected UserMessageBuilder $userMessageBuilder;

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

public function createUserMessage(User $user, string $message, User $createdBy): UserMessage
{
$userMessage = $this->userMessageBuilder->instanciateUserMessage($user, $createdBy);
$userMessage->setMessage($message);
$userMessage->save();
return $userMessage;
}

public function deleteUserMessage(UserMessage $userMessage): bool
{
return $userMessage->delete();
}
}

+ 38
- 0
domain/User/UserMessage/UserMessageModule.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractModule;

class UserMessageModule extends AbstractModule
{
public function getServices(): array
{
return [
UserMessageDefinition::class,
UserMessageBuilder::class,
UserMessageRepository::class,
UserMessageManager::class
];
}

public function getDefinition(): UserMessageDefinition
{
return UserMessageDefinition::getInstance();
}

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

public function getRepository(): UserMessageRepository
{
return UserMessageRepository::getInstance();
}

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

+ 49
- 0
domain/User/UserMessage/UserMessageRepository.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractRepository;
use domain\User\User\User;

class UserMessageRepository extends AbstractRepository
{
protected UserMessageRepositoryQuery $query;

public function loadDependencies(): void
{
$this->loadQuery(UserMessageRepositoryQuery::class);
}

public function getDefaultOptionsSearch(): array
{
return [
self::WITH => [],
self::JOIN_WITH => [],
self::ORDER_BY => 'created_at DESC',
self::ATTRIBUTE_ID_PRODUCER => ''
];
}

public function queryUserMessagesByUser(User $user)
{
return $this->createDefaultQuery()
->filterByUser($user);
}

public function findUserMessagesByUser(User $user): array
{
return $this->queryUserMessagesByUser($user)->find();
}

public function findUserMessagesUnreadByUser(User $user)
{
return $this->queryUserMessagesByUser($user)
->filterIsUnread()
->find();
}

public function countUserMessagesUnreadByUser(User $user): int
{
return count($this->findUserMessagesUnreadByUser($user));
}
}

+ 28
- 0
domain/User/UserMessage/UserMessageRepositoryQuery.php View File

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

namespace domain\User\UserMessage;

use domain\_\AbstractRepositoryQuery;
use domain\User\User\User;

class UserMessageRepositoryQuery extends AbstractRepositoryQuery
{
protected UserMessageDefinition $definition;

public function loadDependencies(): void
{
$this->loadDefinition(UserMessageDefinition::class);
}

public function filterByUser(User $user): self
{
$this->andWhere(['user_message.id_user' => $user->id]);
return $this;
}

public function filterIsUnread(): self
{
$this->andWhere('user_message.read_at IS NULL');
return $this;
}
}

Loading…
Cancel
Save