feat: refactor to cards
This commit is contained in:
1 parent
ead2c092da
commit
49b7a3fe34
40 files changed
+2639
-3097
No files matched your search
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\XmlLoader\AgencyLoader;
|
||||
use App\Exception\BookingNotPossibleException;
|
||||
use App\Exception\HotelNotFoundException;
|
||||
use App\Exception\HotelNotInTravelException;
|
||||
use App\Exception\NoRoomsAvailableException;
|
||||
use App\Exception\TravelNotFoundException;
|
||||
use App\Service\BookingService;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Handles the initialization of new booking sessions.
|
||||
*
|
||||
* This controller provides a clean entry point for starting new booking flows
|
||||
* without requiring random UID parameters. It creates fresh booking sessions
|
||||
* and redirects to the first step of the booking process.
|
||||
*/
|
||||
class IndexController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly BookingService $bookingService,
|
||||
private readonly AgencyLoader $agencyLoader,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes a fresh booking session and redirects to step 1.
|
||||
*
|
||||
* This endpoint provides a clean way to start the booking flow with just
|
||||
* dateId and hotelId parameters. It clears any existing booking session
|
||||
* and creates a fresh BookingCreateDto before redirecting to step 1.
|
||||
*
|
||||
* Optionally accepts an agency code parameter. If provided and valid, the
|
||||
* corresponding agency ID is stored in the booking. If not provided or invalid,
|
||||
* defaults to agency code '0001'.
|
||||
*/
|
||||
#[Route(
|
||||
path: '/bookings/create/{dateId}/{hotelId}',
|
||||
name: 'app_booking_create_init',
|
||||
requirements: ['dateId' => '\d+', 'hotelId' => '\d+']
|
||||
)]
|
||||
public function init(Request $request, int $dateId, int $hotelId): Response
|
||||
{
|
||||
try {
|
||||
// Clear any existing booking session to ensure fresh start
|
||||
$this->bookingService->clearBookingSession($request);
|
||||
|
||||
// Determine agency ID from optional query parameter
|
||||
$agencyId = $this->resolveAgencyId($request->query->get('agency'));
|
||||
|
||||
// Create fresh booking session with the provided parameters
|
||||
$this->bookingService->startFreshBooking($request, $dateId, $hotelId, $agencyId);
|
||||
|
||||
// Redirect to step 1 of the booking flow
|
||||
return $this->redirectToRoute('app_booking_create_step_1');
|
||||
} catch (TravelNotFoundException $e) {
|
||||
throw $this->createNotFoundException(sprintf('Travel not found for date ID %d', $dateId));
|
||||
} catch (HotelNotFoundException $e) {
|
||||
throw $this->createNotFoundException(sprintf('Hotel not found for hotel ID %d', $hotelId));
|
||||
} catch (HotelNotInTravelException $e) {
|
||||
throw $this->createNotFoundException(sprintf('Hotel ID %d is not available for travel ID %d', $hotelId, $dateId));
|
||||
} catch (NoRoomsAvailableException $e) {
|
||||
throw $this->createNotFoundException('No rooms available for this travel.');
|
||||
} catch (BookingNotPossibleException $e) {
|
||||
throw $this->createNotFoundException('Booking is not possible for this travel (Buchungsstop).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the agency ID from the provided agency code.
|
||||
*
|
||||
* If the code is null or the agency is not found, returns the default agency ID.
|
||||
*
|
||||
* @param string|null $agencyCode The agency code from the request parameter
|
||||
*
|
||||
* @return int|null The agency ID, or null if default agency not found
|
||||
*/
|
||||
private function resolveAgencyId(?string $agencyCode): ?int
|
||||
{
|
||||
// Use default agency if no code provided
|
||||
if (null === $agencyCode || '' === trim($agencyCode)) {
|
||||
$defaultAgency = $this->agencyLoader->loadDefault();
|
||||
|
||||
return $defaultAgency?->id;
|
||||
}
|
||||
|
||||
// Try to find agency by provided code
|
||||
$agency = $this->agencyLoader->loadByCode($agencyCode);
|
||||
|
||||
// Fall back to default agency if code not found
|
||||
if (null === $agency) {
|
||||
$defaultAgency = $this->agencyLoader->loadDefault();
|
||||
|
||||
return $defaultAgency?->id;
|
||||
}
|
||||
|
||||
return $agency->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays user-friendly error messages for booking initialization failures.
|
||||
*
|
||||
* This endpoint provides a centralized location for displaying booking errors
|
||||
* with appropriate error messages and guidance for users.
|
||||
*/
|
||||
#[Route('/bookings/create/error', name: 'app_booking_create_error')]
|
||||
public function error(Request $request): Response
|
||||
{
|
||||
return $this->render('booking/create/error.html.twig');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\Controller\Booking\Traits\BookingCreateTrait;
|
||||
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
|
||||
use App\Form\BookingCreateStep1Type;
|
||||
use App\Htmx\HxTrait;
|
||||
use App\Service\BookingService;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Handles the first step of the booking creation process.
|
||||
*
|
||||
* This controller manages room selection functionality where users
|
||||
* choose the types and quantities of rooms for their booking.
|
||||
*/
|
||||
class Step1Controller extends AbstractController
|
||||
{
|
||||
use BookingCreateTrait;
|
||||
use BookingExceptionHandlerTrait;
|
||||
use HxTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly BookingService $bookingService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays and processes the room selection form.
|
||||
*/
|
||||
#[Route('/bookings/create', name: 'app_booking_create_step_1')]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
$bookingCreateDto = $result;
|
||||
|
||||
// Get or create baseline snapshot for change detection
|
||||
$oldRoomSelectionSnapshot = $this->bookingService->getOrCreateBaselineSnapshot($request, $bookingCreateDto);
|
||||
|
||||
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
|
||||
|
||||
// Validate step access - allow step 1 or redirect to current step
|
||||
if ($redirect = $this->validateStepAccess($bookingCreateDto, 1)) {
|
||||
return $redirect;
|
||||
}
|
||||
|
||||
$form = $this->createForm(BookingCreateStep1Type::class, $bookingCreateDto, [
|
||||
'attr' => [
|
||||
'hx-post' => $this->generateUrl('app_booking_create_step_1'),
|
||||
'hx-target' => '#form-wrapper',
|
||||
'hx-select' => '#form-wrapper',
|
||||
'hx-swap' => 'outerHTML',
|
||||
],
|
||||
'validation_groups' => ['booking_create_step_1'],
|
||||
]);
|
||||
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
if ($this->bookingService->hasRoomSelectionChanged($oldRoomSelectionSnapshot, $bookingCreateDto)) {
|
||||
$this->bookingService->resetParticipantAssignments($bookingCreateDto);
|
||||
}
|
||||
|
||||
$bookingCreateDto->currentStep = 2;
|
||||
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
|
||||
|
||||
// Clear baseline snapshot when moving to step 2
|
||||
$this->bookingService->clearBaselineSnapshot($request);
|
||||
|
||||
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_2'));
|
||||
}
|
||||
|
||||
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
|
||||
$groupedRooms = $this->bookingService->groupRoomsBySelectionType($availableRooms);
|
||||
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summary['selectedRooms'], $availableRooms);
|
||||
|
||||
return $this->render('booking/create/step_1.html.twig', [
|
||||
'bookingCreateDto' => $bookingCreateDto,
|
||||
'roomSummary' => $summary['selectedRooms'],
|
||||
'participantCount' => $summary['participantCount'],
|
||||
'pricingData' => $summary['pricing'],
|
||||
'form' => $form->createView(),
|
||||
'groupedRooms' => $groupedRooms,
|
||||
'groupedSelectedRooms' => $groupedSelectedRooms,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles HTMX requests for dynamic form updates when room selections change by submitting the form
|
||||
* without validation and returning freshly rendered blocks.
|
||||
*/
|
||||
#[Route('/bookings/create/refresh', name: 'app_booking_create_step_1_refresh', methods: ['POST'])]
|
||||
public function refreshRoomSelection(Request $request): Response
|
||||
{
|
||||
$result = $this->getOrCreateBookingCreateDtoForHtmx($this->bookingService, $request);
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
$bookingCreateDto = $result;
|
||||
|
||||
// Process form data without validation to capture current state
|
||||
$form = $this->createForm(BookingCreateStep1Type::class, $bookingCreateDto, [
|
||||
'validation_groups' => false,
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
|
||||
|
||||
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
|
||||
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
|
||||
$groupedRooms = $this->bookingService->groupRoomsBySelectionType($availableRooms);
|
||||
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summary['selectedRooms'], $availableRooms);
|
||||
|
||||
// The DTO is now updated with the latest selection.
|
||||
// We can now render the blocks with the fresh data.
|
||||
return $this->htmxOobResponse(
|
||||
'booking/create/step_1.html.twig',
|
||||
['room_selection_form', 'booking_summary'],
|
||||
[
|
||||
'form' => $form->createView(),
|
||||
'bookingCreateDto' => $bookingCreateDto,
|
||||
'participantCount' => $summary['participantCount'],
|
||||
'pricingData' => $summary['pricing'],
|
||||
'groupedRooms' => $groupedRooms,
|
||||
'groupedSelectedRooms' => $groupedSelectedRooms,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\Controller\Booking\Traits\BookingCreateTrait;
|
||||
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
|
||||
use App\Controller\Booking\Traits\ParticipantCardFlowTrait;
|
||||
use App\Controller\Booking\Traits\ParticipantValidationTrait;
|
||||
use App\Form\BookingCreateStep2Type;
|
||||
use App\Form\Model\BookingDto;
|
||||
use App\Form\Model\ParticipantDto;
|
||||
use App\Htmx\HxTrait;
|
||||
use App\Service\BookingPriceCalculatorService;
|
||||
use App\Service\BookingService;
|
||||
use App\Service\ParticipantCardDataService;
|
||||
use App\Service\RoomAssignmentService;
|
||||
use App\Service\TravelDataService;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Handles the second step of the booking creation process using card-based UI.
|
||||
*
|
||||
* This controller uses a card overview and lazy-loaded individual participant forms
|
||||
* for better performance and UX with large groups (50+ participants).
|
||||
*/
|
||||
class Step2Controller extends AbstractController
|
||||
{
|
||||
use BookingCreateTrait;
|
||||
use BookingExceptionHandlerTrait;
|
||||
use HxTrait;
|
||||
use ParticipantCardFlowTrait;
|
||||
use ParticipantValidationTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly BookingService $bookingService,
|
||||
private readonly BookingPriceCalculatorService $priceCalculator,
|
||||
private readonly TravelDataService $travelDataService,
|
||||
private readonly RoomAssignmentService $roomAssignmentService,
|
||||
private readonly ParticipantCardDataService $participantCardService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Display card grid for all participants.
|
||||
*/
|
||||
#[Route('/bookings/create/participants', name: 'app_booking_create_step_2')]
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
// Load or create booking DTO
|
||||
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
$bookingCreateDto = $result;
|
||||
|
||||
// Enrich with fresh availability data
|
||||
$this->enrichWithFreshAvailabilities($bookingCreateDto);
|
||||
|
||||
// Validate step access
|
||||
if ($redirect = $this->validateStepAccess($bookingCreateDto, 2)) {
|
||||
return $redirect;
|
||||
}
|
||||
|
||||
// Ensure correct number of participants
|
||||
$this->ensureCorrectNumberOfParticipants($bookingCreateDto);
|
||||
|
||||
// Auto-assign rooms if needed
|
||||
$this->autoAssignRoomsIfNeeded($bookingCreateDto);
|
||||
|
||||
// Preselect mandatory services
|
||||
$this->bookingService->preselectMandatoryServices($bookingCreateDto);
|
||||
|
||||
// Save BookingDto to session
|
||||
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
|
||||
|
||||
// Create validation form
|
||||
$form = $this->createForm(BookingCreateStep2Type::class, $bookingCreateDto, [
|
||||
'validation_groups' => ['booking_create_step_2'],
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
// Handle form submission (clicking "Weiter")
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
// All participants validated successfully, update current step
|
||||
$bookingCreateDto->currentStep = 3;
|
||||
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
|
||||
|
||||
// Proceed to Step 3
|
||||
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_3'));
|
||||
}
|
||||
|
||||
// Extract participant indices with validation errors
|
||||
$participantErrors = [];
|
||||
if ($form->isSubmitted() && false === $form->isValid()) {
|
||||
$participantErrors = $this->extractParticipantErrorIndices($form);
|
||||
}
|
||||
|
||||
// Generate cards data
|
||||
$cardsData = $this->generateAllCardsData($bookingCreateDto);
|
||||
|
||||
// Calculate summary data
|
||||
$summaryData = $this->calculateSummaryData($bookingCreateDto);
|
||||
|
||||
// Get detailed pricing data for summary sidebar
|
||||
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
|
||||
|
||||
$templateData = [
|
||||
'form' => $form->createView(),
|
||||
'bookingDto' => $bookingCreateDto,
|
||||
'cardsData' => $cardsData,
|
||||
'summaryData' => $summaryData,
|
||||
'pricingData' => $summary['pricing'],
|
||||
'participantErrors' => $participantErrors,
|
||||
];
|
||||
|
||||
// If HTMX request, render only blocks to avoid layout duplication
|
||||
if ($this->isHxRequest($request)) {
|
||||
return $this->htmxOobResponse(
|
||||
'booking/create/step_2.html.twig',
|
||||
['participant_cards', 'booking_summary'],
|
||||
$templateData
|
||||
);
|
||||
}
|
||||
|
||||
// Regular request: render full template
|
||||
return $this->render('booking/create/step_2.html.twig', $templateData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show or submit individual participant form.
|
||||
*/
|
||||
#[Route(
|
||||
path: '/bookings/create/participants/{index}',
|
||||
name: 'app_booking_create_step_2_participant',
|
||||
requirements: ['index' => '\d+']
|
||||
)]
|
||||
public function editParticipant(int $index, Request $request): Response
|
||||
{
|
||||
$bookingDto = $this->loadBookingDtoOrFail($request, BookingDto::MODE_CREATE);
|
||||
|
||||
// Validate participant index
|
||||
if (false === isset($bookingDto->participants[$index])) {
|
||||
throw $this->createNotFoundException(sprintf('Participant at index %d does not exist', $index));
|
||||
}
|
||||
|
||||
// Create form with booking_context option
|
||||
$form = $this->createParticipantForm($bookingDto, $index, [
|
||||
'validation_groups' => ['booking_create_step_2'],
|
||||
]);
|
||||
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
// Save BookingDto to session
|
||||
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_CREATE);
|
||||
|
||||
// HTMX redirect to cards view
|
||||
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_2'));
|
||||
}
|
||||
|
||||
// Calculate summary data for sidebar
|
||||
$summaryData = $this->calculateSummaryData($bookingDto);
|
||||
|
||||
// Get detailed pricing data for summary sidebar
|
||||
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingDto);
|
||||
|
||||
// Render form and sidebar with OOB swap using htmxOobResponse
|
||||
// This ensures both initial load and refresh use the same block-based rendering
|
||||
return $this->htmxOobResponse(
|
||||
'booking/_participant_form.html.twig',
|
||||
['participant_form', 'booking_summary'],
|
||||
[
|
||||
'form' => $form->createView(),
|
||||
'participantIndex' => $index,
|
||||
'bookingDto' => $bookingDto,
|
||||
'summaryData' => $summaryData,
|
||||
'pricingData' => $summary['pricing'],
|
||||
'refreshRouteName' => 'app_booking_create_step_2_participant_refresh',
|
||||
'submitRouteName' => 'app_booking_create_step_2_participant',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* HTMX refresh endpoint for individual participant form.
|
||||
*/
|
||||
#[Route(
|
||||
path: '/bookings/create/participants/{index}/refresh',
|
||||
name: 'app_booking_create_step_2_participant_refresh',
|
||||
requirements: ['index' => '\d+'],
|
||||
methods: ['POST']
|
||||
)]
|
||||
public function refreshParticipantForm(int $index, Request $request): Response
|
||||
{
|
||||
$bookingDto = $this->loadBookingDtoOrFail($request, BookingDto::MODE_CREATE);
|
||||
|
||||
// Enrich with fresh availability data
|
||||
$this->enrichWithFreshAvailabilities($bookingDto);
|
||||
|
||||
// Validate participant index
|
||||
if (false === isset($bookingDto->participants[$index])) {
|
||||
throw $this->createNotFoundException(sprintf('Participant at index %d does not exist', $index));
|
||||
}
|
||||
|
||||
// Use trait method for refresh handling
|
||||
return $this->handleParticipantRefresh(
|
||||
$request,
|
||||
$bookingDto,
|
||||
$index,
|
||||
'app_booking_create_step_2_participant_refresh',
|
||||
'app_booking_create_step_2_participant'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the booking DTO has the correct number of participant objects.
|
||||
*/
|
||||
private function ensureCorrectNumberOfParticipants(BookingDto $bookingCreateDto): void
|
||||
{
|
||||
$participantsCount = $this->getParticipantsCount($bookingCreateDto);
|
||||
|
||||
$participants = $bookingCreateDto->participants;
|
||||
$bookingCreateDto->participants = [];
|
||||
for ($i = 0; $i < $participantsCount; ++$i) {
|
||||
$participant = $participants[$i] ?? new ParticipantDto();
|
||||
$participant->index = $i;
|
||||
$bookingCreateDto->participants[$i] = $participant;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriches travel data with cached availability information from BusProNet API.
|
||||
*/
|
||||
private function enrichWithFreshAvailabilities(BookingDto $bookingCreateDto): void
|
||||
{
|
||||
$dateId = $bookingCreateDto->travel->id;
|
||||
|
||||
$availabilities = $this->travelDataService->getAvailabilityData($dateId, true);
|
||||
|
||||
if (null !== $availabilities) {
|
||||
$this->travelDataService->patchAvailabilities($bookingCreateDto->travel, $availabilities);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically assigns participants to rooms if they don't have room assignments yet.
|
||||
*/
|
||||
private function autoAssignRoomsIfNeeded(BookingDto $bookingCreateDto): void
|
||||
{
|
||||
// Check if any participants need room assignment
|
||||
$needsAssignment = false;
|
||||
foreach ($bookingCreateDto->participants as $participant) {
|
||||
if (null === $participant->assignedRoomId) {
|
||||
$needsAssignment = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($needsAssignment) {
|
||||
$this->roomAssignmentService->assignParticipantsToRooms($bookingCreateDto);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\Model\Notification;
|
||||
use App\Controller\Booking\Traits\BookingCreateTrait;
|
||||
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
|
||||
use App\Form\BookingCreateStep3Type;
|
||||
use App\Form\Model\BookingDto;
|
||||
use App\Htmx\HxTrait;
|
||||
use App\Service\BookingPriceCalculatorService;
|
||||
use App\Service\BookingService;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Handles the third step of the booking creation process (payment method selection).
|
||||
*/
|
||||
class Step3Controller extends AbstractController
|
||||
{
|
||||
use BookingCreateTrait;
|
||||
use BookingExceptionHandlerTrait;
|
||||
use HxTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly BookingService $bookingService,
|
||||
private readonly ApiClient $apiClient,
|
||||
private readonly BookingPriceCalculatorService $priceCalculator,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays and processes the payment method form.
|
||||
*/
|
||||
#[Route('/bookings/create/payment', name: 'app_booking_create_step_3')]
|
||||
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, 3)) {
|
||||
return $redirect;
|
||||
}
|
||||
|
||||
$form = $this->createForm(BookingCreateStep3Type::class, $bookingCreateDto, [
|
||||
'attr' => [
|
||||
'hx-post' => $this->generateUrl('app_booking_create_step_3'),
|
||||
'hx-target' => '#form-wrapper',
|
||||
'hx-select' => '#form-wrapper',
|
||||
'hx-swap' => 'outerHTML',
|
||||
],
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
try {
|
||||
// Validate booking data with API (inquiry)
|
||||
$inquiryResponse = $this->apiClient->createBookingInquiry($bookingCreateDto);
|
||||
|
||||
if ($inquiryResponse instanceof Notification) {
|
||||
return $this->handleInquiryError(
|
||||
'Booking inquiry failed',
|
||||
['message' => $inquiryResponse->message],
|
||||
'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
|
||||
if (false === $inquiryResponse->isInquiryValid()) {
|
||||
return $this->handleInquiryError(
|
||||
'Booking inquiry validation failed',
|
||||
['status' => $inquiryResponse->status],
|
||||
'Buchung konnte nicht validiert werden.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
|
||||
// Validate price match (exact comparison)
|
||||
$apiTotal = $inquiryResponse->totalPrice ?? 0.0;
|
||||
$calculatedTotal = $this->priceCalculator->calculateGrandTotal($bookingCreateDto);
|
||||
|
||||
if ($apiTotal !== $calculatedTotal) {
|
||||
return $this->handleInquiryError(
|
||||
'Price mismatch detected - payload incomplete',
|
||||
[
|
||||
'apiTotal' => $apiTotal,
|
||||
'calculatedTotal' => $calculatedTotal,
|
||||
'difference' => abs($apiTotal - $calculatedTotal),
|
||||
],
|
||||
'Ein technischer Fehler ist aufgetreten.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
|
||||
// Validation successful - proceed to confirmation step
|
||||
$bookingCreateDto->currentStep = 4;
|
||||
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
|
||||
|
||||
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_4'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->handleInquiryError(
|
||||
'Booking inquiry exception',
|
||||
[
|
||||
'exception' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
],
|
||||
'Ein technischer Fehler ist aufgetreten.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->renderStepForm($bookingCreateDto, $form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles HTMX refresh when payment method changes.
|
||||
*/
|
||||
#[Route('/bookings/create/payment/refresh', name: 'app_booking_create_step_3_refresh', methods: ['POST'])]
|
||||
public function refresh(Request $request): Response
|
||||
{
|
||||
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
$bookingCreateDto = $result;
|
||||
|
||||
$form = $this->createForm(BookingCreateStep3Type::class, $bookingCreateDto, [
|
||||
'validation_groups' => false,
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
|
||||
|
||||
return $this->renderStepForm($bookingCreateDto, $form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles inquiry errors by logging, adding flash message, and rendering the form.
|
||||
*/
|
||||
private function handleInquiryError(
|
||||
string $logMessage,
|
||||
array $context,
|
||||
string $flashMessage,
|
||||
BookingDto $bookingCreateDto,
|
||||
FormInterface $form,
|
||||
): Response {
|
||||
$this->logger->error($logMessage, $context);
|
||||
$this->addFlash('error', $flashMessage);
|
||||
|
||||
return $this->renderStepForm($bookingCreateDto, $form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the step 3 form with standard template variables.
|
||||
*/
|
||||
private function renderStepForm(BookingDto $bookingCreateDto, FormInterface $form): Response
|
||||
{
|
||||
return $this->render('booking/create/step_3.html.twig', [
|
||||
'bookingCreateDto' => $bookingCreateDto,
|
||||
'form' => $form->createView(),
|
||||
...$this->getSummaryVariables($bookingCreateDto),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use App\BusProNet\ApiClient;
|
||||
use App\BusProNet\Model\Notification;
|
||||
use App\Controller\Booking\Traits\BookingCreateTrait;
|
||||
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
|
||||
use App\Form\BookingCreateStep4Type;
|
||||
use App\Form\Model\BookingDto;
|
||||
use App\Htmx\HxTrait;
|
||||
use App\Service\BookingService;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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 ApiClient $apiClient,
|
||||
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;
|
||||
}
|
||||
|
||||
$form = $this->createForm(BookingCreateStep4Type::class, $bookingCreateDto, [
|
||||
'attr' => [
|
||||
'hx-post' => $this->generateUrl('app_booking_create_step_4'),
|
||||
'hx-target' => '#form-wrapper',
|
||||
'hx-select' => '#form-wrapper',
|
||||
'hx-swap' => 'outerHTML',
|
||||
],
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
try {
|
||||
// Submit final booking (already validated in Step 3)
|
||||
$bookingResponse = $this->apiClient->createBooking($bookingCreateDto);
|
||||
|
||||
if ($bookingResponse instanceof Notification) {
|
||||
return $this->handleBookingError(
|
||||
'Booking creation failed - API notification',
|
||||
['message' => $bookingResponse->message],
|
||||
$bookingResponse->message,
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
|
||||
if (false === $bookingResponse->isBookingSuccessful()) {
|
||||
return $this->handleBookingError(
|
||||
'Booking creation unsuccessful',
|
||||
['status' => $bookingResponse->status],
|
||||
'Buchung konnte nicht erstellt werden.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
|
||||
// Success: Store booking number in flash and clear session
|
||||
$this->addFlash('booking_number', $bookingResponse->transactionNumber);
|
||||
$this->bookingService->clearBookingCreateDto($request);
|
||||
|
||||
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_success'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->handleBookingError(
|
||||
'Booking creation exception',
|
||||
[
|
||||
'exception' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
],
|
||||
'Ein technischer Fehler ist aufgetreten.',
|
||||
$bookingCreateDto,
|
||||
$form
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->renderStepForm($bookingCreateDto, $form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles booking errors by logging, adding flash message, and rendering the form.
|
||||
*/
|
||||
private function handleBookingError(
|
||||
string $logMessage,
|
||||
array $context,
|
||||
string $flashMessage,
|
||||
BookingDto $bookingCreateDto,
|
||||
FormInterface $form,
|
||||
): Response {
|
||||
$this->logger->error($logMessage, $context);
|
||||
$this->addFlash('error', $flashMessage);
|
||||
|
||||
return $this->renderStepForm($bookingCreateDto, $form);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the step 4 form with standard template variables.
|
||||
*/
|
||||
private function renderStepForm(BookingDto $bookingCreateDto, FormInterface $form): Response
|
||||
{
|
||||
return $this->render('booking/create/step_4.html.twig', [
|
||||
'bookingCreateDto' => $bookingCreateDto,
|
||||
'form' => $form->createView(),
|
||||
...$this->getSummaryVariables($bookingCreateDto),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller\Booking\Create;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/**
|
||||
* Handles the success page after completing the booking creation flow.
|
||||
*/
|
||||
class SuccessController extends AbstractController
|
||||
{
|
||||
#[Route('/bookings/create/success', name: 'app_booking_create_success')]
|
||||
public function success(Request $request): Response
|
||||
{
|
||||
$bookingNumber = $request->getSession()->getFlashBag()->get('booking_number')[0] ?? null;
|
||||
|
||||
// Redirect to homepage if no booking number (direct access or refresh)
|
||||
if (null === $bookingNumber) {
|
||||
return $this->redirect('https://www.ep-reisen.de');
|
||||
}
|
||||
|
||||
return $this->render('booking/create/success.html.twig', [
|
||||
'bookingNumber' => $bookingNumber,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user