feat: refactoring and cleanup

This commit is contained in:
Björn Fromme
2025-12-06 15:02:13 +01:00
parent f4691ec67e
commit 696800aafd
41 changed files with 2591 additions and 2233 deletions
@@ -7,6 +7,7 @@ namespace App\Controller\Booking\Create;
use App\Controller\Booking\Traits\BookingCreateTrait;
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
use App\Form\BookingCreateStep1Type;
use App\Form\Model\BookingDto;
use App\Htmx\HxTrait;
use App\Service\BookingService;
use App\Service\BookingSummaryDataService;
@@ -66,15 +67,15 @@ class Step1Controller extends AbstractController
$form->handleRequest($request);
if (true === $form->isSubmitted() && true === $form->isValid()) {
if ($this->bookingService->hasRoomSelectionChanged($oldRoomSelectionSnapshot, $bookingCreateDto)) {
$this->bookingService->resetParticipantAssignments($bookingCreateDto);
if ($bookingCreateDto->hasRoomSelectionChanged($oldRoomSelectionSnapshot)) {
$bookingCreateDto->resetParticipantAssignments();
}
// Check if room selection forces inquiry mode
$this->bookingService->updateBookingStatusFromRoomSelection($bookingCreateDto);
$bookingCreateDto->currentStep = 2;
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
// Clear baseline snapshot when moving to step 2
$this->bookingService->clearBaselineSnapshot($request);
@@ -83,21 +84,16 @@ class Step1Controller extends AbstractController
}
// Get complete summary data (pricing, rooms, CMS data)
$summary = $this->summaryDataService->getSummaryData($bookingCreateDto);
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedRooms = $this->bookingService->groupRoomsBySelectionType($availableRooms);
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summary['selectedRooms'], $availableRooms);
return $this->render('booking/create/step_1.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'roomSummary' => $summary['selectedRooms'],
'participantCount' => $summary['participantCount'],
'pricingData' => $summary['pricingData'],
'cmsData' => $summary['cmsData'],
'summaryData' => $summaryData,
'form' => $form->createView(),
'groupedRooms' => $groupedRooms,
'groupedSelectedRooms' => $groupedSelectedRooms,
]);
}
@@ -120,13 +116,12 @@ class Step1Controller extends AbstractController
]);
$form->handleRequest($request);
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
// Get complete summary data (pricing, rooms, CMS data)
$summary = $this->summaryDataService->getSummaryData($bookingCreateDto);
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedRooms = $this->bookingService->groupRoomsBySelectionType($availableRooms);
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summary['selectedRooms'], $availableRooms);
// The DTO is now updated with the latest selection.
// We can now render the blocks with the fresh data.
@@ -136,11 +131,8 @@ class Step1Controller extends AbstractController
[
'form' => $form->createView(),
'bookingCreateDto' => $bookingCreateDto,
'participantCount' => $summary['participantCount'],
'pricingData' => $summary['pricingData'],
'cmsData' => $summary['cmsData'],
'summaryData' => $summaryData,
'groupedRooms' => $groupedRooms,
'groupedSelectedRooms' => $groupedSelectedRooms,
]
);
}
@@ -9,7 +9,6 @@ use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
use App\Controller\Booking\Traits\ParticipantCardFlowTrait;
use App\Form\BookingCreateStep2Type;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Service\ParticipantFieldOptionsProvider;
use App\Htmx\HxTrait;
use App\Service\BookingService;
@@ -66,13 +65,17 @@ class Step2Controller extends AbstractController
}
// Enrich with fresh availability data
$this->enrichWithFreshAvailabilities($bookingCreateDto);
$this->travelDataService->enrichWithFreshAvailabilities($bookingCreateDto->travel);
// Ensure correct number of participants
$this->ensureCorrectNumberOfParticipants($bookingCreateDto);
// Ensure correct number of participants with prepopulation callback
$this->bookingService->ensureCorrectNumberOfParticipants(
$bookingCreateDto,
$this->getUser(),
fn ($user, $participant) => $this->prepopulationService->prepopulateApplicantFromUser($user, $participant)
);
// Auto-assign rooms if needed
$this->autoAssignRoomsIfNeeded($bookingCreateDto);
$this->roomAssignmentService->assignRoomsIfNeeded($bookingCreateDto);
// Preselect mandatory services
$this->bookingService->preselectMandatoryServices($bookingCreateDto);
@@ -107,8 +110,6 @@ class Step2Controller extends AbstractController
'bookingDto' => $bookingCreateDto,
'cardsData' => $cardsData,
'summaryData' => $summaryData,
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
];
// HTMX request: render blocks only
@@ -143,7 +144,7 @@ class Step2Controller extends AbstractController
}
// Enrich with fresh availability data
$this->enrichWithFreshAvailabilities($bookingDto);
$this->travelDataService->enrichWithFreshAvailabilities($bookingDto->travel);
// Create form with booking_context option
$form = $this->createParticipantForm($bookingDto, $index);
@@ -158,11 +159,7 @@ class Step2Controller extends AbstractController
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_CREATE);
// Add notifications as flash messages (redirects destroy HTMX-triggered toasts)
if (false === empty($notifications)) {
foreach ($notifications as $notification) {
$this->addFlash($notification['type'], $notification['message']);
}
}
$this->addNotificationsAsFlashMessages($notifications);
// HTMX redirect to cards view
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_step_2'));
@@ -176,8 +173,6 @@ class Step2Controller extends AbstractController
'participantIndex' => $index,
'bookingDto' => $bookingDto,
'summaryData' => $summaryData,
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'refreshRouteName' => 'app_booking_create_step_2_participant_refresh',
'submitRouteName' => 'app_booking_create_step_2_participant',
];
@@ -224,7 +219,7 @@ class Step2Controller extends AbstractController
}
// Enrich with fresh availability data
$this->enrichWithFreshAvailabilities($bookingDto);
$this->travelDataService->enrichWithFreshAvailabilities($bookingDto->travel);
// Use trait method for refresh handling
return $this->handleParticipantRefresh(
@@ -235,76 +230,4 @@ class Step2Controller extends AbstractController
'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;
// Prepopulate applicant from authenticated user (index 0 only)
if (0 === $i && $this->getUser() && $this->shouldPrepopulate($participant)) {
$participant = $this->prepopulationService->prepopulateApplicantFromUser(
$this->getUser(),
$participant
);
}
$bookingCreateDto->participants[$i] = $participant;
}
}
/**
* Determines if a participant should be prepopulated.
*
* Only prepopulates if the participant is "fresh" (no name set yet).
*/
private function shouldPrepopulate(ParticipantDto $participant): bool
{
return null === $participant->firstName || '' === $participant->firstName;
}
/**
* 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.
*
* Note: Auto-assignment only occurs when exactly one room type is selected.
* With multiple room types, users must manually select rooms to avoid UX issues
* with having to unselect preassigned rooms in individual participant forms.
*/
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);
}
}
}
@@ -94,7 +94,7 @@ class Step3Controller extends AbstractController
// Auto-switch to inquiry mode
$bookingCreateDto->bookingStatus = 'A';
$bookingCreateDto->currentStep = 4;
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
$message = 'Buchung konnte nicht validiert werden.';
if (null !== $inquiryResponse->message && '' !== trim($inquiryResponse->message)) {
@@ -147,7 +147,7 @@ class Step3Controller extends AbstractController
// Validation successful - proceed to confirmation step
$bookingCreateDto->currentStep = 4;
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
if ($inquiryResponse->message) {
$this->addFlash('info', $inquiryResponse->message);
@@ -199,7 +199,7 @@ class Step3Controller extends AbstractController
]);
$form->handleRequest($request);
$this->bookingService->saveBookingCreateDto($request, $bookingCreateDto);
$this->bookingService->saveBookingDto($request, $bookingCreateDto, BookingDto::MODE_CREATE);
return $this->renderStepForm($bookingCreateDto, $form);
}
@@ -211,17 +211,11 @@ class Step3Controller extends AbstractController
{
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summaryData['selectedRooms'], $availableRooms);
return $this->render('booking/create/step_3.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
'participantCount' => $summaryData['participantCount'],
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'assignmentCounts' => $summaryData['assignmentCounts'],
'groupedSelectedRooms' => $groupedSelectedRooms,
'summaryData' => $summaryData,
]);
}
@@ -102,7 +102,7 @@ class Step4Controller extends AbstractController
// Success: Store booking number in flash and clear session
$this->addFlash('booking_number', $bookingResponse->transactionNumber);
$this->clearTravelDataCache($bookingCreateDto);
$this->bookingService->clearBookingCreateDto($request);
$this->bookingService->clearBookingDto($request, BookingDto::MODE_CREATE);
return $this->hxRedirect($request, $this->generateUrl('app_booking_create_success'));
} catch (TimeoutException $e) {
@@ -140,17 +140,11 @@ class Step4Controller extends AbstractController
{
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($bookingCreateDto);
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($summaryData['selectedRooms'], $availableRooms);
return $this->render('booking/create/step_4.html.twig', [
'bookingCreateDto' => $bookingCreateDto,
'form' => $form->createView(),
'participantCount' => $summaryData['participantCount'],
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'assignmentCounts' => $summaryData['assignmentCounts'],
'groupedSelectedRooms' => $groupedSelectedRooms,
'summaryData' => $summaryData,
'participantPrices' => $this->priceCalculator->calculateAllParticipantIndividualPrices($bookingCreateDto),
]);
}
+60 -174
View File
@@ -5,35 +5,30 @@ 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\Exception\TimeoutException;
use App\BusProNet\Model\Notification;
use App\Controller\Booking\Traits;
use App\Controller\Booking\Traits\BookingDataTrait;
use App\Controller\Booking\Traits\BookingExceptionHandlerTrait;
use App\Entity\User;
use App\Form\BookingEditType;
use App\Form\BookingParticipantType;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantEditDto;
use App\Form\Service\ParticipantFieldHandlerRegistry;
use App\Htmx\HxTrait;
use App\Security\Crypt;
use App\Service\BookingEditDataLoaderService;
use App\Service\BookingFingerprintService;
use App\Service\BookingService;
use App\Service\BookingSummaryDataService;
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.
@@ -46,22 +41,18 @@ use Symfony\Contracts\Cache\CacheInterface;
*/
class IndexController extends AbstractController
{
use BookingDataTrait;
use BookingExceptionHandlerTrait;
use HxTrait;
use Traits\ParticipantCardFlowTrait;
public function __construct(
private readonly ApiClient $apiClient,
private readonly BookingDataProcessor $bookingDataProcessor,
private readonly BookingEditDataLoaderService $dataLoader,
private readonly TravelDataService $travelDataService,
private readonly BookingService $bookingService,
private readonly BookingFingerprintService $fingerprintService,
private readonly BookingSummaryDataService $summaryDataService,
private readonly ParticipantCardDataService $participantCardService,
private readonly ParticipantFieldHandlerRegistry $fieldHandlerRegistry,
private readonly CacheInterface $cache,
private readonly Security $security,
private readonly Crypt $crypt,
private readonly LoggerInterface $logger,
) {
@@ -80,20 +71,27 @@ class IndexController extends AbstractController
$password = $this->crypt->decrypt($user->getPassword());
// Load form data from session (or API on first load)
$bookingDto = $this->loadFormData($request, $id, $email, $password);
$loadResult = $this->dataLoader->loadFormData($request, $id, $email, $password);
$bookingDto = $loadResult['bookingDto'];
if (null === $bookingDto) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
// Show staleness warning if applicable
if (null !== $loadResult['stalenessWarning']) {
$this->addFlash('info', $loadResult['stalenessWarning']);
}
// 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);
$this->dataLoader->resetStalenessTimer($request, $bookingDto);
}
// Fetch booking data for display (surcharges, canceled status, etc.)
$bookingData = $this->fetchBookingData($email, $password, $id);
$bookingData = $this->dataLoader->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
@@ -109,56 +107,7 @@ class IndexController extends AbstractController
// 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 (TimeoutException $e) {
$this->addFlash('error', 'Die Anfrage hat zu lange gedauert. Bitte versuchen Sie es erneut.');
$this->logger->error('Booking update timeout', [
'email' => $email,
'booking_id' => $id,
'exception' => $e->getMessage(),
]);
} 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->handleFormSubmission($request, $bookingDto, $id, $email);
}
// Generate card data for all participants with validation state if form was submitted and failed
@@ -169,24 +118,13 @@ class IndexController extends AbstractController
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($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' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'groupedSelectedRooms' => $groupedSelectedRooms,
'assignmentCounts' => $summaryData['assignmentCounts'],
'summaryData' => $summaryData,
'isDirty' => $this->fingerprintService->isDirty($bookingDto),
'hasValidationErrors' => $form->isSubmitted() && false === $form->isValid(),
];
@@ -237,7 +175,7 @@ class IndexController extends AbstractController
}
// Fetch booking data to check for canceled status
$bookingData = $this->fetchBookingData($email, $password, $id);
$bookingData = $this->dataLoader->fetchBookingData($email, $password, $id);
if (null === $bookingData || $bookingData instanceof Notification) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
@@ -245,10 +183,9 @@ class IndexController extends AbstractController
}
// Check if participant is canceled
$isCanceled = ($bookingData->participantsStatus[$index] ?? null) === 'S';
$isCanceled = 'S' === ($bookingData->participantsStatus[$index] ?? null);
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]);
@@ -275,11 +212,7 @@ class IndexController extends AbstractController
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_EDIT);
// Add notifications as flash messages (redirects destroy HTMX-triggered toasts)
if (false === empty($notifications)) {
foreach ($notifications as $notification) {
$this->addFlash($notification['type'], $notification['message']);
}
}
$this->addNotificationsAsFlashMessages($notifications);
// Redirect back to cards
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
@@ -298,8 +231,6 @@ class IndexController extends AbstractController
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'summaryData' => $summaryData,
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'submitRouteName' => 'app_booking_edit_participant',
@@ -356,13 +287,10 @@ class IndexController extends AbstractController
}
// Refresh availability data
$availabilities = $this->travelDataService->getAvailabilityData($bookingDto->travel->id, cached: true);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($bookingDto->travel, $availabilities);
}
$this->travelDataService->enrichWithFreshAvailabilities($bookingDto->travel);
// Fetch booking data and mutable data
$bookingData = $this->fetchBookingData($email, $password, $id);
$bookingData = $this->dataLoader->fetchBookingData($email, $password, $id);
$mutableData = null !== $bookingData && !($bookingData instanceof Notification)
? $this->travelDataService->getMutabilityData($bookingData->dateId)
: null;
@@ -401,8 +329,6 @@ class IndexController extends AbstractController
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'summaryData' => $summaryData,
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'submitRouteName' => 'app_booking_edit_participant',
@@ -461,92 +387,52 @@ class IndexController extends AbstractController
}
/**
* Loads form data from session or initializes from API on first load.
*
* @return BookingDto|null The form data, or null on error
* Handles form submission for booking update.
*/
private function loadFormData(Request $request, int $bookingId, string $email, string $password): ?BookingDto
private function handleFormSubmission(Request $request, BookingDto $bookingDto, int $id, string $email): Response
{
// Try to load from session first
$formData = $this->bookingService->getBookingDto($request, BookingDto::MODE_EDIT);
$this->logger->info('Initiated booking update', [
'email' => $email,
'booking_id' => $id,
]);
if (null === $formData) {
// First load: initialize from API
return $this->initializeFromApi($request, $bookingId, $email, $password);
}
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 {
// Invalidate cache and clear session on success
$this->dataLoader->invalidateBookingCache($id);
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
// Subsequent load: refresh from session with staleness check
return $this->refreshFromSession($formData);
}
$this->addFlash('success', 'Buchung erfolgreich aktualisiert');
$this->logger->info('Booking update successful', [
'email' => $email,
'booking_id' => $id,
]);
/**
* 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
$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->getAvailabilityData($formData->travel->id, cached: true);
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 $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
} catch (TimeoutException $e) {
$this->addFlash('error', 'Die Anfrage hat zu lange gedauert. Bitte versuchen Sie es erneut.');
$this->logger->error('Booking update timeout', [
'email' => $email,
'booking_id' => $id,
'exception' => $e->getMessage(),
]);
} catch (ApiClientException) {
$this->addFlash('error', 'Es ist ein Fehler in der Kommunikation mit dem Buchungssystem aufgetreten');
}
return $formData;
return $this->hxRedirect($request, $this->generateUrl('app_booking_edit', ['id' => $id]));
}
}
@@ -69,7 +69,7 @@ trait BookingCreateTrait
{
$participantsCount = $this->getParticipantsCount($bookingCreateDto);
$summary = $this->bookingService->getRoomSummaryAndParticipantCount($bookingCreateDto);
$roomAssignmentCounts = $this->bookingService->getRoomAssignmentCounts($bookingCreateDto);
$roomAssignmentCounts = $bookingCreateDto->getRoomAssignmentCounts();
$availableRooms = $bookingCreateDto->travel->getAvailableRooms();
$groupedSelectedRooms = $this->bookingService->groupRoomSelectionsByType($bookingCreateDto->getSelectedRooms(), $availableRooms);
@@ -142,8 +142,6 @@ trait ParticipantCardFlowTrait
'participantIndex' => $index,
'bookingDto' => $bookingDto,
'summaryData' => $summaryData,
'pricingData' => $summaryData['pricingData'],
'cmsData' => $summaryData['cmsData'],
'refreshRouteName' => $refreshRouteName,
'submitRouteName' => $submitRouteName,
]
@@ -159,6 +157,21 @@ trait ParticipantCardFlowTrait
return $response;
}
/**
* Converts collected notifications to flash messages.
*
* Used when redirecting after form submission, as HTMX-triggered toasts
* are destroyed on redirect. Flash messages persist across the redirect.
*
* @param array<array{type: string, message: string}> $notifications The notifications to convert
*/
private function addNotificationsAsFlashMessages(array $notifications): void
{
foreach ($notifications as $notification) {
$this->addFlash($notification['type'], $notification['message']);
}
}
/**
* Required services - implementing controllers must inject these.
*
@@ -170,4 +183,6 @@ trait ParticipantCardFlowTrait
abstract private function createForm(string $type, $data = null, array $options = []): FormInterface;
abstract private function render(string $view, array $parameters = [], ?Response $response = null): Response;
abstract protected function addFlash(string $type, mixed $message): void;
}