Skip to content

Commit

Permalink
Créneaux : Alertes : refactoring de l'envoi via l'EmailingEventListen…
Browse files Browse the repository at this point in the history
…er & MattermostEventListener (elefan-grenoble#1057)

* Create MattermostEventListener & ShiftAlertEvent

* Seperate ShiftAlertsEvent & ShiftAlertsMattermostEvent
  • Loading branch information
raphodn authored and OursDesCavernes committed Jan 20, 2024
1 parent a8a4147 commit 92a36d8
Show file tree
Hide file tree
Showing 6 changed files with 236 additions and 67 deletions.
9 changes: 9 additions & 0 deletions app/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ services:
- { name: kernel.event_listener, event: shift.freed, method: onShiftFreed }
- { name: kernel.event_listener, event: shift.reminder, method: onShiftReminder }
- { name: kernel.event_listener, event: shift.deleted, method: onShiftDeleted }
- { name: kernel.event_listener, event: shift.alerts, method: onShiftAlerts }
- { name: kernel.event_listener, event: member.cycle.start, method: onMemberCycleStart }
- { name: kernel.event_listener, event: member.cycle.half, method: onMemberCycleHalf }
- { name: kernel.event_listener, event: member.created, method: onMemberCreated }
Expand All @@ -177,6 +178,14 @@ services:
- { name: kernel.event_listener, event: helloasso.registration_success, method: onHelloassoRegistrationSuccess }
- { name: kernel.event_listener, event: helloasso.too_early, method: onHelloassoTooEarly }
- { name: kernel.event_listener, event: code.new, method: onCodeNew }
mattermost_event_listener:
class: AppBundle\EventListener\MattermostEventListener
arguments:
$entityManager: "@doctrine.orm.entity_manager"
$logger: "@logger"
$container: "@service_container"
tags:
- { name: kernel.event_listener, event: shift.alerts.mattermost, method: onShiftAlerts }

# subscribers
beneficiary_initialization_subscriber:
Expand Down
90 changes: 23 additions & 67 deletions src/AppBundle/Command/SendShiftAlertsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@

use AppBundle\Entity\ShiftAlert;
use AppBundle\Entity\ShiftBucket;
use AppBundle\Event\ShiftAlertsEvent;
use AppBundle\Event\ShiftAlertsMattermostEvent;
use DateTime;
use Swift_Message;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpClient\HttpClient;

class SendShiftAlertsCommand extends ContainerAwareCommand
{
Expand All @@ -33,24 +33,38 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$date_given = $input->getArgument('date');
$jobs = explode(',', $input->getArgument('jobs'));
$emails = $input->getOption('emails') ? explode(',', $input->getOption('emails')) : null;
$email_template = $input->getOption('emailTemplate');
$mattermost_hook_url = $input->getOption('mattermostUrl');
$mattermost_template = $input->getOption('mattermostTemplate');

$date = date_create_from_format('Y-m-d', $date_given);
if (!$date || $date->format('Y-m-d') != $date_given) {
$output->writeln('<fg=red;> wrong date format. Use Y-m-d </>');
$output->writeln('<error>Wrong date format. Use Y-m-d </>');
return;
}
$date->setTime(0, 0);

$alerts = $this->computeAlerts($date, $jobs);
$nbAlerts = count($alerts);
if ($nbAlerts > 0) {
$output->writeln('<fg=cyan;>Found ' . $nbAlerts . ' alerts to send</>');
$this->sendAlertsToMattermost($input, $output, $date, $alerts, $mattermost_template);
$this->sendAlertsByEmail($input, $output, $date, $alerts, $email_template);
if (count($alerts) > 0) {
$output->writeln('<question>Found ' . count($alerts) . ' alert' . ((count($alerts)>1)?'s':'') . ' to send</>');

// email
if ($emails) {
$dispatcher = $this->getContainer()->get('event_dispatcher');
$dispatcher->dispatch(ShiftAlertsEvent::NAME, new ShiftAlertsEvent($alerts, $date, $email_template, $emails));
$output->writeln('<comment>Email(s) sent</>');
}

// mattermost
if ($mattermost_hook_url) {
$dispatcher = $this->getContainer()->get('event_dispatcher');
$dispatcher->dispatch(ShiftAlertsMattermostEvent::NAME, new ShiftAlertsMattermostEvent($alerts, $date, $mattermost_template, $mattermost_hook_url));
$output->writeln('<comment>Alerts posted on Mattermost</>');
}

} else {
$output->writeln('<fg=cyan;>No shift alert to send</>');
$output->writeln('<comment>No shift alert to send</>');
}
}

Expand Down Expand Up @@ -84,62 +98,4 @@ private function computeAlerts(DateTime $date, $jobs) {
}
return $alerts;
}

private function sendAlertsByEmail(InputInterface $input, OutputInterface $output, DateTime $date, $alerts, $template) {
$mailer = $this->getContainer()->get('mailer');
$recipients = $input->getOption('emails') ? explode(',', $input->getOption('emails')) : null;
if ($recipients) {
$dateFormatted = strftime("%A %e %B", $date->getTimestamp());
$subject = '[ALERTE CRENEAUX] ' . $dateFormatted;

$shiftEmail = $this->getContainer()->getParameter('emails.shift');

$em = $this->getContainer()->get('doctrine')->getManager();
$dynamicContent = $em->getRepository('AppBundle:DynamicContent')->findOneByCode($template);
$template = null;
if ($dynamicContent) {
$template = $this->getContainer()->get('twig')->createTemplate($dynamicContent->getContent());
} else {
$template = 'emails/shift_alerts_default.html.twig';
}

$email = (new Swift_Message($subject))
->setFrom($shiftEmail['address'], $shiftEmail['from_name'])
->setTo($recipients)
->setBody(
$this->getContainer()->get('twig')->render(
$template,
array('alerts' => $alerts, 'date' => $date)
),
'text/html'
);
$mailer->send($email);
$output->writeln('<fg=cyan;>Email(s) sent</>');
}
}

private function sendAlertsToMattermost(InputInterface $input, OutputInterface $output, DateTime $date, $alerts, $template) {
$mmHookUrl = $input->getOption('mattermostUrl');
if ($mmHookUrl != null) {
$em = $this->getContainer()->get('doctrine')->getManager();
$dynamicContent = $em->getRepository('AppBundle:DynamicContent')->findOneByCode($template);
$template = null;
if ($dynamicContent) {
$template = $this->getContainer()->get('twig')->createTemplate($dynamicContent->getContent());
} else {
$template = 'markdown/shift_alerts_default.md.twig';
}
$content = $this->getContainer()->get('twig')->render(
$template,
array('alerts' => $alerts, 'date' => $date)
);

$client = HttpClient::create();
$response = $client->request('POST', $mmHookUrl, [
'json' => ['text' => $content]
]);
}
$output->writeln('<fg=cyan;>Alerts posted on Mattermost</>');
}

}
55 changes: 55 additions & 0 deletions src/AppBundle/Event/ShiftAlertsEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace AppBundle\Event;

use Symfony\Component\EventDispatcher\Event;

class ShiftAlertsEvent extends Event
{
const NAME = 'shift.alerts';

private $alerts;
private $date;
private $template;
private $recipients;

public function __construct(array $alerts, \DateTime $date, $template = null, $recipients = null)
{
$this->alerts = $alerts;
$this->date = $date;
$this->template = $template;
$this->recipients = $recipients;
}

/**
* @return array
*/
public function getAlerts()
{
return $this->alerts;
}

/**
* @return \DateTime
*/
public function getDate()
{
return $this->date;
}

/**
* @return string|null
*/
public function getTemplate()
{
return $this->template;
}

/**
* @return array|null
*/
public function getRecipients()
{
return $this->recipients;
}
}
55 changes: 55 additions & 0 deletions src/AppBundle/Event/ShiftAlertsMattermostEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace AppBundle\Event;

use Symfony\Component\EventDispatcher\Event;

class ShiftAlertsMattermostEvent extends Event
{
const NAME = 'shift.alerts.mattermost';

private $alerts;
private $date;
private $template;
private $mattermost_hook_url;

public function __construct(array $alerts, \DateTime $date, $template = null, $mattermost_hook_url = null)
{
$this->alerts = $alerts;
$this->date = $date;
$this->template = $template;
$this->mattermost_hook_url = $mattermost_hook_url;
}

/**
* @return array
*/
public function getAlerts()
{
return $this->alerts;
}

/**
* @return \DateTime
*/
public function getDate()
{
return $this->date;
}

/**
* @return string|null
*/
public function getTemplate()
{
return $this->template;
}

/**
* @return string|null
*/
public function getMattermostHookUrl()
{
return $this->mattermost_hook_url;
}
}
40 changes: 40 additions & 0 deletions src/AppBundle/EventListener/EmailingEventListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use AppBundle\Event\MemberCycleEndEvent;
use AppBundle\Event\MemberCycleHalfEvent;
use AppBundle\Event\MemberCycleStartEvent;
use AppBundle\Event\ShiftAlertsEvent;
use AppBundle\Event\ShiftReservedEvent;
use AppBundle\Event\ShiftBookedEvent;
use AppBundle\Event\ShiftFreedEvent;
Expand Down Expand Up @@ -446,6 +447,45 @@ public function onShiftDeleted(ShiftDeletedEvent $event)
}
}

/**
* @param ShiftAlertsEvent $event
* @throws \Exception
*/
public function onShiftAlerts(ShiftAlertsEvent $event)
{
$this->logger->info("Emailing Listener: onShiftAlerts");

$alerts = $event->getAlerts();
$date = $event->getDate();
$recipients = $event->getRecipients();

if ($alerts && $recipients) {
$emailObject = '[ALERTE CRENEAUX] ' . strftime("%A %e %B", $date->getTimestamp());
$emailTo = $recipients;

$dynamicContent = $this->em->getRepository('AppBundle:DynamicContent')->findOneByCode($event->getTemplate());
$template = null;
if ($dynamicContent) {
$template = $this->container->get('twig')->createTemplate($dynamicContent->getContent());
} else {
$template = 'emails/shift_alerts_default.html.twig';
}

$email = (new \Swift_Message($emailObject))
->setFrom($this->shift_email['address'], $this->shift_email['from_name'])
->setTo($emailTo)
->setBody(
$this->container->get('twig')->render(
$template,
array('alerts' => $alerts, 'date' => $date)
),
'text/html'
);

$this->mailer->send($email);
}
}

/**
* @param MemberCycleStartEvent $event
* @throws \Exception
Expand Down
54 changes: 54 additions & 0 deletions src/AppBundle/EventListener/MattermostEventListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

namespace AppBundle\EventListener;

use AppBundle\Event\ShiftAlertsMattermostEvent;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Logger;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpClient\HttpClient;

class MattermostEventListener
{
protected $em;
protected $logger;
protected $container;

public function __construct(EntityManagerInterface $entityManager, Logger $logger, Container $container)
{
$this->em = $entityManager;
$this->logger = $logger;
$this->container = $container;
}

/**
* @param ShiftAlertsMattermostEvent $event
* @throws \Exception
*/
public function onShiftAlerts(ShiftAlertsMattermostEvent $event)
{
$this->logger->info("Mattermost Listener: onShiftAlerts");

$alerts = $event->getAlerts();
$date = $event->getDate();

if ($alerts && $event->getMattermostHookUrl()) {
$template = null;
$dynamicContent = $this->em->getRepository('AppBundle:DynamicContent')->findOneByCode($event->getTemplate());
if ($dynamicContent) {
$template = $this->container->get('twig')->createTemplate($dynamicContent->getContent());
} else {
$template = 'markdown/shift_alerts_default.md.twig';
}
$content = $this->container->get('twig')->render(
$template,
array('alerts' => $alerts, 'date' => $date)
);

$client = HttpClient::create();
$response = $client->request('POST', $event->getMattermostHookUrl(), [
'json' => ['text' => $content]
]);
}
}
}

0 comments on commit 92a36d8

Please sign in to comment.