feat: refactor to cards

This commit is contained in:
Björn Fromme
2026-03-16 11:59:10 +01:00
parent 32a9fac9ed
commit e51c4843c5
40 changed files with 2639 additions and 3097 deletions
@@ -110,12 +110,85 @@ class BookingDataProcessor
$room = $booking->getRoomForParticipant($index);
$participantData->assignedRoomId = $room?->id;
// Enrich services with data from travel (especially prices)
$this->enrichParticipantServicesFromTravel($participantData, $travel);
$dto->participants[$index] = $participantData;
}
return $dto;
}
/**
* Enriches participant service selections with data from travel model.
*
* Services extracted from booking API responses might not include all necessary data
* (especially prices). This method looks up each service in the travel data and copies
* over missing properties to ensure proper pricing calculations.
*
* @param ParticipantDto $participant The participant with service selections
* @param Travel $travel The travel data containing full service information
*/
private function enrichParticipantServicesFromTravel(ParticipantDto $participant, Travel $travel): void
{
// Enrich courses
foreach ($participant->courses as $key => $course) {
if (isset($travel->additionalServices[$course->id])) {
$participant->courses[$key] = $travel->additionalServices[$course->id];
}
}
// Enrich ski pass
if (null !== $participant->skiPass && isset($travel->additionalServices[$participant->skiPass->id])) {
$participant->skiPass = $travel->additionalServices[$participant->skiPass->id];
}
// Enrich additional services
foreach ($participant->additionalServices as $key => $service) {
if (isset($travel->additionalServices[$service->id])) {
$participant->additionalServices[$key] = $travel->additionalServices[$service->id];
}
}
// Enrich board
foreach ($participant->board as $key => $board) {
if (isset($travel->additionalServices[$board->id])) {
$participant->board[$key] = $travel->additionalServices[$board->id];
}
}
// Enrich rentals
foreach ($participant->rentals as $key => $rental) {
if (isset($travel->additionalServices[$rental->id])) {
$participant->rentals[$key] = $travel->additionalServices[$rental->id];
}
}
// Enrich rental insurance
if (null !== $participant->rentalInsurance && isset($travel->additionalServices[$participant->rentalInsurance->id])) {
$participant->rentalInsurance = $travel->additionalServices[$participant->rentalInsurance->id];
}
// Enrich transportation services
if (null !== $participant->transportationOutbound && isset($travel->transportationServices[$participant->transportationOutbound->id])) {
$participant->transportationOutbound = $travel->transportationServices[$participant->transportationOutbound->id];
}
if (null !== $participant->transportationInbound && isset($travel->transportationServices[$participant->transportationInbound->id])) {
$participant->transportationInbound = $travel->transportationServices[$participant->transportationInbound->id];
}
// Enrich pickup
if (null !== $participant->pickup && isset($travel->pickupsOutbound[$participant->pickup->id])) {
$participant->pickup = $travel->pickupsOutbound[$participant->pickup->id];
}
// Enrich insurance
if (null !== $participant->insurance && isset($travel->insurances[$participant->insurance->id])) {
$participant->insurance = $travel->insurances[$participant->insurance->id];
}
}
/**
* Creates an update request payload for the BusProNet API from booking form data.
*
@@ -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);
}
}
+11 -65
View File
@@ -1,81 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Form;
use App\Form\Model\BookingDto;
use App\Form\Service\ParticipantFieldHandlerRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Form type for Step 2 of the booking process (participant data validation).
*
* This form is used in the card-based UI where participants are edited individually
* in separate forms. This form validates the complete BookingDto before proceeding
* to Step 3, ensuring all participants have valid and complete data.
*/
class BookingCreateStep2Type extends AbstractType
{
public function __construct(
private readonly ParticipantFieldHandlerRegistry $participantFieldHandlerRegistry,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData'])
->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit']);
}
/**
* Handles the initial form creation.
*/
public function onPreSetData(FormEvent $event): void
{
/** @var BookingDto|null $data */
$data = $event->getData();
if (null === $data) {
return;
}
$this->addParticipantsField($event->getForm());
}
/**
* Handles dynamic participant form field updates on POST requests (e.g., from HTMX).
*
* This listener synchronizes the BookingDto with the submitted participant data *before*
* the form's children are processed. It then rebuilds the participants
* field to ensure choice loaders are created with the fresh state.
*/
public function onPreSubmit(FormEvent $event): void
{
$form = $event->getForm();
$submittedData = $event->getData();
/** @var BookingDto $bookingDto */
$bookingDto = $form->getData();
// Process field handlers and synchronize submitted data with cleaned DTO state
$cleanedSubmittedData = $this->participantFieldHandlerRegistry->processFieldsAndSync($submittedData, $bookingDto);
$event->setData($cleanedSubmittedData);
// Rebuild the 'participants' field with the updated DTO.
$this->addParticipantsField($form);
}
/**
* Adds or replaces the 'participants' collection field on the form.
*/
private function addParticipantsField(FormInterface $form): void
{
$form->add('participants', CollectionType::class, [
'entry_type' => BookingParticipantType::class,
'entry_options' => [
'edit_mode' => false,
],
'allow_add' => false,
'allow_delete' => false,
]);
// No fields needed - participants are edited individually in their own forms
// This form exists purely for validation and CSRF protection
}
public function configureOptions(OptionsResolver $resolver): void
+11 -55
View File
@@ -1,71 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Form;
use App\Form\Model\BookingDto;
use App\Form\Service\ParticipantFieldHandlerRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Form type for edit booking validation.
*
* This form is used in the card-based UI where participants are edited individually.
* This form validates the complete BookingDto before allowing updates,
* ensuring all participants have valid and complete data.
*/
class BookingEditType extends AbstractType
{
public function __construct(
private readonly ParticipantFieldHandlerRegistry $participantFieldHandlerRegistry,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onPreSetData'])
->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit']);
}
public function onPreSetData(FormEvent $event): void
{
/** @var BookingDto $data */
$data = $event->getData();
$form = $event->getForm();
$form->add('participants', CollectionType::class, [
'entry_type' => BookingParticipantType::class,
'entry_options' => [
'edit_mode' => true,
],
'allow_add' => false,
'allow_delete' => false,
]);
}
public function onPreSubmit(FormEvent $event): void
{
$form = $event->getForm();
$submittedData = $event->getData();
/** @var BookingDto $bookingDto */
$bookingDto = $form->getData();
// Process field handlers and synchronize submitted data with cleaned DTO state
$cleanedSubmittedData = $this->participantFieldHandlerRegistry->processFieldsAndSync($submittedData, $bookingDto);
$event->setData($cleanedSubmittedData);
// Rebuild the 'participants' field with the updated DTO
if ($form->has('participants')) {
$form->remove('participants');
}
$form->add('participants', CollectionType::class, [
'entry_type' => BookingParticipantType::class,
'entry_options' => [
'edit_mode' => true,
],
'allow_add' => false,
'allow_delete' => false,
]);
// No fields needed - participants are edited individually in their own forms
// This form exists purely for validation
}
public function configureOptions(OptionsResolver $resolver): void
+58 -12
View File
@@ -9,12 +9,12 @@ use App\Form\Service\Contract\FieldOptionsProviderInterface;
use App\Form\Service\Contract\FieldStateProviderInterface;
use App\Form\Service\CreateFieldStateProvider;
use App\Form\Service\EditFieldStateProvider;
use App\Form\Service\ParticipantFieldHandlerRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
@@ -31,6 +31,7 @@ class BookingParticipantType extends AbstractType
private readonly FieldOptionsProviderInterface $fieldOptionsProvider,
private readonly CreateFieldStateProvider $createFieldStateProvider,
private readonly EditFieldStateProvider $editFieldStateProvider,
private readonly ParticipantFieldHandlerRegistry $fieldHandlerRegistry,
) {
}
@@ -41,19 +42,60 @@ class BookingParticipantType extends AbstractType
? $this->editFieldStateProvider
: $this->createFieldStateProvider;
// Capture booking context for use in event listeners
$bookingContext = $options['booking_context'];
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$this->onPreSetData($event);
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($bookingContext) {
$this->onPreSetData($event, $bookingContext);
})
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$this->onPreSubmit($event);
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($bookingContext) {
// Process field handlers FIRST (before form binding and validation)
// This ensures data is cleaned before Symfony processes it
if (null !== $bookingContext) {
$this->processFieldHandlers($event, $bookingContext);
}
// Then rebuild fields with updated states
$this->onPreSubmit($event, $bookingContext);
});
}
/**
* Processes field handlers for this participant.
*
* Field handlers are executed in PRE_SUBMIT to clean and transform data
* before Symfony binds it to the form. This matches the pattern used in
* the old BookingCreateStep2Type parent form.
*/
private function processFieldHandlers(FormEvent $event, BookingDto $bookingContext): void
{
$form = $event->getForm();
$submittedData = $event->getData();
if (false === is_array($submittedData)) {
return;
}
/** @var ParticipantDto $participant */
$participant = $form->getData();
if (null === $participant || false === property_exists($participant, 'index')) {
return;
}
// Process all field handlers for this participant in dependency order
$this->fieldHandlerRegistry->processFieldsForParticipant(
$submittedData,
$bookingContext,
$participant->index
);
}
/**
* Adds dynamic fields to the form based on participant data.
*/
private function onPreSetData(FormEvent $event): void
private function onPreSetData(FormEvent $event, ?BookingDto $bookingContext): void
{
/** @var ParticipantDto|null $participantData */
$participantData = $event->getData();
@@ -63,8 +105,9 @@ class BookingParticipantType extends AbstractType
return;
}
// Get the booking DTO from the root form
$bookingDto = $this->fieldStateProvider->getBookingDtoFromForm($form);
// Card flow: BookingDto passed via options
// Accordion flow (if we had one): traverse form tree
$bookingDto = $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
if (null === $bookingDto) {
return;
@@ -80,7 +123,7 @@ class BookingParticipantType extends AbstractType
/**
* Handles form pre-submit events to update field states based on submitted data.
*/
private function onPreSubmit(FormEvent $event): void
private function onPreSubmit(FormEvent $event, ?BookingDto $bookingContext): void
{
$submittedData = $event->getData();
$form = $event->getForm();
@@ -89,8 +132,9 @@ class BookingParticipantType extends AbstractType
return;
}
// Get the booking DTO from the root form
$bookingDto = $this->fieldStateProvider->getBookingDtoFromForm($form);
// Card flow: BookingDto passed via options
// Accordion flow (if we had one): traverse form tree
$bookingDto = $bookingContext ?? $this->fieldStateProvider->getBookingDtoFromForm($form);
if (null === $bookingDto) {
return;
@@ -173,7 +217,7 @@ class BookingParticipantType extends AbstractType
* field states change based on submitted data.
*
* @param FormInterface $form The form to modify
* @param BookingDto $bookingDto The booking data for context
* @param BookingDto $bookingDto The booking data for context
* @param int $participantIndex The participant index
* @param array<string, mixed> $formData Submitted form data for state calculation
*/
@@ -334,9 +378,11 @@ class BookingParticipantType extends AbstractType
'data_class' => ParticipantDto::class,
'selected_rooms' => [],
'edit_mode' => false,
'booking_context' => null,
]);
$resolver->setAllowedTypes('selected_rooms', 'array');
$resolver->setAllowedTypes('edit_mode', 'bool');
$resolver->setAllowedTypes('booking_context', ['null', BookingDto::class]);
}
}
+8 -1
View File
@@ -49,7 +49,7 @@ class BookingDto
/**
* Booking status code for API submission.
* Values: 'F' (Final/Frei), 'A' (Anfrage/Inquiry)
* Values: 'F' (Final/Frei), 'A' (Anfrage/Inquiry).
*/
public string $bookingStatus = 'F';
@@ -64,6 +64,13 @@ class BookingDto
*/
public ?\DateTimeImmutable $lastSessionUpdate = null;
/**
* Fingerprint of the booking state when loaded from API (edit mode only).
* This property stores the original state and is never updated after initial load.
* Used to detect unsaved changes in edit mode by comparing with current state.
*/
public ?string $originalFingerprint = null;
public function __construct(public Travel $travel, public int $hotelId)
{
}
@@ -100,6 +100,10 @@ class ParticipantAdditionalServicesFieldHandler extends AbstractParticipantField
// Extract current service selections from submitted data
$selectedServices = $this->getFieldValue($submittedData, $this->getFieldName()) ?? [];
// Debug: Log what was submitted
$submittedIds = array_map(fn($s) => is_object($s) ? $s->id : $s, $selectedServices);
error_log(sprintf('[AdditionalServices] Participant %d: Submitted service IDs: [%s]', $participantIndex, implode(', ', $submittedIds)));
// Get available additional services from travel data
$availableServices = $bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_ADDITIONAL);
@@ -111,6 +115,10 @@ class ParticipantAdditionalServicesFieldHandler extends AbstractParticipantField
$participantIndex
);
// Debug: Log what passed validation
$validIds = array_map(fn($s) => $s->id, $validSelections);
error_log(sprintf('[AdditionalServices] Participant %d: Valid service IDs after filtering: [%s]', $participantIndex, implode(', ', $validIds)));
// Update participant with validated selections
$participant->additionalServices = $validSelections;
}
@@ -173,17 +181,33 @@ class ParticipantAdditionalServicesFieldHandler extends AbstractParticipantField
$service = $this->findServiceInAvailableServices($selectedService, $availableServices);
if (null === $service) {
error_log(sprintf('[AdditionalServices] Participant %d: Service %s NOT FOUND in available services', $participantIndex, is_object($selectedService) ? $selectedService->id : $selectedService));
return false; // Service not found in available services
}
// Check if service has age constraints
$ageEvaluator = new ServiceAgeEvaluator();
if (false === $ageEvaluator->canEvaluate($service)) {
error_log(sprintf('[AdditionalServices] Participant %d: Service %d (%s) has NO age constraints - VALID', $participantIndex, $service->id, $service->label));
return true; // No age restrictions, service is valid
}
// Validate service against participant's age
return $ageEvaluator->isServiceAvailableForParticipant($service, $bookingDto, $participantIndex);
$isValid = $ageEvaluator->isServiceAvailableForParticipant($service, $bookingDto, $participantIndex);
$participant = $bookingDto->getParticipant($participantIndex);
$age = $participant?->getAge($bookingDto->travel->dateFrom);
error_log(sprintf(
'[AdditionalServices] Participant %d (age %s): Service %d (%s) age validation = %s. Constraints: %s',
$participantIndex,
$age ?? 'unknown',
$service->id,
$service->label,
$isValid ? 'VALID' : 'INVALID',
$ageEvaluator->getConstraintDescription($service)
));
return $isValid;
}
/**
@@ -76,7 +76,7 @@ class ParticipantFieldHandlerRegistry
* automatically cleared.
*
* @param array<string, mixed> $submittedData The submitted form data containing participants array
* @param BookingDto $bookingDto The booking DTO to update with processed field values
* @param BookingDto $bookingDto The booking DTO to update with processed field values
*
* @return array<string, mixed> The synchronized submitted data reflecting DTO changes
*/
@@ -108,7 +108,7 @@ class ParticipantFieldHandlerRegistry
* family detection which needs all participants' ages to be processed first).
*
* @param array<string, mixed> $submittedData The submitted form data containing participants array
* @param BookingDto $bookingDto The booking DTO to update with processed field values (create or edit)
* @param BookingDto $bookingDto The booking DTO to update with processed field values (create or edit)
*/
public function processFields(array $submittedData, BookingDto $bookingDto): void
{
@@ -133,7 +133,7 @@ class ParticipantFieldHandlerRegistry
}
// Let each handler decide if it should process this participant's data
if ($handler->shouldProcess($participantData, $bookingDto->mode, (int) $participantIndex)) {
if ($handler->shouldProcess($participantData, $bookingDto->getMode(), (int) $participantIndex)) {
$handler->processField($participantData, $bookingDto, (int) $participantIndex);
}
}
@@ -149,9 +149,9 @@ class ParticipantFieldHandlerRegistry
*
* Handlers are executed in dependency order to ensure proper data consistency.
*
* @param array<string, mixed> $participantData Submitted data for one participant
* @param BookingDto $bookingDto The booking DTO to update
* @param int $participantIndex Index of participant to process
* @param array<string, mixed> $participantData Submitted data for one participant
* @param BookingDto $bookingDto The booking DTO to update
* @param int $participantIndex Index of participant to process
*/
public function processFieldsForParticipant(array $participantData, BookingDto $bookingDto, int $participantIndex): void
{
@@ -163,7 +163,7 @@ class ParticipantFieldHandlerRegistry
$handler = $this->handlers[$handlerName];
// Let each handler decide if it should process this participant's data
if ($handler->shouldProcess($participantData, $bookingDto->mode, $participantIndex)) {
if ($handler->shouldProcess($participantData, $bookingDto->getMode(), $participantIndex)) {
$handler->processField($participantData, $bookingDto, $participantIndex);
}
}
@@ -284,7 +284,7 @@ class ParticipantFieldHandlerRegistry
* the current DTO state and updating the corresponding submitted data fields.
*
* @param array<string, mixed> $submittedData The original submitted form data
* @param BookingDto $bookingDto The DTO with cleaned data from field handlers
* @param BookingDto $bookingDto The DTO with cleaned data from field handlers
*
* @return array<string, mixed> Updated submitted data reflecting DTO state
*/
@@ -326,7 +326,7 @@ class ParticipantFieldHandlerRegistry
* @param array<string, mixed> $participantData The submitted participant data
* @param ParticipantDto $participant The cleaned participant DTO
* @param int $index The participant index
* @param BookingDto $bookingDto The booking DTO for mode detection
* @param BookingDto $bookingDto The booking DTO for mode detection
*
* @return array<string, mixed> Updated participant data with synchronized field values
*/
@@ -125,7 +125,10 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'expanded' => true,
'required' => false,
'choices' => $this->filterServicesByAgeConstraints(
$bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_COURSES),
$bookingDto->travel->getAdditionalServicesBySubTypes(
Constants::TOKEN_COURSES,
BookingDto::MODE_CREATE === $bookingDto->getMode() // Only filter by availability in create mode
),
$bookingDto,
$participantIndex
),
@@ -143,8 +146,8 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes['data-description'] = $service->description;
}
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'courses')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
@@ -160,7 +163,10 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'expanded' => true,
'required' => false,
'choices' => $this->filterServicesByAgeConstraints(
$bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_ADDITIONAL),
$bookingDto->travel->getAdditionalServicesBySubTypes(
Constants::TOKEN_ADDITIONAL,
BookingDto::MODE_EDIT !== $bookingDto->getMode() // Only filter by availability in create mode
),
$bookingDto,
$participantIndex
),
@@ -187,7 +193,7 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
}
// Make readonly if service is unavailable (only if not already mandatory)
if (false === $service->mandatory && $this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
if (false === $service->mandatory && $this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'additionalServices')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
@@ -203,7 +209,10 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'expanded' => true,
'required' => false,
'choices' => $this->filterServicesByAgeConstraints(
$bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_BOARD),
$bookingDto->travel->getAdditionalServicesBySubTypes(
Constants::TOKEN_BOARD,
BookingDto::MODE_CREATE === $bookingDto->getMode() // Only filter by availability in create mode
),
$bookingDto,
$participantIndex
),
@@ -216,8 +225,8 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes = [];
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'board')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
@@ -234,7 +243,11 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'required' => false,
'choices' => $this->filterServicesByAgeConstraints(
$this->filterRentalsBySkiPassDuration(
$bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_RENTALS, true, true),
$bookingDto->travel->getAdditionalServicesBySubTypes(
Constants::TOKEN_RENTALS,
BookingDto::MODE_CREATE === $bookingDto->getMode(), // Only filter by availability in create mode
true // Filter by travel date range
),
$bookingDto,
$participantIndex
),
@@ -255,8 +268,8 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes['data-description'] = $service->description;
}
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'rentals')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
@@ -292,7 +305,11 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'expanded' => true,
'required' => true,
'choices' => $this->filterServicesByAgeConstraints(
$bookingDto->travel->getAdditionalServicesBySubTypes(Constants::TOKEN_SKI_PASS, true, true),
$bookingDto->travel->getAdditionalServicesBySubTypes(
Constants::TOKEN_SKI_PASS,
BookingDto::MODE_CREATE === $bookingDto->getMode(), // Only filter by availability in create mode
true // Filter by travel date range
),
$bookingDto,
$participantIndex
),
@@ -310,8 +327,8 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes['data-description'] = $service->description;
}
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'skiPass')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
@@ -348,19 +365,14 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes = [];
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'transportationOutbound')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
return $attributes;
},
'attr' => [
'hx-post' => $this->urlGenerator->generate('app_booking_create_step_2_refresh'),
'hx-swap' => 'none',
'hx-trigger' => 'change',
],
];
// Inbound Transportation
@@ -379,19 +391,14 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$attributes = [];
// Make readonly if service is unavailable
if ($this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex)) {
// Make readonly if service is unavailable (intelligently handles edit mode)
if ($this->shouldMakeServiceReadonly($service, $bookingDto, $participantIndex, 'transportationInbound')) {
$attributes['readonly'] = true;
$attributes['data-tooltip'] = 'ausgebucht';
}
return $attributes;
},
'attr' => [
'hx-post' => $this->urlGenerator->generate('app_booking_create_step_2_refresh'),
'hx-swap' => 'none',
'hx-trigger' => 'change',
],
];
// Pickup (conditional - only shown when either transportation direction is bus)
@@ -419,11 +426,6 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
$this->fieldOptionProviders['bulkInsuranceBooking'] = fn (BookingDto $bookingDto, int $participantIndex, array $options = []) => [
'label' => 'Für alle Teilnehmer buchen',
'required' => false,
'attr' => [
'hx-post' => $this->urlGenerator->generate('app_booking_create_step_2_refresh'),
'hx-swap' => 'none',
'hx-trigger' => 'change',
],
];
// Insurance field provider - provides age and eligibility filtered insurances for participants
@@ -434,11 +436,6 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
'expanded' => true,
'required' => false,
'insurances' => $this->getEligibleInsurances($bookingDto, $participantIndex),
'attr' => [
'hx-post' => $this->urlGenerator->generate('app_booking_create_step_2_refresh'),
'hx-swap' => 'none',
'hx-trigger' => 'change',
],
];
// Future field providers would be added here, for example:
@@ -601,6 +598,78 @@ class ParticipantFieldOptionsProvider extends AbstractFieldOptionsProvider
return $this->serviceAvailabilityCalculator->isServiceUnavailable($service->id, $bookingDto, $participantIndex);
}
/**
* Determines if a service should be rendered as read-only.
*
* This method intelligently handles readonly state for services in both create and edit modes:
*
* - CREATE MODE: Uses existing availability calculator logic
* - EDIT MODE: Services unavailable (available <= 0) are readonly ONLY if participant doesn't already have them
*
* This prevents fingerprint false positives in edit mode by allowing participants to keep
* services they already have, even if those services are now fully booked.
*
* @param Service $service The service to check
* @param BookingDto $bookingDto The booking DTO containing participant data
* @param int $participantIndex Index of the participant currently selecting services
* @param string $fieldName Name of the service field (e.g., 'courses', 'board', 'rentals')
*
* @return bool True if the service should be read-only
*/
private function shouldMakeServiceReadonly(Service $service, BookingDto $bookingDto, int $participantIndex, string $fieldName): bool
{
// In CREATE mode, use existing availability logic
if (BookingDto::MODE_CREATE === $bookingDto->getMode()) {
return $this->isServiceUnavailableForParticipant($service, $bookingDto, $participantIndex);
}
// In EDIT mode, apply intelligent readonly logic
// If service is available (available > 0), it's never readonly
if (null !== $service->available && $service->available > 0) {
return false;
}
// Service is unavailable - check if participant already has it
$participant = $bookingDto->getParticipant($participantIndex);
if (null === $participant) {
return true; // Readonly if no participant data
}
// Check if participant has this service based on field type
$participantHasService = match ($fieldName) {
'courses' => $this->hasServiceById($participant->courses, $service->id),
'additionalServices' => $this->hasServiceById($participant->additionalServices, $service->id),
'board' => $this->hasServiceById($participant->board, $service->id),
'rentals' => $this->hasServiceById($participant->rentals, $service->id),
'skiPass' => $participant->skiPass?->id === $service->id,
'transportationOutbound' => $participant->transportationOutbound?->id === $service->id,
'transportationInbound' => $participant->transportationInbound?->id === $service->id,
default => false,
};
// Make readonly only if participant doesn't have it
return false === $participantHasService;
}
/**
* Checks if a service array contains a service with the given ID.
*
* @param array $services Array of Service objects
* @param int $serviceId Service ID to search for
*
* @return bool True if the service is found in the array
*/
private function hasServiceById(array $services, int $serviceId): bool
{
foreach ($services as $service) {
if ($service->id === $serviceId) {
return true;
}
}
return false;
}
/**
* Filters services based on participant's age constraints.
*
+172
View File
@@ -0,0 +1,172 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Form\Model\BookingDto;
/**
* Generates fingerprints of booking state for change detection in edit mode.
*
* Creates SHA-256 hashes of all mutable booking data to detect unsaved changes.
* Used by EditController to determine if user modifications need to be saved.
*/
class BookingFingerprintService
{
/**
* Generates a fingerprint (hash) of all mutable booking data.
*
* The fingerprint includes payment details and all participant data including
* personal information, addresses, body dimensions, room assignments, and service selections.
*/
public function generateFingerprint(BookingDto $bookingDto, bool $logData = false): string
{
$data = [
'paymentMethod' => $bookingDto->paymentMethod,
'bankAccount' => [
'iban' => $bookingDto->bankAccount?->iban,
'accountHolder' => $bookingDto->bankAccount?->accountHolder,
],
'participants' => [],
];
foreach ($bookingDto->participants as $index => $participant) {
$data['participants'][$index] = [
'personalData' => [
'firstName' => $participant->firstName,
'lastName' => $participant->lastName,
'dateOfBirth' => $participant->dateOfBirth?->format('Y-m-d'),
'email' => $participant->email,
'mobile' => $participant->mobile,
'gender' => $participant->gender,
'nationality' => $participant->nationality,
],
'address' => [
'street' => $participant->address?->street,
'postCode' => $participant->address?->postCode,
'city' => $participant->address?->city,
'country' => $participant->address?->country,
],
'bodyDimensions' => [
'height' => $participant->height,
'weight' => $participant->weight,
'shoeSize' => $participant->shoeSize,
],
'roomAssignment' => [
'assignedRoomId' => $participant->assignedRoomId,
'remarksRoom' => $participant->remarksRoom,
],
'licensePlate' => $participant->licensePlate,
'services' => [
'skiPass' => $participant->skiPass?->id,
'courses' => $this->normalizeServiceArray($participant->courses),
'board' => $this->normalizeServiceArray($participant->board),
'rentals' => $this->normalizeServiceArray($participant->rentals),
'rentalInsurance' => $participant->rentalInsurance?->id,
'additionalServices' => $this->normalizeServiceArray($participant->additionalServices),
'transportationOutbound' => $participant->transportationOutbound?->id,
'transportationInbound' => $participant->transportationInbound?->id,
'pickup' => $participant->pickup?->id,
'parking' => $participant->parking,
'insurance' => $participant->insurance?->id,
'bulkInsuranceBooking' => $participant->bulkInsuranceBooking,
],
];
}
$fingerprint = hash('sha256', serialize($data));
if ($logData) {
error_log(sprintf('[Fingerprint] Generated fingerprint: %s', $fingerprint));
error_log(sprintf('[Fingerprint] Serialized data: %s', serialize($data)));
}
return $fingerprint;
}
/**
* Normalizes a service array to ensure consistent fingerprinting.
*
* Extracts service IDs, sorts them, and returns a simple indexed array.
* This ensures that associative arrays, indexed arrays, and different orders
* all produce the same fingerprint as long as the same services are present.
*
* @param array $services Array of Service objects
*
* @return array Sorted array of service IDs
*/
private function normalizeServiceArray(array $services): array
{
$ids = array_map(fn ($s) => $s->id, $services);
sort($ids);
return array_values($ids);
}
/**
* Checks if the booking has unsaved changes in edit mode.
*
* Compares the current state fingerprint with the original fingerprint
* that was set when the booking was loaded from the API.
*/
public function isDirty(BookingDto $bookingDto): bool
{
if (BookingDto::MODE_EDIT !== $bookingDto->getMode()) {
return false;
}
if (null === $bookingDto->originalFingerprint) {
return false;
}
$currentFingerprint = $this->generateFingerprint($bookingDto);
$isDirty = $bookingDto->originalFingerprint !== $currentFingerprint;
// Debug logging to identify what changed
if ($isDirty) {
error_log(sprintf('[Fingerprint] DIRTY DETECTED! Original: %s, Current: %s', $bookingDto->originalFingerprint, $currentFingerprint));
$this->logFingerprintDiff($bookingDto);
}
return $isDirty;
}
/**
* Logs detailed fingerprint data for debugging dirty state issues.
*/
private function logFingerprintDiff(BookingDto $bookingDto): void
{
foreach ($bookingDto->participants as $index => $participant) {
$participantData = [
'firstName' => $participant->firstName,
'lastName' => $participant->lastName,
'dateOfBirth' => $participant->dateOfBirth?->format('Y-m-d'),
'email' => $participant->email,
'mobile' => $participant->mobile,
'gender' => $participant->gender,
'nationality' => $participant->nationality,
'address' => [
'street' => $participant->address?->street,
'postCode' => $participant->address?->postCode,
'city' => $participant->address?->city,
'country' => $participant->address?->country,
],
'services' => [
'skiPass' => $participant->skiPass?->id,
'courses' => $this->normalizeServiceArray($participant->courses),
'board' => $this->normalizeServiceArray($participant->board),
'rentals' => $this->normalizeServiceArray($participant->rentals),
'rentalInsurance' => $participant->rentalInsurance?->id,
'additionalServices' => $this->normalizeServiceArray($participant->additionalServices),
'transportationOutbound' => $participant->transportationOutbound?->id,
'transportationInbound' => $participant->transportationInbound?->id,
'pickup' => $participant->pickup?->id,
'parking' => $participant->parking,
],
];
error_log(sprintf('[Fingerprint] Participant %d data: %s', $index, json_encode($participantData)));
}
}
}
+64 -3
View File
@@ -56,6 +56,12 @@ class BookingPriceCalculatorService
{
$roomPricing = [];
// In edit mode, use room data from the booking entity
if (BookingDto::MODE_EDIT === $bookingDto->getMode() && null !== $bookingDto->booking) {
return $this->calculateRoomPricingFromBooking($bookingDto);
}
// In create mode, use room selections from the form
$selectedRooms = $bookingDto->getSelectedRooms();
if (true === empty($selectedRooms)) {
return $roomPricing;
@@ -86,6 +92,61 @@ class BookingPriceCalculatorService
return $roomPricing;
}
/**
* Calculates room pricing from booking entity data (edit mode).
*
* In edit mode, room prices come from the booking entity's individualPrice arrays.
* Each participant has their room price stored in the room's individualPrice array.
*
* @param BookingDto $bookingDto The booking data with booking entity
*
* @return array Array of room pricing data with labels, quantities, and totals
*/
private function calculateRoomPricingFromBooking(BookingDto $bookingDto): array
{
$roomPricing = [];
$roomGroups = [];
// Group participants by room and sum their individual prices
foreach ($bookingDto->booking->rooms as $room) {
if (false === isset($roomGroups[$room->id])) {
$roomGroups[$room->id] = [
'room' => $room,
'participantCount' => 0,
'totalPrice' => 0.0,
];
}
// Sum individual prices for all participants in this room
foreach ($room->mapping as $participantIndex) {
$individualPrice = $room->individualPrice[$participantIndex] ?? 0.0;
$roomGroups[$room->id]['totalPrice'] += $individualPrice;
++$roomGroups[$room->id]['participantCount'];
}
}
// Build pricing array
foreach ($roomGroups as $roomId => $data) {
$room = $data['room'];
$participantCount = $data['participantCount'];
$totalPrice = $data['totalPrice'];
// Calculate average unit price (price per person)
$unitPrice = $participantCount > 0 ? $totalPrice / $participantCount : 0.0;
$roomPricing[] = [
'roomId' => $room->id,
'label' => $room->label,
'quantity' => $room->totalCount,
'participantCount' => $participantCount,
'unitPrice' => $unitPrice,
'totalPrice' => $totalPrice,
];
}
return $roomPricing;
}
/**
* Calculates pricing for all selected services across all participants, grouped by subtype.
*
@@ -516,9 +577,9 @@ class BookingPriceCalculatorService
/**
* Calculates the total service cost for a single participant.
*
* @param ParticipantDto $participant The participant to calculate services for
* @param bool $includeInsurance Whether to include insurance pricing (default: true)
* @param BookingDto|null $bookingDto Optional booking DTO for bulk insurance resolution
* @param ParticipantDto $participant The participant to calculate services for
* @param bool $includeInsurance Whether to include insurance pricing (default: true)
* @param BookingDto|null $bookingDto Optional booking DTO for bulk insurance resolution
* @param bool $onlyInsuranceCalculationServices Only include services with includeInInsuranceCalculation=true (default: false)
*
* @return float The total service cost for this participant
+4 -4
View File
@@ -72,7 +72,7 @@ class ParticipantCardDataService
$firstName = $participant->firstName ?? '';
$lastName = $participant->lastName ?? '';
$name = trim($firstName . ' ' . $lastName);
$name = trim($firstName.' '.$lastName);
if ('' === $name) {
return sprintf('Teilnehmer %d', $index + 1);
@@ -98,7 +98,7 @@ class ParticipantCardDataService
return 'Unbekanntes Zimmer';
}
return $room->name;
return $room->label;
}
/**
@@ -110,6 +110,6 @@ class ParticipantCardDataService
$price = $prices[$index] ?? 0.0;
return number_format($price, 2, ',', '.') . ' €';
return number_format($price, 2, ',', '.').' €';
}
}
}