<?php
namespace App\EventSubscriber\MeterReading;
use App\Entity\IndexUpdate;
use App\Manager\ContractManager;
use App\Entity\User;
use App\Event\MeterReading\IndexUpdatedEvent;
use App\EventSubscriber\AbstractEmailSubscriber;
use App\Manager\Mailer;
use App\Manager\MailTypeInterface;
use App\Repository\Scp\ContactRepository;
use App\ScpExport\Strategy\IndexUpdateScpExportStrategy;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class MeterReadingSubscriber extends AbstractEmailSubscriber
{
private const ENABLE_CENTER_EMAIL = false;
protected $contactRepository;
protected $exportStrategy;
protected $contractManager;
public function __construct(
Mailer $mailer,
Environment $templating,
TranslatorInterface $translator,
ContactRepository $contactRepository,
IndexUpdateScpExportStrategy $exportStrategy,
ContractManager $contractManager
) {
parent::__construct($mailer, $templating, $translator);
$this->contactRepository = $contactRepository;
$this->exportStrategy = $exportStrategy;
$this->contractManager = $contractManager;
}
public static function getSubscribedEvents(): array
{
return [
IndexUpdatedEvent::class => 'onIndexUpdated',
];
}
public function onIndexUpdated(IndexUpdatedEvent $event): void
{
$index = $event->getIndex();
$user = $event->getUser();
$this->sendCustomerEmail($user, $index);
if (self::ENABLE_CENTER_EMAIL && null !== $index->getPicture()) {
$this->sendCenterEmail($user, $index);
}
}
protected function sendCenterEmail(User $user, IndexUpdate $index): void
{
$technicalContact = $this->contactRepository->findOneByDeliveryStationAndType($index->getStationId(), ContactRepository::TYPE_TECHNICAL, $index->getCustomerNumber());
if (null === $technicalContact) {
return;
}
$contract = $this->contractManager->getContractByPostNumber($index->getStationId(), $user);
$reperage = $contract['Reperage'];
$subject = $this->transEmail('meter_reading.index_updated_center.subject');
$message = $this->templating->render('email/meter_reading/index_updated_center.html.twig', [
'customer' => $user,
'index' => $index,
'reperage' => $reperage,
]);
$picturePath = $this->exportStrategy->getExportPath($index).DIRECTORY_SEPARATOR.$index->getPicture();
$this->mailer->sendMail(
[$technicalContact['Email']],
$subject,
$message,
MailTypeInterface::METER_READING_INDEX_UPDATED_SCP,
[\Swift_Attachment::fromPath($picturePath)]
);
}
protected function sendCustomerEmail(User $user, IndexUpdate $index): void
{
$subject = $this->transEmail('meter_reading.index_updated.subject');
$contract = $this->contractManager->getContractByPostNumber($index->getStationId(), $user);
$reperage = $contract['Reperage'];
$message = $this->templating->render('email/meter_reading/index_updated.html.twig', [
'customer' => $user,
'index' => $index,
'reperage' => $reperage,
]);
$this->mailer->sendMail([$user->getEmail()], $subject, $message, MailTypeInterface::METER_READING_INDEX_UPDATED_USER);
}
}