<?php
namespace App\EventListener;
use App\Entity\AbstractOperation;
use App\Entity\CoopOperation;
use App\Entity\LocalOperation;
use App\Entity\Operation;
use App\Entity\OperationDate;
use App\Manager\CustomerManager;
use App\Manager\OperationDateManager;
use App\Service\ConvertXlsToArray;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Container\ContainerInterface;
use Sogec\BOBundle\Event\CRUDEvents;
use Sogec\BOBundle\Event\GetCRUDPersistResponseEvent;
use Sogec\BOBundle\Event\GetCRUDSubmittedFormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Class LocalOperationSubscriber.
*/
final class LocalOperationSubscriber implements EventSubscriberInterface
{
/**
* @var CustomerManager
*/
protected $manager;
/**
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* @var ConvertXlsToArray
*/
private $convertXlsToArray;
/**
* @var ContainerInterface
*/
private $container;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var OperationDateManager
*/
private $operationDateManager;
/**
* LocalOperationSubscriber constructor.
*
* @param CustomerManager $manager
* @param UrlGeneratorInterface $urlGenerator
* @param ConvertXlsToArray $convertXlsToArray
* @param ContainerInterface $container
* @param EntityManagerInterface $entityManager
* @param OperationDateManager $operationDateManager
*/
public function __construct(CustomerManager $manager, UrlGeneratorInterface $urlGenerator, ConvertXlsToArray $convertXlsToArray, ContainerInterface $container, EntityManagerInterface $entityManager, OperationDateManager $operationDateManager)
{
$this->manager = $manager;
$this->urlGenerator = $urlGenerator;
$this->convertXlsToArray = $convertXlsToArray;
$this->container = $container;
$this->entityManager = $entityManager;
$this->operationDateManager = $operationDateManager;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
CRUDEvents::NEW_COMPLETED => ['subscribeOperation', 10],
CRUDEvents::NEW_SUBMITTED => ['checkCab', 'changeOperationDate'],
CRUDEvents::EDIT_SUBMITTED => ['checkCab', 'changeOperationDate'],
];
}
/**
* @param GetResponseForControllerResultEvent $event
*/
public function subscribeOperation(GetCRUDPersistResponseEvent $event)
{
$entity = $event->getEntity();
if (!$entity instanceof LocalOperation) {
return;
}
$campaign = $entity->getCampaign();
$entity->setImage($campaign->getImage());
$this->manager->flush();
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_local_operation_partners_edit', [
'operation_id' => $entity->getId(),
])));
}
/**
* @param GetCRUDSubmittedFormEvent $event
*
* @return void
*/
public function checkCab(GetCRUDSubmittedFormEvent $event)
{
if (!$event->getEntity() instanceof LocalOperation) {
return;
}
$request = $event->getRequest();
/** @var UploadedFile $file */
$file = $request->files->get('local_operation')['cab']['file'];
if (null === $file) {
return;
}
$filePath = $file->getPathname();
$datas = $this->convertXlsToArray->transformAndCheckFileToData($filePath, 18);
$wrongStart = $datas['wrong_start'];
$errorMsg = sprintf('<p>Une erreur est survenue lors de la création de votre opération :</p></p><p>Information incorrecte dans le fichier de Simulateur promo (CAB) <strong>"%s"</strong></p>', $file->getClientOriginalName());
if (!$datas['valid']) {
$errorMsg .= '<ul>';
foreach ($datas['errors'] as $errorKey => $error) {
if (!$wrongStart) {
$errorMsg .= sprintf('<li>Colonne <strong>%s</strong><ul>', strtoupper($errorKey));
}
foreach ($error as $value) {
$errorMsg .= sprintf('<li>%s</li>', $value);
}
$errorMsg .= '</ul>';
}
$errorMsg .= '</li></ul>';
$this->container->get('session')->getFlashBag()->add('warning', $errorMsg);
if ($event->getEntity()->getId() !== null) {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_local_operations_edit', ['id' => $event->getEntity()->getId()])));
} else {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_local_operations_new')));
}
}
if (!$wrongStart) {
foreach ($datas['participations'] as $participation) {
$remise = isset($participation[LocalOperation::COL_PERCENT_DISCOUNT]) ?: $participation[strtoupper(LocalOperation::COL_PERCENT_DISCOUNT)];
if ($remise < 0 || $remise > 1) {
$this->container->get('session')->getFlashBag()->add('warning', sprintf('Information incorrecte dans le fichier de Simulateur promo (CAB) "%s"', $file->getClientOriginalName()));
if ($event->getEntity()->getId() !== null) {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_local_operations_edit', ['id' => $event->getEntity()->getId()])));
} else {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate('admin_local_operations_new')));
}
}
}
}
}
public function changeOperationDate(GetCRUDSubmittedFormEvent $event)
{
$entity = $event->getEntity();
if (!$entity instanceof LocalOperation) {
return;
}
$request = $event->getRequest();
$attribute = 'operation';
if ($entity instanceof CoopOperation) {
$attribute = 'coop_operation';
}
if ($entity instanceof LocalOperation) {
$attribute = 'local_operation';
}
if ($operationDate = $this->entityManager->getRepository(OperationDate::class)->findOneBy([], ['id' => 'DESC'])) {
try {
$date = DateTime::createFromFormat(AbstractOperation::DATE_FORMAT, $request->request->get($attribute)['endDate']);
} catch (\Exception $e) {
return;
}
$newDate = new DateTime(date(AbstractOperation::DATETIME_FORMAT, strtotime($this->operationDateManager->settingFormattedDate($operationDate), strtotime($date->format(AbstractOperation::DATETIME_FORMAT)))));
$entity->setEventClosingDate(date_time_set($newDate, 23, 59, 59));
}
}
}