Files
myep/src/Controller/Booking/Edit/IndexController.php
T

463 lines
18 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controller\Booking\Edit;
use App\BusProNet\ApiClient;
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\BookingExceptionHandlerTrait;
use App\Entity\User;
use App\Exception\TravelNotFoundException;
use App\Form\BookingEditType;
use App\Form\BookingParticipantType;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantEditDto;
use App\Htmx\HxTrait;
use App\Service\BookingEditDataLoaderService;
use App\Service\BookingEditDraftService;
use App\Service\BookingFingerprintService;
use App\Service\BookingService;
use App\Service\BookingSummaryDataService;
use App\Service\ParticipantCardDataService;
use App\Service\TravelDataService;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* 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 BookingExceptionHandlerTrait;
use HxTrait;
use Traits\ParticipantCardFlowTrait;
public function __construct(
private readonly ApiClient $apiClient,
private readonly BookingEditDataLoaderService $dataLoader,
private readonly BookingEditDraftService $draftService,
private readonly TravelDataService $travelDataService,
private readonly BookingService $bookingService,
private readonly BookingFingerprintService $fingerprintService,
private readonly BookingSummaryDataService $summaryDataService,
private readonly ParticipantCardDataService $participantCardService,
private readonly LoggerInterface $logger,
) {
}
/**
* Entry point for editing a booking from the booking list.
*
* Clears any existing session data and API cache to ensure fresh data
* is loaded, then redirects to the main edit page.
*/
#[Route('/bookings/{id}/edit/start', name: 'app_booking_edit_start', requirements: ['id' => '\d+'])]
#[IsGranted('ROLE_USER')]
public function start(int $id, Request $request): Response
{
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
$this->dataLoader->invalidateBookingCache($id);
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
/**
* 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();
// Load form data from session (or API on first load)
try {
$bookingDto = $this->dataLoader->loadFormData($request, $id, $user);
} catch (TravelNotFoundException) {
$this->addFlash('error', 'Reisedaten sind nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
if (null === $bookingDto) {
$this->addFlash('error', 'Buchungsdaten nicht (mehr) verfügbar');
return $this->redirectToRoute('app_bookings');
}
// Show flash message if draft was restored
if (true === $this->dataLoader->wasDraftRestored()) {
$this->addFlash('info', 'Dein zuvor gespeicherter Entwurf wurde wiederhergestellt.');
}
// Fetch booking data for display (surcharges, canceled status, etc.)
$bookingData = $this->dataLoader->fetchBookingData($id, $user);
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);
$form->handleRequest($request);
// Handle form submission (clicking "Buchung aktualisieren")
if ($form->isSubmitted() && $form->isValid()) {
return $this->handleFormSubmission($request, $bookingDto, $id, $user);
}
// Always generate card data with validation state to show completeness
$cardsData = $this->participantCardService->getAllCardsDataWithValidation($bookingDto);
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($bookingDto);
$templateData = [
'form' => $form->createView(),
'bookingDto' => $bookingDto,
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'cardsData' => $cardsData,
'summaryData' => $summaryData,
'isDirty' => $this->fingerprintService->isDirty($bookingDto),
'isSubmitted' => $form->isSubmitted(),
'hasValidationErrors' => $form->isSubmitted() && false === $form->isValid(),
];
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();
// 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->dataLoader->fetchBookingData($id, $user);
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 = 'S' === ($bookingData->participantsStatus[$index] ?? null);
if ($isCanceled) {
$this->addFlash('warning', 'Stornierte Teilnehmer können nicht bearbeitet werden');
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
// Use cached availability data (populated during booking init)
$this->travelDataService->enrichWithFreshAvailabilities($bookingDto->travel);
// Create wrapper DTO for email uniqueness validation
$wrapper = new ParticipantEditDto(
participant: $participant,
bookingContext: $bookingDto,
);
// Create form for participant with booking context
$form = $this->createForm(BookingParticipantType::class, $wrapper, [
'booking_context' => $bookingDto,
'height_choices' => $this->getParameter('body_dimensions.height_choices'),
'weight_choices' => $this->getParameter('body_dimensions.weight_choices'),
'shoe_size_min' => $this->getParameter('body_dimensions.shoe_size_min'),
'shoe_size_max' => $this->getParameter('body_dimensions.shoe_size_max'),
]);
$form->handleRequest($request);
// Collect notifications from field handlers (run during PRE_SUBMIT)
$notifications = $this->collectAndClearNotifications($bookingDto);
if ($form->isSubmitted() && $form->isValid()) {
// Save updated booking data to session
$this->bookingService->saveBookingDto($request, $bookingDto, BookingDto::MODE_EDIT);
// Auto-save draft to database for data persistence
$this->draftService->saveDraft($user, $id, $bookingDto);
// Add notifications as flash messages (redirects destroy HTMX-triggered toasts)
$this->addNotificationsAsFlashMessages($notifications);
// Redirect back to cards
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($bookingDto);
// Fetch mutable data for form constraints
$mutableData = $this->travelDataService->getMutabilityData($bookingData->dateId);
$templateData = [
'form' => $form->createView(),
'participantIndex' => $index,
'bookingDto' => $bookingDto,
'bookingData' => $bookingData,
'mutableData' => $mutableData,
'summaryData' => $summaryData,
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'cancelRouteName' => 'app_booking_edit',
'cancelRouteParams' => ['id' => $id],
];
return $this->render('booking/edit/participant.html.twig', $templateData);
}
/**
* 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();
// 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
$this->travelDataService->enrichWithFreshAvailabilities($bookingDto->travel);
// Fetch booking data and mutable data
$bookingData = $this->dataLoader->fetchBookingData($id, $user);
$mutableData = null !== $bookingData && !($bookingData instanceof Notification)
? $this->travelDataService->getMutabilityData($bookingData->dateId)
: null;
// Create wrapper DTO for form
$wrapper = new ParticipantEditDto(
participant: $bookingDto->participants[$index],
bookingContext: $bookingDto,
);
// Create form with validation disabled
$form = $this->createForm(BookingParticipantType::class, $wrapper, [
'booking_context' => $bookingDto,
'validation_groups' => false,
'height_choices' => $this->getParameter('body_dimensions.height_choices'),
'weight_choices' => $this->getParameter('body_dimensions.weight_choices'),
'shoe_size_min' => $this->getParameter('body_dimensions.shoe_size_min'),
'shoe_size_max' => $this->getParameter('body_dimensions.shoe_size_max'),
]);
$form->handleRequest($request);
// Collect notifications from field handlers
$notifications = $this->collectAndClearNotifications($bookingDto);
// Get complete summary data (pricing, rooms, CMS data)
$summaryData = $this->summaryDataService->getSummaryData($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,
'refreshRouteName' => 'app_booking_edit_participant_refresh',
'refreshRouteParams' => ['id' => $id, 'index' => $index],
'cancelRouteName' => 'app_booking_edit',
'cancelRouteParams' => ['id' => $id],
]
);
// Add notifications to HX-Trigger header if present
if (false === empty($notifications)) {
$response->headers->set('HX-Trigger', json_encode([
'showNotifications' => $notifications,
]));
}
return $response;
}
/**
* Reloads booking data from API, discarding all session changes.
*
* GET: Returns modal HTML for confirmation
* POST: Clears session and redirects to reload the booking
*/
#[Route(
path: '/bookings/{id}/edit/reload',
name: 'app_booking_edit_reload',
requirements: ['id' => '\d+']
)]
#[IsGranted('ROLE_USER')]
public function reloadFromApi(int $id, Request $request): Response
{
if (Request::METHOD_POST === $request->getMethod()) {
// Clear session to discard all changes
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
// Delete draft since user explicitly chose to discard changes
/** @var User $user */
$user = $this->getUser();
$this->draftService->deleteDraft($user, $id);
$this->addFlash('success', 'Änderungen verworfen, Daten neu geladen');
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
return $this->render('booking/edit/modal_reload.html.twig', [
'bookingId' => $id,
]);
}
/**
* Handles "Zurück" button - clears session and preserves draft.
*
* Draft is preserved so the user can continue editing later.
* Shows a flash message informing about the saved draft.
*/
#[Route(
path: '/bookings/{id}/edit/cancel',
name: 'app_booking_edit_cancel',
requirements: ['id' => '\d+']
)]
#[IsGranted('ROLE_USER')]
public function cancelEdit(int $id, Request $request): Response
{
// Clear session state
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
// Check if a draft exists to show appropriate message
/** @var User $user */
$user = $this->getUser();
$draft = $this->draftService->findDraft($user, $id);
if (null !== $draft) {
$this->addFlash('info', 'Deine Änderungen wurden als Entwurf gespeichert.');
}
return $this->redirectToRoute('app_bookings');
}
/**
* Handles form submission for booking update.
*/
private function handleFormSubmission(Request $request, BookingDto $bookingDto, int $id, User $user): Response
{
$email = $user->getEmail();
$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,
]);
} elseif (true === $response->success) {
// Invalidate cache and clear session on success
$this->dataLoader->invalidateBookingCache($id);
$this->bookingService->clearBookingDto($request, BookingDto::MODE_EDIT);
// Delete draft on successful submission
$this->draftService->deleteDraft($user, $id);
$this->addFlash('success', 'Buchung erfolgreich aktualisiert');
$this->logger->info('Booking update successful', [
'email' => $email,
'booking_id' => $id,
]);
return $this->redirectToRoute('app_booking_edit', ['id' => $id]);
} else {
// BookingUpdate received but success is false
$this->addFlash('error', $response->status ?? 'Buchung konnte nicht aktualisiert werden');
$this->logger->warning('Booking update returned unsuccessful status', [
'email' => $email,
'booking_id' => $id,
'status' => $response->status,
'valid' => $response->valid,
]);
}
} 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 $this->redirectToRoute('app_booking_edit', ['id' => $id]);
}
}