<?php
namespace App\Controller;
use App\Business\EventOffer;
use App\Business\Loader\EventStatusHelper;
use App\Form\EventOfferType;
use App\Services\DomainService;
use App\Services\EventOfferService;
use App\Services\EventService;
use App\Services\UserService;
use App\Services\S3Provider;
use App\Extern\XrmService;
use App\Utils\Helper;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use App\Business\ExcelImport\ExcelTransmissionsImporter;
use App\Business\Export\ExcelTransmissionsExporter;
use Throwable;
class EventOfferController extends AbstractController
{
/**
* @var EventOfferService $eventOfferService
*/
protected $eventOfferService;
/** @var DomainService $domainService */
protected $domainService;
/** @var ExcelTransmissionsImporter $excelImporter */
protected $excelImporter;
/** @var S3Provider $s3Provider */
protected $s3Provider;
/** @var EventService $eventService */
protected $eventService;
/** @var UserService $userService */
protected $userService;
/** @var XrmService $xrmService */
protected $xrmService;
/** @var ExcelTransmissionsExporter $excelExporter */
protected $excelExporter;
public function __construct(
EventOfferService $programmeOfferService,
DomainService $domainService,
ExcelTransmissionsImporter $excelImporter,
ExcelTransmissionsExporter $excelExporter,
S3Provider $s3Provider,
EventService $eventService,
UserService $userService,
XrmService $xrmService
)
{
$this->eventOfferService = $programmeOfferService;
$this->domainService = $domainService;
$this->excelImporter = $excelImporter;
$this->excelExporter = $excelExporter;
$this->s3Provider = $s3Provider;
$this->eventService = $eventService;
$this->userService = $userService;
$this->xrmService = $xrmService;
}
/**
* @Route("/events/my-offers", name="event_my_offers", options={"expose" = true }, methods={"GET", "POST"})
* @Security("is_granted('ROLE_USER')")
* @param Request|null $request
* @return Response
*/
public function myOffersAction(Request $request = null)
{
return $this->render('event_offer/event_offer_overview.html.twig');
}
/**
* @Route("/intern/events/my-event-offers", name="event_my_event_offers", options={"expose" = true }, methods={"GET", "POST"})
* @Security("is_granted('ROLE_USER')")
* @return Response
*/
public function displayMyOffersAction()
{
// Get events
$events = $this->eventOfferService->getEventOffersForCurrentUser();
return $this->render(
'event_offer/event_offer_list.html.twig',
['events' => $events]
);
}
/**
* @Route("/events/event-offer", name="event_event_offer", options={"expose" = true }, methods={"GET", "POST"})
* @Security("is_granted('ROLE_USER')")
* @param Request|null $request
* @return Response
*/
public function eventOfferAction(Request $request = null)
{
$codeOps = $this->userService->getCurrentUserCodeOps();
if (empty($codeOps)) {
$parts = explode('@', $this->getUser()->getEmail());
$domain = array_pop($parts);
$organization = $this->xrmService->getOrganizationsRelatedToSpecificEmailDomain($domain);
return $this->render('default/access_restriction_no_company.html.twig', ['username' => $this->getUser(), "organizationMappingPossible" => count($organization) > 0]);
} elseif (!$this->domainService->isCompanyActive($codeOps)) {
return $this->render('default/access_restriction_no_company.html.twig', ['username' => $this->getUser(), "organizationMappingPossible" => true]);
}
$eventNo = ($request->query->has('eventNo')) ? $request->query->get('eventNo') : null;
$action = ($request->query->has('action')) ? $request->query->get('action') : null;
$isDuplicate = 'duplicate' == $action;
if ($isDuplicate) {
$eventNo = ($request->query->has('fromEventNo')) ? $request->query->get('fromEventNo') : null;
}
$eventOffer = new EventOffer();
if ($eventNo != null) {
$eventOffer = $this->eventOfferService->prefillEventOffer($eventNo, $isDuplicate);
if (!EventStatusHelper::isEventOfferStatusEditable($eventOffer->status)) {
return $this->redirectToRoute('event_my_offers', ['eventNotEditable' => $eventNo]);
}
if (EventStatusHelper::isEventOfferStatusEditableWithRules($eventOffer->status)) {
if (!EventOffer::isEditable($eventOffer->startDate)) {
return $this->redirectToRoute('event_my_offers', ['eventEditableByMail' => $eventNo]);
}
}
if (empty($this->eventOfferService->getEventOffersForCurrentUser($eventNo))) {
return $this->redirectToRoute('event_my_offers', ['eventNotEditable' => $eventNo]);
}
}
$form = $this->createForm(EventOfferType::class, $eventOffer);
$form->handleRequest($request);
return $this->render(
'event_offer/event_offer_form.html.twig',
[
'form' => $form->createView(),
'isDuplicate' => $isDuplicate,
'event' => $eventOffer,
'videoData' => json_encode($this->domainService->getVideoDataForEventOffer())
]
);
}
/**
* @Security("is_granted('ROLE_USER')")
* @Route("/intern/events/event-offer/submit", name="event_offer_submit", options={"expose" = true})
* @param Request $request
* @param LoggerInterface $logger
* @return Response
*/
public function submitEventOfferAction(Request $request, LoggerInterface $logger)
{
try {
$eventOffer = new EventOffer();
$eventOfferForm = $this->createForm(EventOfferType::class, $eventOffer);
$eventOfferForm->handleRequest($request);
//not valid...
if (!$eventOfferForm->isValid()) {
$jsonResponse = $this->buildJsonResponseForOfferNotValid($eventOfferForm);
return $jsonResponse;
}
$eventToCompare = null;
if (!empty($eventOffer->eventNo)) {
$eventToCompare = $this->eventOfferService->prefillEventOffer($eventOffer->eventNo, false);
}
$ccForConfirmedOrPublished = $this->getParameter('booking_mail');
$result = $this->eventOfferService->createOrEditEventOffer($eventOffer, $eventToCompare, $ccForConfirmedOrPublished);
if ($result->isError()) {
$errorToDisplay = $this->render('event_offer/offer_error.html.twig', ["operationResult" => $result])->getContent();
return $this->json($errorToDisplay, JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
//we return the eventNo
return $this->json($result->getData()['eventNo']);
} catch (Throwable $ex) {
$logger->alert("error in submit booking" . $ex->getMessage(), ["exception" => $ex]);
return $this->json($ex->getMessage(), JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
}
/**
* @param $eventOfferForm
* @param array|null $otherData
* @return JsonResponse
*/
private function buildJsonResponseForOfferNotValid($eventOfferForm, array $otherData = null): JsonResponse
{
$data = [];
$errors = Helper::getErrorMessagesFlat($eventOfferForm, true);
$data['message'] = "Please, check errors in the offer";
$data['errors'] = $errors;
if ($otherData != null) {
$data = array_merge($data, $otherData);
}
//warn: the javascript is waiting for this response in case of unvalide data
//our javascript use the code to differentiate validation errors to internal errors.
$jsonResponse = $this->json($data, JsonResponse::HTTP_BAD_REQUEST);
return $jsonResponse;
}
/**
* @Route("/intern/test/excel/parsing", name="event_offer_import_transmission", options={"expose" = true})
*/
public function testExcelParsingJsonAction(Request $request = null)
{
if (empty($request->query->get('folder')) || empty($request->query->get('filename'))) {
return null;
}
$s3Url = $this->s3Provider->getS3Url($request->query->get('folder'), $request->query->get('filename'));
// $transmissions = $this->excelImporter->readExcelFile($s3Url);
// return JsonResponseHelper::buildSuccessJsonData($transmissions);
return null;
}
/**
* @Security("is_granted('ROLE_USER')")
* @Route("/intern/get/eventOffer/attachments/{eventNo}/{status}", name="get_event_offer_attachments", options={"expose" = true})
* @param string $eventNo
* @param string $status
* @return Response
*/
public function getEventOfferAttachmentsAction(string $eventNo, string $status)
{
$oldAttachments = $this->eventService->getEventAttachments($eventNo);
return $this->render(
'event_offer/event_offer_attachments.html.twig', [
'oldAttachments' => $oldAttachments,
'eventNo' => $eventNo,
'status' => $status
]
);
}
/**
* @Security("is_granted('ROLE_USER')")
* @Route("/intern/get/attachment/file/{eventNo}/{attachmentId}", name="getAttachmentFile", options={"expose" = true})
* @param string $eventNo
* @param string $attachmentId
* @return Response
*/
public function getAttachmentFileAction(string $eventNo, string $attachmentId)
{
$attachment = json_decode($this->eventService->getEventAttachmentContent($eventNo, $attachmentId));
$filename = $attachment->title;
$file = base64_decode($attachment->inputFile);
$f = finfo_open();
$mime_type = finfo_buffer($f, $file, FILEINFO_MIME_TYPE);
$response = new Response();
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', $mime_type);
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . "." . strtolower($attachment->fileFormat) . '";');
$response->setContent($file);
return $response;
}
/**
* @Security("is_granted('ROLE_USER')")
* @Route("/intern/delete/attachment/file/{eventNo}/{attachmentId}", name="deleteAttachmentFile", options={"expose" = true})
* @param string $eventNo
* @param string $attachmentId
* @return JsonResponse
*/
public function deleteAttachmentFile(string $eventNo, string $attachmentId)
{
$res = $this->eventService->deleteEventAttachment($eventNo, $attachmentId);
return new JsonResponse([
'message' => $res->getMessage(),
'status' => $res->getStatus(),
'data' => $res->getData(),
]);
}
/**
* @Security("is_granted('ROLE_USER')")
* @Route("/intern/events/event-offer/{eventNo}/report", name="event_offer_report", options={"expose" = true})
* @param string $eventNo
* @return Response
*/
public function eventOfferReportAction(string $eventNo)
{
$participations = $this->eventService->getEventParticipations($eventNo);
$event = $this->eventService->getEventByNo($eventNo);
$spreadsheet = $this->excelExporter->createExcelParticipationsObject($participations->getData(), $event, $this->getUser(), 10);
// create the writer
$writer = $this->excelExporter->createWriter($spreadsheet);
// create the response
$response = $this->excelExporter->createStreamedResponse($writer);
// adding headers
$filename = sprintf(
$eventNo . '-event-offer-participation-report-on-%s.xlsx',
date('Y-m-d')
);
$s3Path = 'media_public/event_offer/' . $filename;
$localPath = '/tmp/' . $filename;
// Save file in local
$writer->save($localPath);
$response = $this->s3Provider->setFile($s3Path, $localPath);
if (isset($response['status']) && $response['status'] != "success") {
return $this->json('Error during the generation of the report', JsonResponse::HTTP_BAD_REQUEST);
} else {
return $this->json($s3Path, JsonResponse::HTTP_OK);
}
}
}