Files
myep/src/Controller/Booking/Create/Step4Controller.php
T
2026-03-19 16:15:07 +01:00

238 lines
9.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controller\Booking\Create;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\TimeoutException;
use App\BusProNet\Model\Notification;
use App\Controller\Booking\Traits\BookingCreateTrait;
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
use App\Exception\NewsletterProviderException;
use App\Form\BookingCreateStep4Type;
use App\Form\Model\BookingDto;
use App\Htmx\HxTrait;
use App\Entity\User;
use App\Service\BookingPriceCalculatorService;
use App\Service\BookingService;
use App\Service\BookingSummaryDataService;
use App\Service\Newsletter\MailjetNewsletterService;
use App\Service\Newsletter\NewsletterDoubleOptInService;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
/**
* Handles the fourth step of the booking creation process (confirmation).
*/
class Step4Controller extends AbstractController
{
use BookingCreateTrait;
use BookingExceptionHandlerTrait;
use HxTrait;
public function __construct(
private readonly BookingService $bookingService,
private readonly BookingSummaryDataService $summaryDataService,
private readonly BookingPriceCalculatorService $priceCalculator,
private readonly ApiClient $apiClient,
private readonly CacheInterface $cache,
private readonly MailjetNewsletterService $newsletterService,
private readonly NewsletterDoubleOptInService $doubleOptInService,
private readonly LoggerInterface $logger,
) {
}
/**
* Displays booking summary and confirmation form.
*/
#[Route('/bookings/create/confirmation', name: 'app_booking_create_step_4')]
public function index(Request $request): Response
{
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
if ($result instanceof Response) {
return $result;
}
$bookingCreateDto = $result;
// Validate step access
if ($redirect = $this->validateStepAccess($bookingCreateDto, 4)) {
return $redirect;
}
$newsletterTargetEmail = $this->resolveNewsletterTargetEmail($bookingCreateDto);
$newsletterOptInVisible = false;
if (null !== $newsletterTargetEmail) {
try {
$newsletterOptInVisible = false === $this->newsletterService->isSubscribed($newsletterTargetEmail);
} catch (NewsletterProviderException $e) {
$this->logger->warning('Could not resolve newsletter subscription state in booking step 4', [
'email' => $newsletterTargetEmail,
'error' => $e->getMessage(),
]);
}
}
$form = $this->createForm(BookingCreateStep4Type::class, $bookingCreateDto, [
'show_newsletter_opt_in' => $newsletterOptInVisible,
'newsletter_target_email' => $newsletterTargetEmail,
]);
$form->handleRequest($request);
if (true === $form->isSubmitted() && true === $form->isValid()) {
try {
$this->bookingService->applyCreateBookingStatusRules($bookingCreateDto);
// Submit final booking (already validated in Step 3)
$bookingResponse = $this->apiClient->createBooking($bookingCreateDto);
if ($bookingResponse instanceof Notification) {
return $this->handleApiError(
'Booking creation failed - API notification',
['message' => $bookingResponse->message],
$bookingResponse->message ?? 'Ein Fehler ist aufgetreten. Bitte versuchen es erneut.',
$bookingCreateDto,
$form
);
}
if (false === $bookingResponse->isBookingSuccessful()) {
$errorMessage = 'Buchung konnte nicht erstellt werden.';
if (null !== $bookingResponse->message && '' !== trim($bookingResponse->message)) {
$errorMessage .= ' '.$bookingResponse->message;
}
return $this->handleApiError(
'Booking creation unsuccessful',
['status' => $bookingResponse->status, 'message' => $bookingResponse->message],
$errorMessage,
$bookingCreateDto,
$form
);
}
$newsletterOptInSelected = $newsletterOptInVisible
&& $form->has('newsletterOptIn')
&& true === $form->get('newsletterOptIn')->getData();
if (true === $newsletterOptInSelected && null !== $newsletterTargetEmail) {
try {
$this->doubleOptInService->requestConfirmation($newsletterTargetEmail);
} catch (NewsletterProviderException|\InvalidArgumentException $e) {
$this->logger->warning('Newsletter confirmation request failed after booking', [
'email' => $newsletterTargetEmail,
'error' => $e->getMessage(),
]);
}
}
// Success: Store booking data in flash for conversion tracking
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
$this->addFlash('booking_number', $bookingResponse->bookingNumber);
$this->addFlash('booking_total', $summaryData->payableAmount);
$this->addFlash('booking_travel_name', $bookingCreateDto->travel->label);
$this->clearTravelDataCache($bookingCreateDto);
$this->bookingService->clearBookingDto($request, BookingDto::MODE_CREATE);
$this->logger->info('Booking successfully created.', [
'date_id' => $bookingCreateDto->travel->id,
'hotel_id' => $bookingCreateDto->hotelId,
'booking_number' => $bookingResponse->bookingNumber,
]);
return $this->redirectToRoute('app_booking_create_success');
} catch (TimeoutException $e) {
return $this->handleApiError(
'Booking creation timeout',
[
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Die Anfrage hat zu lange gedauert. Bitte versuche es erneut.',
$bookingCreateDto,
$form
);
} catch (\Exception $e) {
return $this->handleApiError(
'Booking creation exception',
[
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Ein technischer Fehler ist aufgetreten.',
$bookingCreateDto,
$form
);
}
}
return $this->renderStepForm($bookingCreateDto, $form, $newsletterOptInVisible, $newsletterTargetEmail);
}
/**
* Renders the step 4 form with standard template variables.
*/
private function renderStepForm(
BookingDto $bookingCreateDto,
FormInterface $form,
bool $newsletterOptInVisible,
?string $newsletterTargetEmail,
): Response
{
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
return $this->render('booking/create/step_4.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
'summaryData' => $summaryData,
'participantPrices' => $this->priceCalculator->calculateAllParticipantIndividualPrices($bookingCreateDto),
'newsletterOptInVisible' => $newsletterOptInVisible,
'newsletterTargetEmail' => $newsletterTargetEmail,
]);
}
private function resolveNewsletterTargetEmail(BookingDto $bookingDto): ?string
{
$currentUser = $this->getUser();
$email = null;
if ($currentUser instanceof User) {
$email = $currentUser->getEmail();
}
if ((null === $email || '' === trim((string) $email)) && isset($bookingDto->participants[0])) {
$email = $bookingDto->participants[0]->email;
}
if (null === $email) {
return null;
}
$normalizedEmail = mb_strtolower(trim($email));
return false !== filter_var($normalizedEmail, FILTER_VALIDATE_EMAIL) ? $normalizedEmail : null;
}
/**
* Clears travel data and availability cache after successful booking.
*/
private function clearTravelDataCache(BookingDto $bookingDto): void
{
$dateId = $bookingDto->travel->id;
$hotelId = $bookingDto->hotelId;
// Clear availability cache
$this->cache->delete(sprintf('availability_%d', $dateId));
// Clear travel data cache (both local and remote variants)
$this->cache->delete(sprintf('travel_unified_%d_%d_local', $dateId, $hotelId));
$this->cache->delete(sprintf('travel_unified_%d_%d_remote', $dateId, $hotelId));
}
}