feat: refactor to cards

This commit is contained in:
Björn Fromme
2025-10-15 18:31:10 +02:00
parent ead2c092da
commit 49b7a3fe34
40 changed files with 2639 additions and 3097 deletions
@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace App\Controller\Booking;
namespace App\Controller\Booking\Create;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Exception\BookingNotPossibleException;
@@ -23,7 +23,7 @@ use Symfony\Component\Routing\Attribute\Route;
* without requiring random UID parameters. It creates fresh booking sessions
* and redirects to the first step of the booking process.
*/
class CreateInitController extends AbstractController
class IndexController extends AbstractController
{
public function __construct(
private readonly BookingService $bookingService,
@@ -42,7 +42,11 @@ class CreateInitController extends AbstractController
* corresponding agency ID is stored in the booking. If not provided or invalid,
* defaults to agency code '0001'.
*/
#[Route('/bookings/create/{dateId}/{hotelId}', name: 'app_booking_create_init', requirements: ['dateId' => '\d+', 'hotelId' => '\d+'])]
#[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 {
@@ -110,6 +114,6 @@ class CreateInitController extends AbstractController
#[Route('/bookings/create/error', name: 'app_booking_create_error')]
public function error(Request $request): Response
{
return $this->render('booking/create_error.html.twig');
return $this->render('booking/create/error.html.twig');
}
}
@@ -2,8 +2,10 @@
declare(strict_types=1);
namespace App\Controller\Booking;
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;
@@ -18,7 +20,7 @@ use Symfony\Component\Routing\Attribute\Route;
* This controller manages room selection functionality where users
* choose the types and quantities of rooms for their booking.
*/
class CreateStep1Controller extends AbstractController
class Step1Controller extends AbstractController
{
use BookingCreateTrait;
use BookingExceptionHandlerTrait;
@@ -81,7 +83,7 @@ class CreateStep1Controller extends AbstractController
$groupedRooms = $this->bookingService->groupRoomsBySelectionType($availableRooms);
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summary['selectedRooms'], $availableRooms);
return $this->render('booking/create_step_1.html.twig', [
return $this->render('booking/create/step_1.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'roomSummary' => $summary['selectedRooms'],
'participantCount' => $summary['participantCount'],
@@ -121,7 +123,7 @@ class CreateStep1Controller extends AbstractController
// 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',
'booking/create/step_1.html.twig',
['room_selection_form', 'booking_summary'],
[
'form' => $form->createView(),
@@ -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);
}
}
}
@@ -2,16 +2,20 @@
declare(strict_types=1);
namespace App\Controller\Booking;
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;
@@ -19,7 +23,7 @@ use Symfony\Component\Routing\Attribute\Route;
/**
* Handles the third step of the booking creation process (payment method selection).
*/
class CreateStep3Controller extends AbstractController
class Step3Controller extends AbstractController
{
use BookingCreateTrait;
use BookingExceptionHandlerTrait;
@@ -37,7 +41,7 @@ class CreateStep3Controller extends AbstractController
* Displays and processes the payment method form.
*/
#[Route('/bookings/create/payment', name: 'app_booking_create_step_3')]
public function step3(Request $request): Response
public function index(Request $request): Response
{
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
if ($result instanceof Response) {
@@ -66,29 +70,23 @@ class CreateStep3Controller extends AbstractController
$inquiryResponse = $this->apiClient->createBookingInquiry($bookingCreateDto);
if ($inquiryResponse instanceof Notification) {
$this->logger->error('Booking inquiry failed', [
'message' => $inquiryResponse->message,
]);
$this->addFlash('error', 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
return $this->render('booking/create_step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->handleInquiryError(
'Booking inquiry failed',
['message' => $inquiryResponse->message],
'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.',
$bookingCreateDto,
$form
);
}
if (false === $inquiryResponse->isInquiryValid()) {
$this->logger->error('Booking inquiry validation failed', [
'status' => $inquiryResponse->status,
]);
$this->addFlash('error', 'Buchung konnte nicht validiert werden.');
return $this->render('booking/create_step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->handleInquiryError(
'Booking inquiry validation failed',
['status' => $inquiryResponse->status],
'Buchung konnte nicht validiert werden.',
$bookingCreateDto,
$form
);
}
// Validate price match (exact comparison)
@@ -96,18 +94,17 @@ class CreateStep3Controller extends AbstractController
$calculatedTotal = $this->priceCalculator->calculateGrandTotal($bookingCreateDto);
if ($apiTotal !== $calculatedTotal) {
$this->logger->error('Price mismatch detected - payload incomplete', [
'apiTotal' => $apiTotal,
'calculatedTotal' => $calculatedTotal,
'difference' => abs($apiTotal - $calculatedTotal),
]);
$this->addFlash('error', 'Ein technischer Fehler ist aufgetreten.');
return $this->render('booking/create_step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
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
@@ -116,32 +113,26 @@ class CreateStep3Controller extends AbstractController
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_4'));
} catch (\Exception $e) {
$this->logger->error('Booking inquiry exception', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->addFlash('error', 'Ein technischer Fehler ist aufgetreten.');
return $this->render('booking/create_step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->handleInquiryError(
'Booking inquiry exception',
[
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Ein technischer Fehler ist aufgetreten.',
$bookingCreateDto,
$form
);
}
}
return $this->render('booking/create_step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->renderStepForm($bookingCreateDto, $form);
}
/**
* Handles HTMX refresh when payment method changes.
*/
#[Route('/bookings/create/payment/refresh', name: 'app_booking_create_step_3_refresh')]
#[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);
@@ -157,7 +148,31 @@ class CreateStep3Controller extends AbstractController
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
return $this->render('booking/create_step_3.html.twig', [
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),
@@ -2,15 +2,19 @@
declare(strict_types=1);
namespace App\Controller\Booking;
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;
@@ -18,7 +22,7 @@ use Symfony\Component\Routing\Attribute\Route;
/**
* Handles the fourth step of the booking creation process (confirmation).
*/
class CreateStep4Controller extends AbstractController
class Step4Controller extends AbstractController
{
use BookingCreateTrait;
use BookingExceptionHandlerTrait;
@@ -35,7 +39,7 @@ class CreateStep4Controller extends AbstractController
* Displays booking summary and confirmation form.
*/
#[Route('/bookings/create/confirmation', name: 'app_booking_create_step_4')]
public function step4(Request $request): Response
public function index(Request $request): Response
{
$result = $this->getOrCreateBookingCreateDto($this->bookingService, $request);
if ($result instanceof Response) {
@@ -64,47 +68,69 @@ class CreateStep4Controller extends AbstractController
$bookingResponse = $this->apiClient->createBooking($bookingCreateDto);
if ($bookingResponse instanceof Notification) {
$this->addFlash('error', $bookingResponse->message);
return $this->render('booking/create_step_4.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->handleBookingError(
'Booking creation failed - API notification',
['message' => $bookingResponse->message],
$bookingResponse->message,
$bookingCreateDto,
$form
);
}
if (false === $bookingResponse->isBookingSuccessful()) {
$this->addFlash('error', 'Buchung konnte nicht erstellt werden.');
return $this->render('booking/create_step_4.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
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_success'));
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_success'));
} catch (\Exception $e) {
$this->logger->error('Booking creation failed', [
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->addFlash('error', 'Ein technischer Fehler ist aufgetreten.');
return $this->render('booking/create_step_4.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
...$this->getSummaryVariables($bookingCreateDto),
]);
return $this->handleBookingError(
'Booking creation exception',
[
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Ein technischer Fehler ist aufgetreten.',
$bookingCreateDto,
$form
);
}
}
return $this->render('booking/create_step_4.html.twig', [
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),
@@ -2,16 +2,19 @@
declare(strict_types=1);
namespace App\Controller\Booking;
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;
class BookingSuccessController extends AbstractController
/**
* Handles the success page after completing the booking creation flow.
*/
class SuccessController extends AbstractController
{
#[Route('/bookings/success', name: 'app_booking_success')]
#[Route('/bookings/create/success', name: 'app_booking_create_success')]
public function success(Request $request): Response
{
$bookingNumber = $request->getSession()->getFlashBag()->get('booking_number')[0] ?? null;
@@ -21,7 +24,7 @@ class BookingSuccessController extends AbstractController
return $this->redirect('https://www.ep-reisen.de');
}
return $this->render('booking/success.html.twig', [
return $this->render('booking/create/success.html.twig', [
'bookingNumber' => $bookingNumber,
]);
}
@@ -1,264 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controller\Booking;
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\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.
*
* This controller manages participant information collection including
* dynamic room assignment functionality with HTMX-based form updates.
*/
class CreateStep2Controller extends AbstractController
{
use BookingCreateTrait;
use BookingExceptionHandlerTrait;
use HxTrait;
public function __construct(
private readonly BookingService $bookingService,
private readonly BookingPriceCalculatorService $priceCalculator,
private readonly TravelDataService $travelDataService,
private readonly RoomAssignmentService $roomAssignmentService,
) {
}
/**
* Displays and processes the participant information form.
*/
#[Route('/bookings/create/participants', name: 'app_booking_create_step_2')]
public function participants(Request $request): Response
{
$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);
$participantsCount = $this->getParticipantsCount($bookingCreateDto);
// Auto-assign participants to rooms if not already assigned
$this->autoAssignRoomsIfNeeded($bookingCreateDto);
// Pre-select mandatory services for participants with birth dates
$this->bookingService->preselectMandatoryServices($bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
$form = $this->createForm(BookingCreateStep2Type::class, $bookingCreateDto, [
'attr' => [
'novalidate' => 'novalidate',
'hx-post' => $this->generateUrl('app_booking_create_step_2'),
'hx-target' => '#form-wrapper',
'hx-select' => '#form-wrapper',
'hx-swap' => 'outerHTML',
],
'validation_groups' => ['booking_create_step_2'],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$bookingCreateDto->currentStep = 3;
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_3'));
}
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($bookingCreateDto->getSelectedRooms(), $availableRooms);
$participantPrices = $this->priceCalculator->calculateAllParticipantIndividualPrices($bookingCreateDto);
return $this->render('booking/create_step_2.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'participantsCount' => $participantsCount,
'pricingData' => $summary['pricing'],
'assignmentCounts' => $roomAssignmentCounts,
'participantPrices' => $participantPrices,
'form' => $form->createView(),
'groupedSelectedRooms' => $groupedSelectedRooms,
]);
}
/**
* Handles HTMX requests for dynamic form updates when room selections change by submitting the form
* without validation and returning a freshly rendered instance.
*/
#[Route('/bookings/create/participants/refresh', name: 'app_booking_create_step_2_refresh', methods: ['POST'])]
public function refreshParticipantForm(Request $request): Response
{
$result = $this->getOrCreateBookingCreateDtoForHtmx($this->bookingService, $request);
if ($result instanceof Response) {
return $result;
}
$bookingCreateDto = $result;
// Enrich with fresh availability data
$this->enrichWithFreshAvailabilities($bookingCreateDto);
$participantsCount = $this->getParticipantsCount($bookingCreateDto);
// Process form data without validation to capture current state
$form = $this->createForm(BookingCreateStep2Type::class, $bookingCreateDto, [
'attr' => ['novalidate' => 'novalidate'],
'validation_groups' => false,
]);
$form->handleRequest($request);
// Pre-select mandatory services after form processing but before pricing calculation
$this->bookingService->preselectMandatoryServices($bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
// Collect notifications from all participants
$notifications = $this->collectParticipantNotifications($bookingCreateDto);
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($bookingCreateDto->getSelectedRooms(), $availableRooms);
$participantPrices = $this->priceCalculator->calculateAllParticipantIndividualPrices($bookingCreateDto);
// The DTO is now updated with the latest selection and submitted data has been cleaned.
// We can now render the blocks with the fresh data.
$response = $this->htmxOobResponse(
'booking/create_step_2.html.twig',
['participants_form', 'booking_summary'],
[
'form' => $form->createView(),
'bookingCreateDto' => $bookingCreateDto,
'participantsCount' => $participantsCount,
'pricingData' => $summary['pricing'],
'assignmentCounts' => $roomAssignmentCounts,
'participantPrices' => $participantPrices,
'groupedSelectedRooms' => $groupedSelectedRooms,
]
);
// Add notifications to HTMX trigger header if any exist
if ([] !== $notifications) {
$response->headers->set('HX-Trigger', json_encode([
'showNotifications' => ['notifications' => $notifications],
]));
}
return $response;
}
/**
* Ensures the booking DTO has the correct number of participant objects.
*
* Creates or reuses participant DTOs to match the required participant count
* based on room selections. Preserves existing participant data when possible
* and assigns proper index values.
*
* @param BookingDto $bookingCreateDto The booking DTO to update
*/
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.
*
* Fetches availability data with short-term caching and patches the travel object
* to ensure service availability is reasonably up-to-date while reducing API calls.
* This is essential for accurate pricing and service selection during the booking process.
*
* @param BookingDto $bookingCreateDto The booking DTO containing travel data to enrich
*/
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.
*
* This is called when entering Step 2 to ensure all participants have room assignments
* based on the selected rooms from Step 1. Only assigns if participants are unassigned.
*
* @param BookingDto $bookingCreateDto The booking DTO with participants and room selections
*/
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);
}
}
/**
* Collects all notifications from participants and clears them.
*
* @param BookingDto $bookingCreateDto The booking DTO containing participants
*
* @return array<array{type: string, message: string}> Array of notification messages
*/
private function collectParticipantNotifications(BookingDto $bookingCreateDto): array
{
$notifications = [];
foreach ($bookingCreateDto->participants as $participant) {
if ([] !== $participant->notifications) {
foreach ($participant->notifications as $notification) {
$notifications[] = $notification;
}
// Clear notifications after collection
$participant->notifications = [];
}
}
return $notifications;
}
}
@@ -5,7 +5,7 @@ namespace App\Controller\Booking;
use App\BusProNet\ApiClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\Controller\Traits\BookingDataTrait;
use App\Controller\Booking\Traits\BookingDataTrait;
use App\Entity\User;
use App\Security\Crypt;
use Psr\Log\LoggerInterface;
@@ -0,0 +1,523 @@
<?php
declare(strict_types=1);
namespace App\Controller\Booking\Edit;
use App\BusProNet\ApiClient;
use App\BusProNet\DataProcessor\BookingDataProcessor;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\Controller\Booking\Traits;
use App\Controller\Booking\Traits\BookingDataTrait;
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
use App\Controller\Booking\Traits\ParticipantValidationTrait;
use App\Entity\User;
use App\Form\BookingEditType;
use App\Form\BookingParticipantType;
use App\Form\Model\BookingDto;
use App\Form\Service\ParticipantFieldHandlerRegistry;
use App\Htmx\HxTrait;
use App\Security\Crypt;
use App\Service\BookingFingerprintService;
use App\Service\BookingPriceCalculatorService;
use App\Service\BookingService;
use App\Service\ParticipantCardDataService;
use App\Service\TravelDataService;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Cache\CacheInterface;
/**
* Edit controller using card-based participant interface.
*
* This controller implements the card-based UI for editing existing bookings:
* - Card overview with lazy-loaded individual participant forms
* - Handles canceled participants (status 'S')
* - Applies mutability constraints via EditFieldStateProvider
* - Final submission calls ApiClient::updateBooking()
*/
class IndexController extends AbstractController
{
use BookingDataTrait;
use BookingExceptionHandlerTrait;
use HxTrait;
use Traits\ParticipantCardFlowTrait;
use ParticipantValidationTrait;
public function __construct(
private readonly ApiClient $apiClient,
private readonly BookingDataProcessor $bookingDataProcessor,
private readonly TravelDataService $travelDataService,
private readonly BookingService $bookingService,
private readonly BookingFingerprintService $fingerprintService,
private readonly BookingPriceCalculatorService $priceCalculator,
private readonly ParticipantCardDataService $participantCardService,
private readonly ParticipantFieldHandlerRegistry $fieldHandlerRegistry,
private readonly CacheInterface $cache,
private readonly Security $security,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger,
) {
}
/**
* Display participant cards overview.
*/
#[Route('/bookings/{id}/edit', name: 'app_booking_edit', requirements: ['id' => '\d+'])]
#[IsGranted('ROLE_USER')]
public function index(int $id, Request $request): Response
{
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
// Load form data from session (or API on first load)
$bookingDto = $this->loadFormData($request, $id, $email, $password);
if (null === $bookingDto) {
return $this->redirectToRoute('app_bookings');
}
// Reset staleness timer when first loading the cards view (not HTMX requests)
// This prevents false staleness warnings from old edit sessions
if (false === $this->isHxRequest($request)) {
$bookingDto->lastSessionUpdate = new \DateTimeImmutable();
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_EDIT);
}
// Fetch booking data for display (surcharges, canceled status, etc.)
$bookingData = $this->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
// Fetch mutable data for form constraints
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
// Create validation form (same pattern as CreateStep2Controller)
$form = $this->createForm(BookingEditType::class, $bookingDto, [
'validation_groups' => ['booking_edit'],
]);
$form->handleRequest($request);
// Handle form submission (clicking "Buchung aktualisieren")
if ($form->isSubmitted() && $form->isValid()) {
// All participants validated successfully, submit to API
$this->logger->info('Initiated booking update', [
'email' => $email,
'booking_id' => $id,
]);
try {
$response = $this->apiClient->updateBooking($bookingDto, true);
if ($response instanceof Notification) {
if (true === $response->isError()) {
$this->addFlash('error', $response->message);
} else {
$this->addFlash('info', $response->message);
}
$this->logger->error('Booking update not successful', [
'email' => $email,
'booking_id' => $id,
'message' => $response->message,
]);
} else {
try {
$cacheKey = sprintf('bpn_booking_%d', $id);
$this->cache->delete($cacheKey);
} catch (InvalidArgumentException $e) {
}
// Clear session on successful save
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
$this->addFlash('success', 'Buchung erfolgreich aktualisiert');
$this->logger->info('Booking update successful', [
'email' => $email,
'booking_id' => $id,
]);
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
} catch (ApiClientException $e) {
$this->addFlash('error', 'Es ist ein Fehler in der Kommunikation mit dem Buchungssystem aufgetreten');
}
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
// Extract participant indices with validation errors
$participantErrors = [];
if ($form->isSubmitted() && false === $form->isValid()) {
$participantErrors = $this->extractParticipantErrorIndices($form);
}
// Generate card data for all participants
$cardsData = $this->participantCardService->getAllCardsData($bookingDto);
// Calculate summary data for sidebar
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingDto);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($bookingDto);
// Group selected rooms for summary display
$availableRooms = $bookingDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType(
$bookingDto->getSelectedRooms(),
$availableRooms
);
$templateData = [
'form' => $form->createView(),
'bookingDto' => $bookingDto,
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'cardsData' => $cardsData,
'participantsCount' => count($bookingDto->participants),
'pricingData' => $summary['pricing'],
'groupedSelectedRooms' => $groupedSelectedRooms,
'assignmentCounts' => $roomAssignmentCounts,
'isDirty' => $this->fingerprintService->isDirty($bookingDto),
'hasValidationErrors' => count($participantErrors) > 0,
'participantErrors' => $participantErrors,
];
// If HTMX request, render only blocks to avoid layout duplication
if ($this->isHxRequest($request)) {
return $this->htmxOobResponse(
'booking/edit/index.html.twig',
['participant_cards', 'booking_summary'],
$templateData
);
}
// Regular request: render full template
return $this->render('booking/edit/index.html.twig', $templateData);
}
/**
* Edit single participant form.
*/
#[Route(
path: '/bookings/{id}/edit/participants/{index}',
name: 'app_booking_edit_participant',
requirements: ['id' => '\d+', 'index' => '\d+']
)]
#[IsGranted('ROLE_USER')]
public function editParticipant(int $id, int $index, Request $request): Response
{
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
// Load form data from session
$bookingDto = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
if (null === $bookingDto) {
$this->addFlash('error', 'Sitzung abgelaufen. Bitte neu laden.');
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
$participant = $bookingDto->participants[$index] ?? null;
if (null === $participant) {
throw new \InvalidArgumentException('Invalid participant index');
}
// Fetch booking data to check for canceled status
$bookingData = $this->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
// Check if participant is canceled
$isCanceled = ($bookingData->participantsStatus[$index] ?? null) === 'S';
if ($isCanceled) {
// Redirect back to cards - canceled participants cannot be edited
$this->addFlash('warning', 'Stornierte Teilnehmer können nicht bearbeitet werden');
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
// Create form for participant with booking context
$form = $this->createForm(BookingParticipantType::class, $participant, [
'booking_context' => $bookingDto,
'edit_mode' => true,
'validation_groups' => ['booking_edit'],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Save updated booking data to session
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_EDIT);
// Redirect back to cards
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
// Calculate summary data using trait helper
$summaryData = $this->calculateSummaryData($bookingDto);
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingDto);
// Fetch mutable data for form constraints
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
// 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,
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'summaryData' => $summaryData,
'pricingData' => $summary['pricing'],
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'submitRouteName' => 'app_booking_edit_participant',
'submitRouteParams' => ['id' => $id, 'index' => $index],
'cancelRouteName' => 'app_booking_edit',
'cancelRouteParams' => ['id' => $id],
]
);
}
/**
* HTMX endpoint for refreshing participant form without validation.
*/
#[Route(
path: '/bookings/{id}/edit/participants/{index}/refresh',
name: 'app_booking_edit_participant_refresh',
requirements: ['id' => '\d+', 'index' => '\d+'],
methods: ['POST']
)]
#[IsGranted('ROLE_USER')]
public function refreshParticipantForm(int $id, int $index, Request $request): Response
{
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
// Load form data from session
$bookingDto = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
if (null === $bookingDto) {
return new Response('Session expired. Please reload page.', Response::HTTP_BAD_REQUEST);
}
// Refresh availability data
$availabilities = $this->travelDataService->getAvailabilityDataCached($bookingDto->travel->id);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($bookingDto->travel, $availabilities);
}
// Fetch booking data and mutable data
$bookingData = $this->fetchBookingData($email, $password, $id);
$mutableData = null !== $bookingData && !($bookingData instanceof Notification)
? $this->travelDataService->getMutabilityData($bookingData->dateId)
: null;
// Create form with validation disabled
$form = $this->createForm(BookingParticipantType::class, $bookingDto->participants[$index], [
'booking_context' => $bookingDto,
'edit_mode' => true,
'validation_groups' => false,
]);
$form->handleRequest($request);
// Save updated booking data to session
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_EDIT);
// Collect notifications from participant DTO
$participant = $bookingDto->participants[$index] ?? null;
$notifications = $participant?->notifications ?? [];
// Clear notifications after collecting
if (null !== $participant) {
$participant->notifications = [];
}
// Calculate summary data using trait helper
$summaryData = $this->calculateSummaryData($bookingDto);
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingDto);
// Render form + sidebar using htmxOobResponse
$response = $this->htmxOobResponse(
'booking/_participant_form.html.twig',
['participant_form', 'booking_summary'],
[
'form' => $form,
'participantIndex' => $index,
'bookingDto' => $bookingDto,
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'summaryData' => $summaryData,
'pricingData' => $summary['pricing'],
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'submitRouteName' => 'app_booking_edit_participant',
'submitRouteParams' => ['id' => $id, 'index' => $index],
'cancelRouteName' => 'app_booking_edit',
'cancelRouteParams' => ['id' => $id],
]
);
// Add notifications to HX-Trigger header if present
if ([] !== $notifications) {
$response->headers->set('HX-Trigger', json_encode([
'showNotifications' => ['notifications' => $notifications],
]));
}
return $response;
}
/**
* Reloads booking data from API, discarding all session changes.
*/
#[Route(
path: '/bookings/{id}/edit/reload',
name: 'app_booking_edit_reload',
requirements: ['id' => '\d+'],
methods: ['POST']
)]
#[IsGranted('ROLE_USER')]
public function reloadFromApi(int $id, Request $request): Response
{
// Clear session to discard all changes
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
$this->addFlash('success', 'Änderungen verworfen, Daten neu geladen');
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
/**
* Handles "Zurück" button - clears session and returns to bookings list.
*/
#[Route(
path: '/bookings/{id}/edit/cancel',
name: 'app_booking_edit_cancel',
requirements: ['id' => '\d+'],
methods: ['POST']
)]
#[IsGranted('ROLE_USER')]
public function cancelEdit(Request $request): Response
{
// Clear session to discard dirty state
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
return $this->hxRedirect($request, $this->generateUrl('app_bookings'));
}
/**
* Loads form data from session or initializes from API on first load.
*
* @return BookingDto|null The form data, or null on error
*/
private function loadFormData(Request $request, int $bookingId, string $email, string $password): ?BookingDto
{
// Try to load from session first
$formData = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
if (null === $formData) {
// First load: initialize from API
return $this->initializeFromApi($request, $bookingId, $email, $password);
}
// Subsequent load: refresh from session with staleness check
return $this->refreshFromSession($formData);
}
/**
* Initializes form data from API on first load and stores in session.
*
* @return BookingDto|null The form data, or null on error
*/
private function initializeFromApi(Request $request, int $bookingId, string $email, string $password): ?BookingDto
{
$bookingData = $this->fetchBookingData($email, $password, $bookingId);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return null;
}
$this->denyAccessUnlessGranted('EDIT', $bookingData);
$travelData = $this->travelDataService->getTravelData($bookingData->dateId);
if (null === $travelData) {
$this->addFlash('error', 'Reisedaten nicht (mehr) verfügbar');
return null;
}
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
$availabilities = $this->travelDataService->getAvailabilityData($bookingData->dateId);
if (null === $mutableData || null === $availabilities) {
$this->addFlash('error', 'Reisedaten nicht (mehr) verfügbar');
return null;
}
$this->travelDataService->patchAvailabilities($travelData, $availabilities);
$this->travelDataService->patchMutability($travelData, $mutableData);
$formData = $this->bookingDataProcessor->createBookingDtoFromBooking($bookingData, $travelData);
// Set original fingerprint for dirty state detection
error_log('[Fingerprint] === GENERATING ORIGINAL FINGERPRINT ===');
$formData->originalFingerprint = $this->fingerprintService->generateFingerprint($formData, true);
$this->bookingService->saveBookingDto($request, $formData, BookingDto::MODE_EDIT);
return $formData;
}
/**
* Refreshes form data loaded from session with latest availability.
*
* @return BookingDto The refreshed form data
*/
private function refreshFromSession(BookingDto $formData): BookingDto
{
// Refresh availability data
$availabilities = $this->travelDataService->getAvailabilityDataCached($formData->travel->id);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($formData->travel, $availabilities);
}
// Show staleness warning if session is older than 5 minutes
if (null !== $formData->lastSessionUpdate) {
$ageInSeconds = (new \DateTimeImmutable())->getTimestamp() - $formData->lastSessionUpdate->getTimestamp();
if ($ageInSeconds > 300) {
$minutes = (int) ceil($ageInSeconds / 60);
$this->addFlash('info', sprintf('Sie bearbeiten diese Buchung seit %d Minuten. Die Daten könnten veraltet sein.', $minutes));
}
}
return $formData;
}
}
-363
View File
@@ -1,363 +0,0 @@
<?php
namespace App\Controller\Booking;
use App\BusProNet\ApiClient;
use App\BusProNet\DataProcessor\BookingDataProcessor;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Model\Notification;
use App\BusProNet\XmlLoader\PickupLoader;
use App\Controller\Traits\BookingDataTrait;
use App\Entity\User;
use App\Form\BookingEditType;
use App\Form\Model\BookingDto;
use App\Htmx\HxTrait;
use App\Security\Crypt;
use App\Service\BookingPriceCalculatorService;
use App\Service\BookingService;
use App\Service\TravelDataService;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Contracts\Cache\CacheInterface;
class EditController extends AbstractController
{
use BookingDataTrait;
use HxTrait;
public function __construct(
private readonly ApiClient $apiClient,
private readonly BookingDataProcessor $bookingDataProcessor,
private readonly TravelDataService $travelDataService,
private readonly BookingService $bookingService,
private readonly BookingPriceCalculatorService $priceCalculator,
private readonly PickupLoader $pickupDataLoader,
private readonly CacheInterface $cache,
private readonly Security $security,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger,
) {
}
#[Route('/bookings/{id}/edit', name: 'app_booking_edit', requirements: ['id' => '\d+'])]
#[IsGranted('ROLE_USER')]
public function edit(int $id, Request $request): Response
{
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
// Load form data from session (or API on first load)
$formData = $this->loadFormData($request, $id, $email, $password);
if (null === $formData) {
return $this->redirectToRoute('app_bookings');
}
// Fetch booking data for display (surcharges, canceled status, etc.)
$bookingData = $this->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
// Fetch mutable data for form constraints
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
// Calculate pricing data for template
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($formData);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($formData);
$participantPrices = $this->priceCalculator->calculateAllParticipantIndividualPrices($formData);
// Group selected rooms for summary display
$availableRooms = $formData->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType(
$formData->getSelectedRooms(),
$availableRooms
);
$form = $this->createForm(BookingEditType::class, $formData, [
'attr' => [
'novalidate' => 'novalidate',
'hx-post' => $this->generateUrl('app_booking_edit', ['id' => $id]),
'hx-target' => '#form-wrapper',
'hx-select' => '#form-wrapper',
'hx-swap' => 'outerHTML',
],
'validation_groups' => ['booking_edit'],
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->logger->info('Initiated booking update', [
'email' => $email,
'booking_id' => $id,
]);
try {
$response = $this->apiClient->updateBooking($formData, true);
if ($response instanceof Notification) {
if (true === $response->isError()) {
$this->addFlash('error', $response->message);
} else {
$this->addFlash('info', $response->message);
}
$this->logger->error('Booking update not successful', [
'email' => $email,
'booking_id' => $id,
'message' => $response->message,
]);
} else {
try {
$cacheKey = sprintf('bpn_booking_%d', $id);
$this->cache->delete($cacheKey);
} catch (InvalidArgumentException $e) {
}
// Clear session on successful save
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
$this->addFlash('success', 'Buchung erfolgreich aktualisiert');
$this->logger->info('Booking update successful', [
'email' => $email,
'booking_id' => $id,
]);
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
} catch (ApiClientException $e) {
$this->addFlash('error', 'Es ist ein Fehler in der Kommunikation mit dem Buchungssystem aufgetreten');
}
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
return $this->render('booking/edit.html.twig', [
'bookingData' => $bookingData,
'bookingEditDto' => $formData,
'mutableData' => $mutableData,
'form' => $form->createView(),
'pricingData' => $summary['pricing'],
'participantCount' => $summary['participantCount'],
'assignmentCounts' => $roomAssignmentCounts,
'participantPrices' => $participantPrices,
'groupedSelectedRooms' => $groupedSelectedRooms,
]);
}
/**
* Reloads booking data from API, discarding all session changes.
*/
#[Route('/bookings/{id}/edit/reload', name: 'app_booking_edit_reload', requirements: ['id' => '\d+'], methods: ['POST'])]
#[IsGranted('ROLE_USER')]
public function reloadFromApi(int $id, Request $request): Response
{
// Clear session to discard all changes
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
$this->addFlash('success', 'Änderungen verworfen, Daten neu geladen');
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
/**
* HTMX endpoint for refreshing the participant form without validation.
*/
#[Route('/bookings/{id}/edit/refresh', name: 'app_booking_edit_refresh', requirements: ['id' => '\d+'], methods: ['POST'])]
#[IsGranted('ROLE_USER')]
public function refreshParticipantForm(int $id, Request $request): Response
{
// Load form data from session
$formData = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
if (null === $formData) {
return new Response('Session expired. Please reload page.', Response::HTTP_BAD_REQUEST);
}
// Refresh availability data
$availabilities = $this->travelDataService->getAvailabilityDataCached($formData->travel->id);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($formData->travel, $availabilities);
}
// Process form without validation to capture current state
$form = $this->createForm(BookingEditType::class, $formData, [
'attr' => ['novalidate' => 'novalidate'],
'validation_groups' => false,
]);
$form->handleRequest($request);
// Save updated DTO back to session
$this->bookingService->saveBookingDto($request, $formData, BookingDto::MODE_EDIT);
// Collect notifications from all participants
$notifications = $this->collectParticipantNotifications($formData);
// Fetch booking data and mutable data for display
/** @var User $user */
$user = $this->getUser();
$email = $user->getEmail();
$password = $this->crypt->decrypt($user->getPassword());
$bookingData = $this->fetchBookingData($email, $password, $id);
$mutableData = null !== $bookingData && !($bookingData instanceof Notification)
? $this->travelDataService->getMutabilityData($bookingData->dateId)
: null;
// Calculate pricing and summary data
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($formData);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($formData);
$participantPrices = $this->priceCalculator->calculateAllParticipantIndividualPrices($formData);
// Group selected rooms for summary display
$availableRooms = $formData->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType(
$formData->getSelectedRooms(),
$availableRooms
);
// Render updated blocks with fresh data
$response = $this->htmxOobResponse(
'booking/edit.html.twig',
['participants_form', 'booking_summary'],
[
'form' => $form->createView(),
'bookingEditDto' => $formData,
'bookingData' => $bookingData,
'pricingData' => $summary['pricing'],
'participantCount' => $summary['participantCount'],
'assignmentCounts' => $roomAssignmentCounts,
'participantPrices' => $participantPrices,
'groupedSelectedRooms' => $groupedSelectedRooms,
'mutableData' => $mutableData,
]
);
// Add notifications to HTMX trigger header if any exist
if ([] !== $notifications) {
$response->headers->set('HX-Trigger', json_encode([
'showNotifications' => ['notifications' => $notifications],
]));
}
return $response;
}
/**
* Collects all notifications from participants and clears them.
*
* @return array<array{type: string, message: string}> Array of notification messages
*/
private function collectParticipantNotifications(BookingDto $bookingDto): array
{
$notifications = [];
foreach ($bookingDto->participants as $participant) {
if ([] !== $participant->notifications) {
foreach ($participant->notifications as $notification) {
$notifications[] = $notification;
}
// Clear notifications after collecting
$participant->notifications = [];
}
}
return $notifications;
}
/**
* Loads form data from session or initializes from API on first load.
*
* @return BookingDto|null The form data, or null on error
*/
private function loadFormData(Request $request, int $bookingId, string $email, string $password): ?BookingDto
{
// Try to load from session first
$formData = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
if (null === $formData) {
// First load: initialize from API
return $this->initializeFromApi($request, $bookingId, $email, $password);
}
// Subsequent load: refresh from session with staleness check
return $this->refreshFromSession($formData);
}
/**
* Initializes form data from API on first load and stores in session.
*
* @return BookingDto|null The form data, or null on error
*/
private function initializeFromApi(Request $request, int $bookingId, string $email, string $password): ?BookingDto
{
$bookingData = $this->fetchBookingData($email, $password, $bookingId);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return null;
}
$this->denyAccessUnlessGranted('EDIT', $bookingData);
$travelData = $this->travelDataService->getTravelData($bookingData->dateId);
if (null === $travelData) {
$this->addFlash('error', 'Reisedaten nicht (mehr) verfügbar');
return null;
}
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
$availabilities = $this->travelDataService->getAvailabilityData($bookingData->dateId);
if (null === $mutableData || null === $availabilities) {
$this->addFlash('error', 'Reisedaten nicht (mehr) verfügbar');
return null;
}
$this->travelDataService->patchAvailabilities($travelData, $availabilities);
$this->travelDataService->patchMutability($travelData, $mutableData);
$formData = $this->bookingDataProcessor->createBookingDtoFromBooking($bookingData, $travelData);
$this->bookingService->saveBookingDto($request, $formData, BookingDto::MODE_EDIT);
return $formData;
}
/**
* Refreshes form data loaded from session with latest availability.
*
* @return BookingDto The refreshed form data
*/
private function refreshFromSession(BookingDto $formData): BookingDto
{
// Refresh availability data
$availabilities = $this->travelDataService->getAvailabilityDataCached($formData->travel->id);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($formData->travel, $availabilities);
}
// Show staleness warning if session is older than 5 minutes
if (null !== $formData->lastSessionUpdate) {
$ageInSeconds = (new \DateTimeImmutable())->getTimestamp() - $formData->lastSessionUpdate->getTimestamp();
if ($ageInSeconds > 300) {
$minutes = (int) ceil($ageInSeconds / 60);
$this->addFlash('info', sprintf('Sie bearbeiten diese Buchung seit %d Minuten. Die Daten könnten veraltet sein.', $minutes));
}
}
return $formData;
}
}
@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace App\Controller\Booking;
namespace App\Controller\Booking\Traits;
use App\Form\Model\BookingDto;
use Symfony\Component\HttpFoundation\RedirectResponse;
@@ -1,6 +1,6 @@
<?php
namespace App\Controller\Traits;
namespace App\Controller\Booking\Traits;
use App\BusProNet\Model\Booking;
use App\BusProNet\Model\Notification;
@@ -2,7 +2,7 @@
declare(strict_types=1);
namespace App\Controller\Booking;
namespace App\Controller\Booking\Traits;
use App\Exception\BookingSessionNotFoundException;
use App\Exception\HotelNotFoundException;
@@ -0,0 +1,196 @@
<?php
declare(strict_types=1);
namespace App\Controller\Booking\Traits;
use App\Form\BookingParticipantType;
use App\Form\Model\BookingDto;
use App\Service\BookingPriceCalculatorService;
use App\Service\BookingService;
use App\Service\ParticipantCardDataService;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Shared controller logic for participant card-based booking flows.
*
* This trait provides common functionality for both create and edit controllers
* that use the card-based UI pattern (card overview + lazy-loaded forms).
*/
trait ParticipantCardFlowTrait
{
/**
* Load BookingDto from session or throw exception.
*
* @throws \RuntimeException When booking data not found in session
*/
private function loadBookingDtoOrFail(Request $request, string $mode): BookingDto
{
$bookingDto = $this->bookingService->getBookingDto($request, $mode);
if (null === $bookingDto) {
throw new \RuntimeException(sprintf('Booking data not found in session for mode: %s', $mode));
}
return $bookingDto;
}
/**
* Generate card data for all participants.
*
* @return array<int, array{name: string, roomName: string, price: string}>
*/
private function generateAllCardsData(BookingDto $bookingDto): array
{
return $this->participantCardService->getAllCardsData($bookingDto);
}
/**
* Create form for single participant.
*
* This creates an autonomous participant form with booking_context option
* so it can process field handlers independently.
*/
private function createParticipantForm(
BookingDto $bookingDto,
int $index,
array $options = [],
): FormInterface {
$participant = $bookingDto->participants[$index] ?? null;
if (null === $participant) {
throw new \InvalidArgumentException(sprintf('Participant at index %d does not exist', $index));
}
// Merge default options with provided options
$formOptions = array_merge([
'booking_context' => $bookingDto,
'edit_mode' => BookingDto::MODE_EDIT === $bookingDto->getMode(),
], $options);
return $this->createForm(BookingParticipantType::class, $participant, $formOptions);
}
/**
* Calculate summary data (pricing, room counts, etc.).
*
* @return array{
* participantsCount: int,
* totalPrice: string,
* groupedSelectedRooms: array,
* assignmentCounts: array
* }
*/
private function calculateSummaryData(BookingDto $bookingDto): array
{
// Calculate individual prices for all participants
$participantPrices = $this->priceCalculator->calculateAllParticipantIndividualPrices($bookingDto);
// Calculate total price
$totalPrice = array_sum($participantPrices);
// Get room assignment counts
$roomCounts = [];
foreach ($bookingDto->participants as $participant) {
if (null !== $participant->assignedRoomId) {
$roomCounts[$participant->assignedRoomId] = ($roomCounts[$participant->assignedRoomId] ?? 0) + 1;
}
}
// Group selected rooms with counts
$groupedSelectedRooms = [];
foreach ($roomCounts as $roomId => $count) {
$room = $bookingDto->travel->getRoomById($roomId);
if (null !== $room) {
$groupedSelectedRooms[] = [
'room' => $room,
'count' => $count,
];
}
}
return [
'participantsCount' => count($bookingDto->participants),
'totalPrice' => number_format($totalPrice, 2, ',', '.').' €',
'groupedSelectedRooms' => $groupedSelectedRooms,
'assignmentCounts' => $roomCounts,
];
}
/**
* Process single participant form refresh.
*
* Handles HTMX form refresh without validation, updates sidebar via OOB swap.
*/
private function handleParticipantRefresh(
Request $request,
BookingDto $bookingDto,
int $index,
string $refreshRouteName,
string $submitRouteName,
): Response {
// Create form with validation disabled
$form = $this->createParticipantForm($bookingDto, $index, [
'validation_groups' => false,
]);
$form->handleRequest($request);
// Save updated booking data to session
$this->bookingService->saveBookingDto($request, $bookingDto, $bookingDto->getMode());
// Collect notifications from participant DTO
$participant = $bookingDto->participants[$index] ?? null;
$notifications = $participant?->notifications ?? [];
// Clear notifications after collecting
if (null !== $participant) {
$participant->notifications = [];
}
// 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 renders ONLY the specific blocks, not the entire template
$response = $this->htmxOobResponse(
'booking/_participant_form_standalone.html.twig',
['participant_form', 'booking_summary'],
[
'form' => $form->createView(),
'participantIndex' => $index,
'bookingDto' => $bookingDto,
'summaryData' => $summaryData,
'pricingData' => $summary['pricing'],
'refreshRouteName' => $refreshRouteName,
'submitRouteName' => $submitRouteName,
]
);
// Add notifications to HX-Trigger header if present
if (false === empty($notifications)) {
$response->headers->set('HX-Trigger', json_encode([
'showNotifications' => $notifications,
]));
}
return $response;
}
/**
* Required services - implementing controllers must inject these.
*
* Controllers using this trait must have the following properties:
* - BookingService $bookingService
* - ParticipantCardDataService $participantCardService
* - BookingPriceCalculatorService $priceCalculator
*/
abstract private function createForm(string $type, $data = null, array $options = []): FormInterface;
abstract private function render(string $view, array $parameters = [], ?Response $response = null): Response;
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Controller\Booking\Traits;
/**
* Provides participant validation error extraction for card-based booking flows.
*
* Shared between CreateStep2Controller and EditController to identify which
* participants have validation errors that should be displayed on their cards.
*/
trait ParticipantValidationTrait
{
/**
* Extracts participant indices that have validation errors.
*
* Parses form errors to identify which participants have validation issues.
* Returns an array of participant indices (e.g., [0, 2, 5]).
*
* @return array<int> Array of participant indices with errors
*/
private function extractParticipantErrorIndices($form): array
{
$errorIndices = [];
$errors = $form->getErrors(true); // Get all errors recursively
foreach ($errors as $error) {
$propertyPath = $error->getCause()?->getPropertyPath();
if (null === $propertyPath) {
continue;
}
// Property paths look like "participants[0].firstName" or "participants[1].email"
if (preg_match('/participants\[(\d+)]/', $propertyPath, $matches)) {
$index = (int) $matches[1];
$errorIndices[$index] = true; // Use array key to avoid duplicates
}
}
return array_keys($errorIndices);
}
}