<?php
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Job;
use App\Entity\Schedule;
use App\Entity\User;
use App\Service\Message;
use Doctrine\Persistence\ManagerRegistry;
use JetBrains\PhpStorm\ArrayShape;
use Monolog\DateTimeImmutable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use function in_array;
final class ScheduleCompleteSubscriber implements EventSubscriberInterface
{
/** @var string The relative path inside templates/messages without any extensions */
private const TEMPLATE = 'schedule/complete';
/** @var int The user ID of the admin user to notify */
private const ADMIN_TO_NOTIFY = 1;
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly ManagerRegistry $managerRegistry,
private readonly Message $messageService,
)
{
}
#[ArrayShape([KernelEvents::VIEW => "array"])]
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['sendMessage', EventPriorities::POST_WRITE],
];
}
public function sendMessage(ViewEvent $event): void
{
$job = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
# PUT and PATCH methods are used to update instances, and we are only interested in updated jobs
if (!$job instanceof Job || !in_array($method, [Request::METHOD_PUT, Request::METHOD_PATCH])) {
return;
}
$previousData = $event->getRequest()->get('previous_data');
# If the status hasn't changed, we're not interested
if ($previousData->getStatus() === $job->getStatus()) {
return;
}
# If the status hasn't changed to "complete", we're not interested
if ($job->getStatus() !== Job::JOB_STATUS_COMPLETE) {
return;
}
/** @var User $currentUser */
$currentUser = $this->tokenStorage->getToken()->getUser();
/** @var iterable<Schedule> $schedules */
$schedules = $this->managerRegistry->getRepository(Schedule::class)
->findBy([
'employee' => $currentUser->getEmployee(),
'date' => new DateTimeImmutable('today'),
]);
$completed = 0;
$total = 0;
foreach ($schedules as $schedule) {
$total++;
if ($schedule->getJob()->getStatus() === Job::JOB_STATUS_COMPLETE) {
$completed++;
}
}
# If the employee has not completed all of the jobs today, we're not interested
if ($completed !== $total) {
return;
}
// @todo find a better way of choosing which admin(s) to notify
$admin = $this->managerRegistry->getRepository(User::class)
->find(self::ADMIN_TO_NOTIFY);
$message = $this->messageService
->withRecipient($admin)
->withSubject(sprintf('%s has completed today\'s jobs.', $currentUser->getFirstName()))
->withTemplate(self::TEMPLATE)
->withTemplateData([
'employeeName' => $currentUser->getFirstName(),
]);
if ($currentUser instanceof User) {
$message = $message->withCurrentUser($currentUser);
}
$message->send();
}
}