feat: refactoring and cleanup

This commit is contained in:
Björn Fromme
2026-03-16 11:59:12 +01:00
parent 230c53875f
commit 8c8aae9a1e
41 changed files with 2591 additions and 2233 deletions
+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]));
}
}