feat: stop booking flow when BusPro is unreachable

This commit is contained in:
fromme committed 2026-11-11 19:51:52 +01:00
1 parent ac23baf625
commit 55378b2bbc
9 files changed
+249 -43

No files matched your search

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Controller\Booking\Create;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\HotelNotFoundException;
use App\Exception\HotelNotInTravelException;
use App\Exception\NoRoomsAvailableException;
@@ -119,6 +120,10 @@ class IndexController extends AbstractController
} catch (TravelNotFoundException|HotelNotFoundException|HotelNotInTravelException|NoRoomsAvailableException $e) {
$this->addFlash('error', $e->getMessage());
return $this->htmxRedirect($request, $this->generateUrl('app_booking_create_error'));
} catch (BookingBackendUnavailableException) {
$this->addFlash('error', 'Unser Buchungssystem ist gerade nicht erreichbar. Bitte versuche es in ein paar Minuten erneut.');
return $this->htmxRedirect($request, $this->generateUrl('app_booking_create_error'));
}
}
@@ -6,6 +6,7 @@ namespace App\Controller\Booking\Create;
use App\BusProNet\Model\Travel;
use App\Entity\User;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\BookingSessionNotFoundException;
use App\Exception\HotelNotInTravelException;
use App\Exception\TravelNotFoundException;
@@ -67,8 +68,19 @@ class Step2Controller extends AbstractBookingCreateController
return $redirect;
}
// Enrich with fresh availability data
$this->travelDataService->enrichWithFreshAvailabilities($bookingCreateDto->travel);
// Enrich with fresh availability data. Opening the step is the last moment before the customer
// types in participant data, so an unreachable BusPro stops them here rather than at the inquiry
// in step 3. Submitting the step stays lenient: the data is entered by then, and step 3 says so.
try {
$this->travelDataService->enrichWithFreshAvailabilities(
$bookingCreateDto->travel,
requireReachable: false === $request->isMethod(Request::METHOD_POST),
);
} catch (BookingBackendUnavailableException) {
$this->addFlash('error', 'Unser Buchungssystem ist gerade nicht erreichbar. Deine Zimmerauswahl bleibt gespeichert, bitte versuche es in ein paar Minuten erneut.');
return $this->redirectToRoute('app_booking_create_step_1');
}
// Resync the room selections with the refreshed travel before any participant count is derived
// from them, and send the customer back to step 1 when a room they picked is gone.
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Controller\Booking\Create;
use App\BusProNet\Client\BookingClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Exception\TimeoutException;
use App\BusProNet\Model\BookingResponse;
use App\BusProNet\Model\Notification;
@@ -183,7 +184,17 @@ class Step3Controller extends AbstractBookingCreateController
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Die Anfrage hat zu lange gedauert. Bitte versuche es erneut oder wende dich an den Kundenservice.',
'Die Anfrage hat zu lange gedauert. Deine Angaben bleiben gespeichert, bitte versuche es in ein paar Minuten erneut oder wende dich an den Kundenservice.',
);
} catch (ApiClientException $e) {
$this->handleApiError(
$this->logger,
'Booking inquiry failed to reach BusPro',
[
'exception' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
],
'Unser Buchungssystem ist gerade nicht erreichbar. Deine Angaben bleiben gespeichert, bitte versuche es in ein paar Minuten erneut.',
);
} catch (\Exception $e) {
$this->handleApiError(
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Exception;
/**
* Thrown when BusPro cannot be reached at a point where the booking flow must not continue without it.
*
* The flow can render most steps from XML export and snapshot data, but the inquiry in step 3 and the
* booking itself always need BusPro. Failing before the customer types in participant data is kinder
* than failing after.
*/
class BookingBackendUnavailableException extends \RuntimeException
{
}
+7 -1
View File
@@ -10,6 +10,7 @@ use App\BusProNet\Model\Service;
use App\BusProNet\Model\Travel;
use App\BusProNet\Service\BookingStatusRuleRegistry;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\NoRoomsAvailableException;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
@@ -46,6 +47,11 @@ class BookingConfigurator
* - 'Frei': Regular booking with availability checks
* - 'Option': Create-flow override from specific rules
* - 'Anfrage': Inquiry booking, allows booking even with 0 availability
*
* The availability call doubles as the health check for the whole flow: if BusPro cannot be
* reached now, the inquiry in step 3 would fail after the customer typed in every participant.
*
* @throws BookingBackendUnavailableException When BusPro cannot be reached
*/
public function startFreshBooking(Request $request, int $dateId, int $hotelId, ?int $agencyId = null): BookingDto
{
@@ -56,7 +62,7 @@ class BookingConfigurator
// Fetch and patch availability data (includes allowedBookingStatus from API)
// Force refresh ensures fresh data at booking start, then populates cache for subsequent loads
$availabilities = $this->travelDataService->getAvailabilityData($dateId, cached: true, forceRefresh: true);
$availabilities = $this->travelDataService->getAvailabilityData($dateId, cached: true, forceRefresh: true, requireReachable: true);
if (null !== $availabilities) {
$this->travelDataService->patchAvailabilities($travelData, $availabilities);
}
+61 -38
View File
@@ -11,6 +11,7 @@ use App\BusProNet\Model\Notification;
use App\BusProNet\Model\ServiceAvailabilityResponse;
use App\BusProNet\Model\Travel;
use App\BusProNet\XmlLoader\TravelLoader;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\HotelNotInTravelException;
use App\Exception\TravelNotFoundException;
use Psr\Cache\InvalidArgumentException;
@@ -328,24 +329,47 @@ class TravelDataProvider
/**
* Gets availability data for a travel date.
*
* @param int $dateId The travel date ID for API call
* @param bool $cached Whether to use cached data (default: false)
* @param bool $forceRefresh Whether to invalidate cache before fetching (requires cached: true)
* A failed connection is never cached, so the next call asks BusPro again instead of
* reusing the failure for the whole TTL.
*
* @param int $dateId The travel date ID for API call
* @param bool $cached Whether to use cached data (default: false)
* @param bool $forceRefresh Whether to invalidate cache before fetching (requires cached: true)
* @param bool $requireReachable Whether an unreachable BusPro throws instead of returning null
*
* @return ServiceAvailabilityResponse|null The availability data or null if not available or error occurred
*
* @throws BookingBackendUnavailableException When BusPro cannot be reached and $requireReachable is set
*/
public function getAvailabilityData(int $dateId, bool $cached = false, bool $forceRefresh = false): ?ServiceAvailabilityResponse
{
if ($cached) {
return $this->fetchCached(
sprintf('availability_%d', $dateId),
self::AVAILABILITY_CACHE_TTL,
fn () => $this->fetchAvailabilityData($dateId),
$forceRefresh,
);
}
public function getAvailabilityData(
int $dateId,
bool $cached = false,
bool $forceRefresh = false,
bool $requireReachable = false,
): ?ServiceAvailabilityResponse {
try {
if ($cached) {
return $this->fetchCached(
sprintf('availability_%d', $dateId),
self::AVAILABILITY_CACHE_TTL,
fn () => $this->fetchAvailabilityData($dateId),
$forceRefresh,
);
}
return $this->fetchAvailabilityData($dateId);
return $this->fetchAvailabilityData($dateId);
} catch (ApiClientException $e) {
$this->logger->error('Failed to fetch availability data from API', [
'dateId' => $dateId,
'error' => $e->getMessage(),
]);
if ($requireReachable) {
throw new BookingBackendUnavailableException(sprintf('BusPro is unreachable for travel date %d.', $dateId), 0, $e);
}
return null;
}
}
/**
@@ -366,12 +390,15 @@ class TravelDataProvider
/**
* Enriches travel data with fresh availability information from the API.
*
* @param Travel $travel The travel object to enrich
* @param bool $cached Whether to use cached availability data (default: true)
* @param Travel $travel The travel object to enrich
* @param bool $cached Whether to use cached availability data (default: true)
* @param bool $requireReachable Whether an unreachable BusPro throws instead of leaving the travel as is
*
* @throws BookingBackendUnavailableException When BusPro cannot be reached and $requireReachable is set
*/
public function enrichWithFreshAvailabilities(Travel $travel, bool $cached = true): void
public function enrichWithFreshAvailabilities(Travel $travel, bool $cached = true, bool $requireReachable = false): void
{
$availabilities = $this->getAvailabilityData($travel->id, $cached);
$availabilities = $this->getAvailabilityData($travel->id, $cached, requireReachable: $requireReachable);
if (null !== $availabilities) {
$this->patchAvailabilities($travel, $availabilities);
@@ -573,34 +600,30 @@ class TravelDataProvider
}
}
/**
* Lets a connection failure propagate, so it escapes the cache callback without being stored.
*
* @throws ApiClientException
*/
private function fetchAvailabilityData(int $dateId): ?ServiceAvailabilityResponse
{
try {
$availabilities = $this->travelClient->getAvailabilities($dateId);
$availabilities = $this->travelClient->getAvailabilities($dateId);
if ($availabilities instanceof Notification) {
$this->logger->warning('API returned notification for availability data', [
'dateId' => $dateId,
'message' => $availabilities->message,
'isError' => $availabilities->isError(),
]);
return null;
}
$this->logger->debug('Successfully fetched availability data', [
if ($availabilities instanceof Notification) {
$this->logger->warning('API returned notification for availability data', [
'dateId' => $dateId,
]);
return $availabilities;
} catch (ApiClientException $e) {
$this->logger->error('Failed to fetch availability data from API', [
'dateId' => $dateId,
'error' => $e->getMessage(),
'message' => $availabilities->message,
'isError' => $availabilities->isError(),
]);
return null;
}
$this->logger->debug('Successfully fetched availability data', [
'dateId' => $dateId,
]);
return $availabilities;
}
/**
@@ -10,6 +10,7 @@ use App\BusProNet\Model\CrmSelectionGroup;
use App\BusProNet\Model\Room;
use App\BusProNet\Model\Travel;
use App\Controller\Booking\Create\Step2Controller;
use App\Exception\BookingBackendUnavailableException;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Model\RoomSelectionDto;
@@ -184,6 +185,66 @@ class Step2ControllerTest extends TestCase
$this->assertCount(6, $bookingDto->participants, 'Two rooms for three people each yield six participants');
}
public function testSendsCustomerBackToStep1WhenBusProIsUnreachableOnOpeningTheStep(): void
{
$bookingDto = $this->createBookingDto($this->createTravel([$this->createRoom(1409, 'Einzelzimmer', minPax: 1)]));
$travelDataService = $this->createMock(TravelDataProvider::class);
$travelDataService->expects($this->once())
->method('enrichWithFreshAvailabilities')
->with($bookingDto->travel, true, true)
->willThrowException(new BookingBackendUnavailableException());
$bookingService = $this->createMock(BookingConfigurator::class);
$bookingService->expects($this->never())->method('reconcileRoomSelections');
$bookingSessionService = $this->createStub(BookingSessionManager::class);
$bookingSessionService->method('getOrCreateBookingCreateDto')->willReturn($bookingDto);
$controller = $this->createController(
$bookingService,
$bookingSessionService,
$this->createStub(LoggerInterface::class),
$travelDataService,
);
$response = $controller->index(Request::create('/bookings/create/participants', 'GET'));
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertSame('/app_booking_create_step_1', $response->getTargetUrl());
$this->assertSame(
[['error', 'Unser Buchungssystem ist gerade nicht erreichbar. Deine Zimmerauswahl bleibt gespeichert, bitte versuche es in ein paar Minuten erneut.']],
$controller->flashes
);
}
public function testDoesNotRequireAReachableBusProWhenTheStepIsSubmitted(): void
{
$bookingDto = $this->createBookingDto($this->createTravel([$this->createRoom(1409, 'Einzelzimmer', minPax: 1)]));
$travelDataService = $this->createMock(TravelDataProvider::class);
$travelDataService->expects($this->once())
->method('enrichWithFreshAvailabilities')
->with($bookingDto->travel, true, false);
$bookingService = $this->createStub(BookingConfigurator::class);
$bookingService->method('reconcileRoomSelections')->willReturn([]);
$bookingSessionService = $this->createStub(BookingSessionManager::class);
$bookingSessionService->method('getOrCreateBookingCreateDto')->willReturn($bookingDto);
$controller = $this->createController(
$bookingService,
$bookingSessionService,
$this->createStub(LoggerInterface::class),
$travelDataService,
);
$controller->index(Request::create('/bookings/create/participants', 'POST'));
$this->assertSame([], $controller->flashes);
}
public function testEndsASplitTheTravelDateDoesNotOffer(): void
{
$bookingDto = $this->createSplitBookingDto($this->createTravel([$this->createRoom(1409, 'Einzelzimmer', minPax: 1)]));
@@ -245,6 +306,7 @@ class Step2ControllerTest extends TestCase
BookingConfigurator $bookingService,
BookingSessionManager $bookingSessionService,
LoggerInterface $logger,
?TravelDataProvider $travelDataService = null,
): TestableStep2Controller {
$form = $this->createStub(FormInterface::class);
$form->method('isSubmitted')->willReturn(false);
@@ -253,7 +315,7 @@ class Step2ControllerTest extends TestCase
$bookingService,
$bookingSessionService,
$this->createStub(BookingCreateContextFactory::class),
$this->createStub(TravelDataProvider::class),
$travelDataService ?? $this->createStub(TravelDataProvider::class),
$this->createStub(RoomAssigner::class),
$this->createStub(ParticipantDataPrefiller::class),
$logger,
@@ -13,6 +13,7 @@ use App\BusProNet\Model\Travel;
use App\BusProNet\Service\BookingStatusRuleRegistry;
use App\BusProNet\Service\StatusRule\Selection1473StatusRule;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\NoRoomsAvailableException;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
@@ -69,6 +70,28 @@ class BookingConfiguratorStatusTest extends TestCase
$this->assertCount(1, $bookingDto->roomSelections);
}
public function testStartFreshBookingRequiresAReachableBusPro(): void
{
$travel = $this->createTravelWithRooms([
['status' => Constants::STATUS_AVAILABLE, 'available' => 5],
]);
$this->travelDataService
->method('getTravelData')
->willReturn($travel);
$this->travelDataService
->method('getAvailabilityData')
->willReturnCallback(function (int $dateId, bool $cached = false, bool $forceRefresh = false, bool $requireReachable = false): never {
$this->assertTrue($requireReachable, 'Starting a booking must not fall back to export data silently');
throw new BookingBackendUnavailableException();
});
$this->expectException(BookingBackendUnavailableException::class);
$this->bookingService->startFreshBooking($this->createRequestWithSession(), 123, 456);
}
public function testStartFreshBookingWithFreiRoomsAndNoAvailabilityThrowsException(): void
{
$travel = $this->createTravelWithRooms([
+48
View File
@@ -5,8 +5,11 @@ declare(strict_types=1);
namespace App\Tests\Service;
use App\BusProNet\Client\TravelClient;
use App\BusProNet\Exception\ApiClientException;
use App\BusProNet\Exception\TimeoutException;
use App\BusProNet\Model\Travel;
use App\BusProNet\XmlLoader\TravelLoader;
use App\Exception\BookingBackendUnavailableException;
use App\Exception\TravelNotFoundException;
use App\Service\TravelDataProvider;
use App\Service\TravelEnricher;
@@ -14,6 +17,7 @@ use App\Service\TravelIndex;
use App\Service\TravelSnapshotManager;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Contracts\Cache\CacheInterface;
class TravelDataProviderTest extends TestCase
@@ -494,4 +498,48 @@ class TravelDataProviderTest extends TestCase
$this->assertSame($travel, $result);
}
public function testGetAvailabilityDataReturnsNullWhenBusProIsUnreachable(): void
{
$this->travelClient = $this->createStub(TravelClient::class);
$this->travelClient->method('getAvailabilities')->willThrowException(new TimeoutException('Stream timeout'));
$this->assertNull($this->service()->getAvailabilityData(4711));
}
public function testGetAvailabilityDataThrowsWhenBusProIsUnreachableAndRequired(): void
{
$this->travelClient = $this->createStub(TravelClient::class);
$this->travelClient->method('getAvailabilities')->willThrowException(new ApiClientException('Unable to open socket'));
$this->expectException(BookingBackendUnavailableException::class);
$this->service()->getAvailabilityData(4711, requireReachable: true);
}
public function testGetAvailabilityDataDoesNotCacheAFailedConnection(): void
{
$this->travelClient = $this->createStub(TravelClient::class);
$this->travelClient->method('getAvailabilities')->willThrowException(new ApiClientException('Unable to open socket'));
$cache = new ArrayAdapter();
$this->cache = $cache;
$this->assertNull($this->service()->getAvailabilityData(4711, cached: true));
$this->assertFalse($cache->hasItem('availability_4711'), 'The next call must ask BusPro again');
}
public function testEnrichWithFreshAvailabilitiesThrowsWhenBusProIsUnreachableAndRequired(): void
{
$this->travelClient = $this->createStub(TravelClient::class);
$this->travelClient->method('getAvailabilities')->willThrowException(new ApiClientException('Unable to open socket'));
$this->cache = new ArrayAdapter();
$travel = new Travel();
$travel->id = 4711;
$this->expectException(BookingBackendUnavailableException::class);
$this->service()->enrichWithFreshAvailabilities($travel, requireReachable: true);
}
}