<?php
namespace App\EventSubscriber;
use App\Entity\Campaign;
use App\Entity\SystemEmail;
use App\Entity\User;
use App\Event\SubContractor\SubContractorCompletedProfileEvent;
use App\Event\SubContractor\SubContractorMissionAddedEvent;
use App\Event\SubContractor\SubContractorReferencedEvent;
use App\Event\SubContractor\SubContractorServiceAddedEvent;
use App\Event\SubContractor\SubContractorActivatedEvent;
use App\Event\SubContractorRelaunchedEvent;
use App\Event\SubContractorUpdatedEvent;
use App\Repository\SystemEmailRepository;
use App\Repository\UserRepository;
use App\Service\FrontAPIService;
use App\Service\MessageService;
use App\Service\NotificationService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Enum\AdminMail;
use App\Enum\Notification;
use App\Event\User\PasswordResetEmailEvent;
use App\Event\User\UserMentionnedEvent;
use App\Event\SubContractor\SubContractorEvaluateMissionEvent;
use App\Event\SubContractor\SubContractorRequestEvaluateMissionEvent;
use App\Event\SubContractor\SubContractorMarginProblemEvent;
use App\Event\User\SendEmailBeforeDeletedEvent;
use App\Event\User\SendEmailOneMonthBeforeDeletedEvent;
use App\Event\User\UserLoginWithoutPasswordEvent;
use App\Event\User\UserReactionEvent;
use App\Repository\ChatNotificationRepository;
use App\Service\ShortcodeService;
use Symfony\Component\Mime\Address;
use App\Repository\FileMessageRepository;
use App\Repository\MessageRepository;
use App\Service\GoogleStorageService;
use Twig\Environment;
class UserSubscriber implements EventSubscriberInterface
{
public function __construct(
private FrontAPIService $frontAPIService,
private SystemEmailRepository $systemEmailRepository,
private UserRepository $userRepository,
private ShortcodeService $shortcodeService,
private NotificationService $notificationService,
private ChatNotificationRepository $chatNotificationRepository,
private FileMessageRepository $fileMessageRepository,
private MessageRepository $messageRepository,
private GoogleStorageService $googleStorageService,
private MessageService $messageService,
private Environment $twig,
){}
public static function getSubscribedEvents()
{
return [
UserMentionnedEvent::NAME => "onUserMentionnedInTchat",
UserReactionEvent::NAME=>"onUserReactionInMessage",
PasswordResetEmailEvent::NAME => 'onUserResetPassword',
SendEmailBeforeDeletedEvent::NAME => 'onSendEmailBeforeDeletedEvent',
SendEmailOneMonthBeforeDeletedEvent::NAME => 'onSendEmailOneMonthBeforeDeletedEvent',
UserLoginWithoutPasswordEvent::NAME => 'onUserLoginWithoutPasswordEvent'
];
}
public function onUserLoginWithoutPasswordEvent(UserLoginWithoutPasswordEvent $event){
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::LOGIN_WITHOUT_PASSWORD]);
$user = $event->getUser();
$this->notificationService->create($email, $user, $user);
}
public function onUserResetPassword(PasswordResetEmailEvent $event){
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::RESET_PASSWORD]);
$user = $event->getUser();
$this->notificationService->create($email, $user, $user);
}
public function onUserReactionInMessage(UserReactionEvent $event){
$messageCampaingId = $event->getCampaign()->getId();
$to = $event->getTo();
$from = $event->getFrom();
$emoji = $event->getEmoji();
$message = $event->getMessage();
$attachments = null;
$linkAttachments = null;
$filelinksUrl = null;
$displayCodeToAddInMissionInMailHeader = true;
$content = "<p>Bonjour {$to->getFullName()}</p>
<div>{$from->getFullName()} a réagi à votre message : {$message->getContent() }
<p>(Réaction : $emoji)</p>
</div>";
$this->notificationService->sendEmail(
new Address('caroline.b@my-flow.fr', 'myFlow'),
new Address($to->getEmail()),
"{$from->getFullName()} a réagi à votre message",
$content,
$attachments,
$linkAttachments,
$filelinksUrl,
$displayCodeToAddInMissionInMailHeader,
$messageCampaingId
);
}
public function onUserMentionnedInTchat(UserMentionnedEvent $event) {
$mission = $event->getMission();
$campaign = $mission->getCampaign();
$user = $event->getUser();
$message = $event->getMessage();
$messageId = $event->getMessageId();
$destinationMail = $event->getUserEmail();
$messageObj = $this->messageRepository->findOneBy(['id'=>$messageId]);
$linksFileMessages =[];
$render = $this->twig->render('emails/new_message.html.twig',[
'message'=> $messageObj,
'sendTo'=> $user,
'user_second_color'=>'#08085c',
'user_primary_color'=> '#08085c'
]
);
foreach ($messageObj->getFileMessages() as $fileMessage) {
if ($fileMessage->isIsNew()) {
$nameOfFileinBucket = "Campaigns/{$mission->getCampaign()->getId()}/{$fileMessage->getName()}";
$nameOfBucket = "company-{$mission->getCampaign()->getCompany()->getId()}";
$link = $this->googleStorageService->getUrlBucket(strtolower($nameOfBucket),$nameOfFileinBucket);
}
else {
$link = "{$this->getParameter('back_website_url')}/{$this->messageService->getFileMissionUrl($mission, $fileMessage->getName())}";
}
$linksFileMessages[]=[
'link'=>$link,
'name'=>$fileMessage->getName()
];
}
if ($user !=null && $this->canSendEmailToUser($user)) {
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::USER_MENTIONNED]);
$user = $this->setEmailForContactProject(user:$user);
// $emailParsed = $this->shortcodeService->parse($email->getContent(), $user, $campaign->getCompany(),null, $campaign, null, null,null, null, null, null, $message);
$this->notificationService->sendEmail(
from: new Address('operation@my-flow.fr'),
to: new Address($destinationMail),
subject: $email->getSubject(),
content: $render,
attachments: null,
linkAttachments: null,
filelinksUrl: $linksFileMessages,
displayCodeToAddInMissionInMailHeader : true,
campaignId: $campaign->getId(),
user: null,
messageId: $messageId,
);
$this->removePreviewNotificationToSendTo($user, $campaign);
}
else {
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::ALL_USER_MENTIONNED]);
foreach ($this->getUserParticipants($campaign,$messageObj?->getDiscussionGroup()) as $user) {
if ($this->canSendEmailToUser($user)) {
$this->removePreviewNotificationToSendTo($user, $campaign);
$user = $this->setEmailForContactProject(user:$user);
// $emailParsed = $this->shortcodeService->parse($email->getContent(), $user, $campaign->getCompany(),null, $campaign, null, null,null, null, null, null, $message);
$this->notificationService->sendEmail(
from: new Address('operation@my-flow.fr'),
to: new Address($user->getEmail()),
subject: $email->getSubject(),
content: $render,
attachments: null,
linkAttachments: null,
filelinksUrl: $linksFileMessages,
displayCodeToAddInMissionInMailHeader : true,
campaignId: $campaign->getId(),
);
}
}
}
}
public function onSendEmailBeforeDeletedEvent(SendEmailBeforeDeletedEvent $event){
$user = $event->getUser();
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::EMAIL_BEFORE_DELETED_USER]);
$this->notificationService->create($email, $user, $user);
}
public function onSendEmailOneMonthBeforeDeletedEvent(SendEmailOneMonthBeforeDeletedEvent $event){
$user = $event->getUser();
$email = $this->systemEmailRepository->findOneBy(['code' => SystemEmail::EMAIL_ONE_MONTH_BEFORE_DELETED_USER]);
$this->notificationService->create($email, $user, $user);
}
private function getUserParticipants(Campaign $campaign,$groupedMessage = null){
$ids = [];
$allParticipantWithAdmin = [];
if (!is_null($groupedMessage)) {
foreach ($groupedMessage->getUsers() as $userInGroup) {
if (!in_array($userInGroup->getId(), $ids) and !$userInGroup->getDeleted() and $userInGroup->isEnabled()) {
$ids[] = $userInGroup->getId();
$allParticipantWithAdmin[] = $userInGroup;
}
}
}else{
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if (!in_array($participant->getUser()->getId(), $ids) and !$participant->getUser()->getDeleted() and $participant->getUser()->isEnabled()) {
$ids[] = $participant->getUser()->getId();
$allParticipantWithAdmin[] = $participant->getUser();
}
}
}
}
return $allParticipantWithAdmin ;
}
private function setEmailForContactProject(User $user){
if ($user->getId()=="Kb8bh3rBpsRukYgsMoYM9v") {
$adminEmail = $this->userRepository->findOneBy(['email'=>"michael.lh@my-flow.fr"]) ;
return $adminEmail != null ? $adminEmail : $user;
}
if ($user->getId()=="L15WDFhbcUcwtNFtBB2r5Q") {
$adminEmail = $this->userRepository->findOneBy(['email'=>"thomas.s@my-flow.fr"]);
return $adminEmail != null ? $adminEmail : $user;
}
return $user;
}
private function canSendEmailToUser(User $user){
// return (($user->getLastActivityInMinute() > 10 || !$user->isLogged()) && !is_null($user->getFreqNotificationEverytime()) && in_array(Notification::MENTIONNED_TO_ME->value, $user->getFreqNotificationEverytime())) ? true : false;
return (!is_null($user->getFreqNotificationEverytime()) && in_array(Notification::MENTIONNED_TO_ME->value, $user->getFreqNotificationEverytime())) ? true : false;
}
private function removePreviewNotificationToSendTo(User $user,Campaign $campaign){
$chatNotifications = $this->chatNotificationRepository->findNextNotificationToSend($user,$campaign);
}
}