From 3d94505e8d0fb7facd8ad92456c7bbb266c9e9b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Wed, 11 Nov 2026 16:35:49 +0100 Subject: [PATCH] feat: cap rooms sharing a contingent per booking --- config/services.yaml | 3 + src/BpnConnect/RoomsClient.php | 33 ++++ .../Booking/Create/Step1Controller.php | 11 +- src/Form/Model/BookingCreateContext.php | 4 + src/Model/RoomContingentPool.php | 48 ++++++ src/Service/BookingConfigurator.php | 28 +++- src/Service/BookingCreateContextFactory.php | 24 +++ src/Service/RoomContingentPoolResolver.php | 89 +++++++++++ src/Validator/Constraints/RoomSelection.php | 6 +- .../Constraints/RoomSelectionValidator.php | 38 ++++- templates/booking/create/step_1.html.twig | 12 +- tests/BpnConnect/RoomsClientTest.php | 68 ++++++++ tests/Service/BookingConfiguratorBabyTest.php | 2 + ...kingConfiguratorRoomReconciliationTest.php | 51 +++++- .../Service/BookingConfiguratorStatusTest.php | 5 + .../BookingCreateContextFactoryTest.php | 48 ++++++ .../RoomContingentPoolResolverTest.php | 151 ++++++++++++++++++ .../RoomSelectionValidatorTest.php | 69 +++++++- 18 files changed, 671 insertions(+), 19 deletions(-) create mode 100644 src/BpnConnect/RoomsClient.php create mode 100644 src/Model/RoomContingentPool.php create mode 100644 src/Service/RoomContingentPoolResolver.php create mode 100644 tests/BpnConnect/RoomsClientTest.php create mode 100644 tests/Service/RoomContingentPoolResolverTest.php diff --git a/config/services.yaml b/config/services.yaml index 956e9a90..e73217e6 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -426,6 +426,9 @@ services: App\BpnConnect\TravelsClient: parent: App\BpnConnect\AbstractApiClient + App\BpnConnect\RoomsClient: + parent: App\BpnConnect\AbstractApiClient + App\ClickUp\ApiClient: arguments: $apiToken: '%env(default::CLICKUP_API_TOKEN)%' diff --git a/src/BpnConnect/RoomsClient.php b/src/BpnConnect/RoomsClient.php new file mode 100644 index 00000000..be38fd70 --- /dev/null +++ b/src/BpnConnect/RoomsClient.php @@ -0,0 +1,33 @@ +`) + * + * @return array room type id => room type id owning its contingent + */ + public function getContingentPools(int $hotelId): array + { + $payload = $this->request(self::CONTINGENT_POOLS_PATH, ['hotelId' => $hotelId]); + + $pools = []; + foreach ($payload['data'] ?? [] as $item) { + $pools[(int) $item['room_type_id']] = (int) $item['pool_room_type_id']; + } + + return $pools; + } +} diff --git a/src/Controller/Booking/Create/Step1Controller.php b/src/Controller/Booking/Create/Step1Controller.php index ca14f8ba..c2e58b34 100644 --- a/src/Controller/Booking/Create/Step1Controller.php +++ b/src/Controller/Booking/Create/Step1Controller.php @@ -13,7 +13,6 @@ use App\Htmx\HxTrait; use App\Service\BookingConfigurator; use App\Service\BookingCreateContextFactory; use App\Service\BookingSessionManager; -use App\Service\RoomPricingCalculator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; @@ -77,10 +76,7 @@ class Step1Controller extends AbstractBookingCreateController return $this->redirectToRoute('app_booking_create_step_2'); } - $context = $this->createContextFactory->create( - $bookingCreateDto, - RoomPricingCalculator::PRICING_MODE_SELECTION - ); + $context = $this->createContextFactory->createForRoomSelection($bookingCreateDto); return $this->render('booking/create/step_1.html.twig', [ 'bookingCreateContext' => $context, @@ -107,10 +103,7 @@ class Step1Controller extends AbstractBookingCreateController ]); $form->handleRequest($request); - $context = $this->createContextFactory->create( - $bookingCreateDto, - RoomPricingCalculator::PRICING_MODE_SELECTION - ); + $context = $this->createContextFactory->createForRoomSelection($bookingCreateDto); // The DTO is now updated with the latest selection. // We can now render the blocks with the fresh data. diff --git a/src/Form/Model/BookingCreateContext.php b/src/Form/Model/BookingCreateContext.php index d64027b5..58e82e47 100644 --- a/src/Form/Model/BookingCreateContext.php +++ b/src/Form/Model/BookingCreateContext.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Form\Model; +use App\Model\RoomContingentPool; + /** * Bundles the data needed to render the booking create flow. */ @@ -12,6 +14,7 @@ class BookingCreateContext /** * @param array|null $cardsData * @param array|null $participantPrices + * @param array $roomContingentPools shared pools by member room id, step 1 only */ public function __construct( public readonly BookingDto $bookingDto, @@ -21,6 +24,7 @@ class BookingCreateContext public readonly bool $isSubmitted = false, public readonly ?array $participantPrices = null, public readonly bool $familyInsuranceUpgradeAvailable = false, + public readonly array $roomContingentPools = [], ) { } } diff --git a/src/Model/RoomContingentPool.php b/src/Model/RoomContingentPool.php new file mode 100644 index 00000000..4ab02baf --- /dev/null +++ b/src/Model/RoomContingentPool.php @@ -0,0 +1,48 @@ + $rooms the offered members, indexed by room id + */ + public function __construct( + public array $rooms, + ) { + } + + /** + * Rooms left in the pool. The members should all report the same figure; the lowest is the + * safe reading if they ever disagree. + */ + public function getAvailable(): int + { + return min(array_map(static fn (Room $room): int => $room->available ?? 0, $this->rooms)); + } + + public function contains(int $roomId): bool + { + return isset($this->rooms[$roomId]); + } + + /** + * @return list + */ + public function getLabels(): array + { + return array_values(array_map(static fn (Room $room): string => (string) $room->label, $this->rooms)); + } +} diff --git a/src/Service/BookingConfigurator.php b/src/Service/BookingConfigurator.php index 6a3a4aca..44ee4774 100644 --- a/src/Service/BookingConfigurator.php +++ b/src/Service/BookingConfigurator.php @@ -15,6 +15,7 @@ use App\Form\Model\BookingDto; use App\Form\Model\ParticipantDto; use App\Form\Model\RoomSelectionDto; use App\Form\Service\ServiceAgeEvaluator; +use App\Model\RoomContingentPool; use App\Model\RoomSelectionAdjustment; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\HttpFoundation\Request; @@ -28,6 +29,7 @@ class BookingConfigurator private readonly ParticipantEligibilityChecker $participantEligibilityService, private readonly BookingStatusRuleRegistry $bookingStatusRuleRegistry, private readonly AgencyLoader $agencyLoader, + private readonly RoomContingentPoolResolver $poolResolver, #[Autowire(param: 'default_booking_status')] private readonly string $defaultBookingStatus, ) { @@ -102,16 +104,19 @@ class BookingConfigurator * exists; one that only loses part of its contingent leaves a quantity nothing else re-checks * before the booking is submitted; and one that becomes bookable again has no selection at all. * Rebuilding the selections from the current rooms, with the chosen quantities carried over and - * capped at what is left, keeps both sides in step. + * capped at what is left, keeps both sides in step. Rooms sharing a contingent are capped + * together as well, in selection order, since BusPro reports the shared remainder on each. * * @return list The selections that had to give up quantity, in selection order */ public function reconcileRoomSelections(BookingDto $bookingDto): array { $availableRooms = $bookingDto->travel->getAvailableRooms(); + $pools = $this->poolResolver->findSharedPools($bookingDto->travel); $adjustments = []; $quantitiesByRoomId = []; + $poolRemainders = []; foreach ($bookingDto->roomSelections as $roomSelection) { if (null === $roomSelection->id) { @@ -121,6 +126,13 @@ class BookingConfigurator $requestedQuantity = $roomSelection->quantity ?? 0; $bookableQuantity = min($requestedQuantity, $availableRooms[$roomSelection->id]->available ?? 0); + $poolIndex = $this->findPoolIndex($pools, $roomSelection->id); + if (null !== $poolIndex) { + $poolRemainders[$poolIndex] ??= $pools[$poolIndex]->getAvailable(); + $bookableQuantity = min($bookableQuantity, $poolRemainders[$poolIndex]); + $poolRemainders[$poolIndex] -= $bookableQuantity; + } + $quantitiesByRoomId[$roomSelection->id] = $bookableQuantity; if (0 < $requestedQuantity && $bookableQuantity < $requestedQuantity) { @@ -141,6 +153,20 @@ class BookingConfigurator return $adjustments; } + /** + * @param list $pools + */ + private function findPoolIndex(array $pools, int $roomId): ?int + { + foreach ($pools as $index => $pool) { + if ($pool->contains($roomId)) { + return $index; + } + } + + return null; + } + /** * Creates a room selection DTO from room data and quantities. * diff --git a/src/Service/BookingCreateContextFactory.php b/src/Service/BookingCreateContextFactory.php index af549f5c..af5ca8d4 100644 --- a/src/Service/BookingCreateContextFactory.php +++ b/src/Service/BookingCreateContextFactory.php @@ -20,6 +20,7 @@ class BookingCreateContextFactory private readonly BookingSummaryAssembler $summaryDataService, private readonly BookingPriceCalculator $priceCalculator, private readonly FamilyInsuranceAvailabilityChecker $familyInsuranceService, + private readonly RoomContingentPoolResolver $poolResolver, ) { } @@ -37,6 +38,29 @@ class BookingCreateContextFactory ); } + /** + * The step 1 context, which also tells which offered rooms share a contingent. + */ + public function createForRoomSelection(BookingDto $bookingDto): BookingCreateContext + { + $baseContext = $this->buildBaseContext($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION); + + $poolsByRoomId = []; + foreach ($this->poolResolver->findSharedPools($bookingDto->travel) as $pool) { + foreach (array_keys($pool->rooms) as $roomId) { + $poolsByRoomId[$roomId] = $pool; + } + } + + return new BookingCreateContext( + bookingDto: $bookingDto, + summaryData: $baseContext['summaryData'], + groupedRooms: $baseContext['groupedRooms'], + familyInsuranceUpgradeAvailable: $baseContext['familyInsuranceUpgradeAvailable'], + roomContingentPools: $poolsByRoomId, + ); + } + public function createWithParticipantCards(BookingDto $bookingDto, bool $isSubmitted): BookingCreateContext { $baseContext = $this->buildBaseContext($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION); diff --git a/src/Service/RoomContingentPoolResolver.php b/src/Service/RoomContingentPoolResolver.php new file mode 100644 index 00000000..77805190 --- /dev/null +++ b/src/Service/RoomContingentPoolResolver.php @@ -0,0 +1,89 @@ + pools with more than one offered room, in room order + */ + public function findSharedPools(Travel $travel): array + { + if (null === $travel->hotelId) { + return []; + } + + $poolIds = $this->getPoolIds($travel->hotelId); + if ([] === $poolIds) { + return []; + } + + $roomsByPool = []; + foreach ($travel->getAvailableRooms() as $roomId => $room) { + $roomsByPool[$poolIds[$roomId] ?? $roomId][$roomId] = $room; + } + + $pools = []; + foreach ($roomsByPool as $rooms) { + if (1 < count($rooms)) { + $pools[] = new RoomContingentPool($rooms); + } + } + + return $pools; + } + + /** + * @return array room type id => pool room type id, empty when unknown + */ + private function getPoolIds(int $hotelId): array + { + try { + return $this->cache->get( + sprintf('bpn_connect_room_contingent_pools_%d', $hotelId), + function (ItemInterface $item) use ($hotelId): array { + $item->expiresAfter(self::CACHE_TTL_SECONDS); + + return $this->roomsClient->getContingentPools($hotelId); + } + ); + } catch (BpnConnectException $e) { + // Thrown inside the callback, so nothing was cached and the next request asks again. + $this->logger->error('Room contingent pools unavailable, rooms are checked one by one', [ + 'hotel_id' => $hotelId, + 'error' => $e->getMessage(), + ]); + + return []; + } + } +} diff --git a/src/Validator/Constraints/RoomSelection.php b/src/Validator/Constraints/RoomSelection.php index a4a2eea3..d1d119a5 100644 --- a/src/Validator/Constraints/RoomSelection.php +++ b/src/Validator/Constraints/RoomSelection.php @@ -10,14 +10,16 @@ use Symfony\Component\Validator\Constraint; * Validates room selection requirements for bookings. * * Applied as a class-level constraint on BookingDto to ensure valid room - * configurations: at least one room must be selected, and baby rooms - * cannot be booked without accompanying regular rooms. + * configurations: at least one room must be selected, baby rooms + * cannot be booked without accompanying regular rooms, and rooms that + * share a contingent cannot together exceed what is left of it. */ #[\Attribute] class RoomSelection extends Constraint { public string $noRoomSelectedMessage = 'Bitte mindestens ein Zimmer/Bett auswählen'; public string $onlyBabyRoomsMessage = 'Baby-Zimmer können nur in Kombination mit regulären Zimmern gebucht werden.'; + public string $sharedContingentExceededMessage = 'Diese Zimmer teilen sich ein Kontingent, von dem nur noch {{ available }} verfügbar ist: {{ rooms }}. Bitte reduziere deine Auswahl.'; public function getTargets(): array|string { diff --git a/src/Validator/Constraints/RoomSelectionValidator.php b/src/Validator/Constraints/RoomSelectionValidator.php index 806a0071..bf259406 100644 --- a/src/Validator/Constraints/RoomSelectionValidator.php +++ b/src/Validator/Constraints/RoomSelectionValidator.php @@ -6,6 +6,7 @@ namespace App\Validator\Constraints; use App\BusProNet\Constants; use App\Form\Model\BookingDto; +use App\Service\RoomContingentPoolResolver; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; @@ -13,11 +14,17 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException; /** * Validates room selection business rules for bookings. * - * Enforces that at least one room is selected and that baby rooms (BABY code) - * are only booked in combination with regular rooms, not standalone. + * Enforces that at least one room is selected, that baby rooms (BABY code) + * are only booked in combination with regular rooms, not standalone, and that + * rooms sharing a contingent do not together take more than is left of it. */ class RoomSelectionValidator extends ConstraintValidator { + public function __construct( + private readonly RoomContingentPoolResolver $poolResolver, + ) { + } + public function validate(mixed $value, Constraint $constraint): void { if (!$constraint instanceof RoomSelection) { @@ -40,6 +47,33 @@ class RoomSelectionValidator extends ConstraintValidator // Check that not only Baby rooms are selected $this->assertNotOnlyBabyRooms($value, $constraint); + + $this->assertSharedContingentsNotExceeded($value, $constraint); + } + + /** + * BusPro reports a shared contingent's remaining count on every room drawing on it and accepts + * a booking that takes it from two of them, so the sum has to be checked here. + */ + private function assertSharedContingentsNotExceeded(BookingDto $bookingDto, RoomSelection $constraint): void + { + $selectedRooms = $bookingDto->getSelectedRooms(); + + foreach ($this->poolResolver->findSharedPools($bookingDto->travel) as $pool) { + $selectedQuantity = 0; + foreach ($selectedRooms as $roomSelection) { + if (null !== $roomSelection->id && $pool->contains($roomSelection->id)) { + $selectedQuantity += $roomSelection->quantity ?? 0; + } + } + + if ($selectedQuantity > $pool->getAvailable()) { + $this->context->buildViolation($constraint->sharedContingentExceededMessage) + ->setParameter('{{ available }}', (string) $pool->getAvailable()) + ->setParameter('{{ rooms }}', implode(', ', $pool->getLabels())) + ->addViolation(); + } + } } private function assertNotOnlyBabyRooms(BookingDto $bookingDto, RoomSelection $constraint): void diff --git a/templates/booking/create/step_1.html.twig b/templates/booking/create/step_1.html.twig index 9cc49e43..41a55bbb 100644 --- a/templates/booking/create/step_1.html.twig +++ b/templates/booking/create/step_1.html.twig @@ -2,7 +2,7 @@ {% set htmx_change_trigger = 'change delay:300ms' %} -{% macro stepFormField(form) %} +{% macro stepFormField(form, roomId, pool = null) %}
@@ -13,6 +13,12 @@ {{ form.vars.label_price_amount|format_currency('EUR') }} pro Person {% endif %}
+ {% if pool is not null %} +
+ Teilt sich das Kontingent mit: {{ pool.rooms|filter((room, id) => id != roomId)|map(room => room.label)|join(', ') }} + (zusammen noch {{ pool.available }} verfügbar) +
+ {% endif %}
{{ form_row(form, { @@ -70,7 +76,7 @@ Zimmer {% for roomId, room in bookingCreateContext.groupedRooms.byRoom %} - {{ _self.stepFormField(form.roomSelections[roomId]) }} + {{ _self.stepFormField(form.roomSelections[roomId], roomId, bookingCreateContext.roomContingentPools[roomId] ?? null) }} {% endfor %} {% endif %} {% if bookingCreateContext.groupedRooms.byPax is not empty %} @@ -78,7 +84,7 @@ Betten {% for roomId, room in bookingCreateContext.groupedRooms.byPax %} - {{ _self.stepFormField(form.roomSelections[roomId]) }} + {{ _self.stepFormField(form.roomSelections[roomId], roomId, bookingCreateContext.roomContingentPools[roomId] ?? null) }} {% endfor %} {% endif %}
diff --git a/tests/BpnConnect/RoomsClientTest.php b/tests/BpnConnect/RoomsClientTest.php new file mode 100644 index 00000000..cdc474ff --- /dev/null +++ b/tests/BpnConnect/RoomsClientTest.php @@ -0,0 +1,68 @@ +jsonResponse([ + 'meta' => ['hotel_id' => 163113, 'count' => 3, 'execution_time_ms' => 3], + 'data' => [ + ['room_type_id' => 27, 'pool_room_type_id' => 27], + ['room_type_id' => 2366, 'pool_room_type_id' => 2366], + ['room_type_id' => 2367, 'pool_room_type_id' => 2366], + ], + ]); + }); + + $pools = $this->client($http)->getContingentPools(163113); + + self::assertSame([['GET', 'https://bpn-connect.test/api/v1/rooms/contingent-pools?hotelId=163113']], $requests); + self::assertSame([27 => 27, 2366 => 2366, 2367 => 2366], $pools); + } + + public function testAnUnknownHotelYieldsNoPools(): void + { + $http = new MockHttpClient($this->jsonResponse(['meta' => ['hotel_id' => 1, 'count' => 0], 'data' => []])); + + self::assertSame([], $this->client($http)->getContingentPools(1)); + } + + public function testAFailedRequestThrows(): void + { + $http = new MockHttpClient(new MockResponse('', ['http_code' => 500])); + + $this->expectException(BpnConnectException::class); + + $this->client($http)->getContingentPools(163113); + } + + /** + * @param array $payload + */ + private function jsonResponse(array $payload): MockResponse + { + return new MockResponse(json_encode($payload, JSON_THROW_ON_ERROR), [ + 'response_headers' => ['content-type' => 'application/json'], + ]); + } + + private function client(MockHttpClient $http): RoomsClient + { + return new RoomsClient($http, new NullLogger(), 'https://bpn-connect.test', 'secret'); + } +} diff --git a/tests/Service/BookingConfiguratorBabyTest.php b/tests/Service/BookingConfiguratorBabyTest.php index 10a480ea..33d09531 100644 --- a/tests/Service/BookingConfiguratorBabyTest.php +++ b/tests/Service/BookingConfiguratorBabyTest.php @@ -14,6 +14,7 @@ use App\Form\Model\ParticipantDto; use App\Service\BookingConfigurator; use App\Service\BookingSessionManager; use App\Service\ParticipantEligibilityChecker; +use App\Service\RoomContingentPoolResolver; use App\Service\TravelDataProvider; use PHPUnit\Framework\TestCase; @@ -38,6 +39,7 @@ class BookingConfiguratorBabyTest extends TestCase $this->participantEligibilityService, $bookingStatusRuleRegistry, $this->createStub(AgencyLoader::class), + $this->createStub(RoomContingentPoolResolver::class), 'F' // default booking status ); } diff --git a/tests/Service/BookingConfiguratorRoomReconciliationTest.php b/tests/Service/BookingConfiguratorRoomReconciliationTest.php index a5e6aef1..04bb70bf 100644 --- a/tests/Service/BookingConfiguratorRoomReconciliationTest.php +++ b/tests/Service/BookingConfiguratorRoomReconciliationTest.php @@ -11,9 +11,11 @@ use App\BusProNet\Service\BookingStatusRuleRegistry; use App\BusProNet\XmlLoader\AgencyLoader; use App\Form\Model\BookingDto; use App\Form\Model\RoomSelectionDto; +use App\Model\RoomContingentPool; use App\Service\BookingConfigurator; use App\Service\BookingSessionManager; use App\Service\ParticipantEligibilityChecker; +use App\Service\RoomContingentPoolResolver; use App\Service\TravelDataProvider; use PHPUnit\Framework\TestCase; @@ -162,14 +164,61 @@ class BookingConfiguratorRoomReconciliationTest extends TestCase $this->assertSame([], $bookingDto->roomSelections); } - private function bookingService(): BookingConfigurator + public function testCapsRoomsSharingAContingentTogetherInSelectionOrder(): void { + $eight = $this->createRoom(2366, '8er App mit 8 Personen', available: 1, minPax: 8); + $seven = $this->createRoom(2367, '8er App mit 7 Personen', available: 1, minPax: 7); + $travel = $this->createTravel([$eight, $seven]); + + $bookingDto = new BookingDto($travel, 1); + $bookingDto->roomSelections = [ + 2366 => $this->createRoomSelection(2366, quantity: 1), + 2367 => $this->createRoomSelection(2367, quantity: 1), + ]; + + $adjustments = $this->bookingService([new RoomContingentPool([2366 => $eight, 2367 => $seven])]) + ->reconcileRoomSelections($bookingDto); + + $this->assertCount(1, $adjustments); + $this->assertSame(2367, $adjustments[0]->roomId); + $this->assertTrue($adjustments[0]->isDropped()); + $this->assertSame(1, $bookingDto->roomSelections[2366]->quantity); + $this->assertSame(0, $bookingDto->roomSelections[2367]->quantity); + } + + public function testLeavesRoomsSharingAContingentAloneWhileTheyFit(): void + { + $eight = $this->createRoom(2366, '8er App mit 8 Personen', available: 2, minPax: 8); + $seven = $this->createRoom(2367, '8er App mit 7 Personen', available: 2, minPax: 7); + $travel = $this->createTravel([$eight, $seven]); + + $bookingDto = new BookingDto($travel, 1); + $bookingDto->roomSelections = [ + 2366 => $this->createRoomSelection(2366, quantity: 1), + 2367 => $this->createRoomSelection(2367, quantity: 1), + ]; + + $adjustments = $this->bookingService([new RoomContingentPool([2366 => $eight, 2367 => $seven])]) + ->reconcileRoomSelections($bookingDto); + + $this->assertSame([], $adjustments); + } + + /** + * @param list $sharedPools + */ + private function bookingService(array $sharedPools = []): BookingConfigurator + { + $poolResolver = $this->createStub(RoomContingentPoolResolver::class); + $poolResolver->method('findSharedPools')->willReturn($sharedPools); + return new BookingConfigurator( $this->createStub(BookingSessionManager::class), $this->createStub(TravelDataProvider::class), $this->createStub(ParticipantEligibilityChecker::class), $this->createStub(BookingStatusRuleRegistry::class), $this->createStub(AgencyLoader::class), + $poolResolver, 'F' ); } diff --git a/tests/Service/BookingConfiguratorStatusTest.php b/tests/Service/BookingConfiguratorStatusTest.php index af1199ac..1529030f 100644 --- a/tests/Service/BookingConfiguratorStatusTest.php +++ b/tests/Service/BookingConfiguratorStatusTest.php @@ -19,6 +19,7 @@ use App\Form\Model\ParticipantDto; use App\Service\BookingConfigurator; use App\Service\BookingSessionManager; use App\Service\ParticipantEligibilityChecker; +use App\Service\RoomContingentPoolResolver; use App\Service\TravelDataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; @@ -45,6 +46,7 @@ class BookingConfiguratorStatusTest extends TestCase $participantEligibility, $bookingStatusRuleRegistry, $agencyLoader, + $this->createStub(RoomContingentPoolResolver::class), 'F' // default booking status ); } @@ -220,6 +222,7 @@ class BookingConfiguratorStatusTest extends TestCase new Selection1473StatusRule(), ]), $this->createStub(AgencyLoader::class), + $this->createStub(RoomContingentPoolResolver::class), 'F' ); @@ -313,6 +316,7 @@ class BookingConfiguratorStatusTest extends TestCase $this->createStub(ParticipantEligibilityChecker::class), $bookingStatusRuleRegistry, $this->createStub(AgencyLoader::class), + $this->createStub(RoomContingentPoolResolver::class), 'F' ); @@ -344,6 +348,7 @@ class BookingConfiguratorStatusTest extends TestCase $this->createStub(ParticipantEligibilityChecker::class), $bookingStatusRuleRegistry, $this->createStub(AgencyLoader::class), + $this->createStub(RoomContingentPoolResolver::class), 'F' ); diff --git a/tests/Service/BookingCreateContextFactoryTest.php b/tests/Service/BookingCreateContextFactoryTest.php index 03e2e461..2eaed4a0 100644 --- a/tests/Service/BookingCreateContextFactoryTest.php +++ b/tests/Service/BookingCreateContextFactoryTest.php @@ -11,11 +11,13 @@ use App\Form\Model\BookingDto; use App\Form\Model\BookingSummaryDto; use App\Form\Model\ParticipantCardDataDto; use App\Form\Model\ParticipantCardPriceDto; +use App\Model\RoomContingentPool; use App\Service\BookingCreateContextFactory; use App\Service\BookingPriceCalculator; use App\Service\BookingSummaryAssembler; use App\Service\FamilyInsuranceAvailabilityChecker; use App\Service\ParticipantCardAssembler; +use App\Service\RoomContingentPoolResolver; use App\Service\RoomPricingCalculator; use PHPUnit\Framework\TestCase; @@ -71,6 +73,7 @@ class BookingCreateContextFactoryTest extends TestCase $summaryDataService, $priceCalculator, $familyInsuranceService, + $this->createStub(RoomContingentPoolResolver::class), ); $context = $service->create($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION); @@ -134,6 +137,7 @@ class BookingCreateContextFactoryTest extends TestCase $summaryDataService, $priceCalculator, $familyInsuranceService, + $this->createStub(RoomContingentPoolResolver::class), ); $context = $service->createWithParticipantCards($bookingDto, true); @@ -188,6 +192,7 @@ class BookingCreateContextFactoryTest extends TestCase $summaryDataService, $priceCalculator, $familyInsuranceService, + $this->createStub(RoomContingentPoolResolver::class), ); $context = $service->createWithParticipantPrices($bookingDto); @@ -198,4 +203,47 @@ class BookingCreateContextFactoryTest extends TestCase $this->assertNull($context->cardsData); $this->assertSame([10 => $room], $context->groupedRooms->byRoom); } + + public function testCreateForRoomSelectionIndexesSharedPoolsByMemberRoom(): void + { + $travel = new Travel(); + $travel->dateFrom = new \DateTimeImmutable('2030-01-01'); + $travel->dateTo = new \DateTimeImmutable('2030-01-06'); + + $eight = new Room(); + $eight->id = 2366; + $eight->label = '8er App mit 8 Personen'; + $eight->maxPax = 8; + $eight->available = 1; + $eight->status = 'Frei'; + + $seven = new Room(); + $seven->id = 2367; + $seven->label = '8er App mit 7 Personen'; + $seven->maxPax = 7; + $seven->available = 1; + $seven->status = 'Frei'; + + $travel->rooms = [$eight, $seven]; + $bookingDto = new BookingDto($travel, 163113); + + $pool = new RoomContingentPool([2366 => $eight, 2367 => $seven]); + $poolResolver = $this->createStub(RoomContingentPoolResolver::class); + $poolResolver->method('findSharedPools')->willReturn([$pool]); + + $summaryDataService = $this->createStub(BookingSummaryAssembler::class); + $summaryDataService->method('getSummaryData')->willReturn($this->createStub(BookingSummaryDto::class)); + + $service = new BookingCreateContextFactory( + $this->createStub(ParticipantCardAssembler::class), + $summaryDataService, + $this->createStub(BookingPriceCalculator::class), + $this->createStub(FamilyInsuranceAvailabilityChecker::class), + $poolResolver, + ); + + $context = $service->createForRoomSelection($bookingDto); + + $this->assertSame([2366 => $pool, 2367 => $pool], $context->roomContingentPools); + } } diff --git a/tests/Service/RoomContingentPoolResolverTest.php b/tests/Service/RoomContingentPoolResolverTest.php new file mode 100644 index 00000000..f771c801 --- /dev/null +++ b/tests/Service/RoomContingentPoolResolverTest.php @@ -0,0 +1,151 @@ + 27, 'pool_room_type_id' => 27], + ['room_type_id' => 2366, 'pool_room_type_id' => 2366], + ['room_type_id' => 2367, 'pool_room_type_id' => 2366], + ['room_type_id' => 2368, 'pool_room_type_id' => 2366], + ]; + + public function testGroupsOfferedRoomsThatShareAContingent(): void + { + $resolver = $this->resolver(new MockHttpClient($this->poolsResponse(self::POOLS_163113))); + + $pools = $resolver->findSharedPools($this->createTravel([ + $this->createRoom(27, 'Doppelzimmer', available: 3), + $this->createRoom(2366, '8er App mit 8 Personen', available: 1), + $this->createRoom(2367, '8er App mit 7 Personen', available: 1), + $this->createRoom(2368, '8er App mit 6 Personen', available: 1), + ])); + + self::assertCount(1, $pools); + self::assertSame([2366, 2367, 2368], array_keys($pools[0]->rooms)); + self::assertSame(1, $pools[0]->getAvailable()); + } + + public function testLeavesOutPoolsWithASingleOfferedRoom(): void + { + $resolver = $this->resolver(new MockHttpClient($this->poolsResponse(self::POOLS_163113))); + + $pools = $resolver->findSharedPools($this->createTravel([ + $this->createRoom(2366, '8er App mit 8 Personen', available: 1), + $this->createRoom(2367, '8er App mit 7 Personen', available: 0), + ])); + + self::assertSame([], $pools); + } + + public function testAsksBpnConnectOncePerHotel(): void + { + $calls = 0; + $http = new MockHttpClient(function () use (&$calls): MockResponse { + ++$calls; + + return $this->poolsResponse(self::POOLS_163113); + }); + $resolver = $this->resolver($http); + $travel = $this->sharedPoolTravel(); + + $resolver->findSharedPools($travel); + $resolver->findSharedPools($travel); + + self::assertSame(1, $calls); + } + + public function testTreatsEveryRoomAsItsOwnPoolWhenBpnConnectFailsAndAsksAgainNextTime(): void + { + $calls = 0; + $http = new MockHttpClient(function () use (&$calls): MockResponse { + ++$calls; + + return 1 === $calls + ? new MockResponse('', ['http_code' => 503]) + : $this->poolsResponse(self::POOLS_163113); + }); + $resolver = $this->resolver($http); + $travel = $this->sharedPoolTravel(); + + self::assertSame([], $resolver->findSharedPools($travel)); + self::assertCount(1, $resolver->findSharedPools($travel)); + self::assertSame(2, $calls); + } + + public function testATravelWithoutHotelHasNoPools(): void + { + $http = new MockHttpClient(function (): MockResponse { + self::fail('bpn-connect must not be asked without a hotel'); + }); + + $travel = $this->sharedPoolTravel(); + $travel->hotelId = null; + + self::assertSame([], $this->resolver($http)->findSharedPools($travel)); + } + + private function sharedPoolTravel(): Travel + { + return $this->createTravel([ + $this->createRoom(2366, '8er App mit 8 Personen', available: 1), + $this->createRoom(2367, '8er App mit 7 Personen', available: 1), + ]); + } + + /** + * @param list $data + */ + private function poolsResponse(array $data): MockResponse + { + return new MockResponse(json_encode(['meta' => ['hotel_id' => 163113], 'data' => $data], JSON_THROW_ON_ERROR), [ + 'response_headers' => ['content-type' => 'application/json'], + ]); + } + + private function resolver(MockHttpClient $http): RoomContingentPoolResolver + { + return new RoomContingentPoolResolver( + new RoomsClient($http, new NullLogger(), 'https://bpn-connect.test', 'secret'), + new ArrayAdapter(), + new NullLogger(), + ); + } + + /** + * @param list $rooms + */ + private function createTravel(array $rooms): Travel + { + $travel = new Travel(); + $travel->hotelId = 163113; + $travel->rooms = $rooms; + + return $travel; + } + + private function createRoom(int $id, string $label, int $available): Room + { + $room = new Room(); + $room->id = $id; + $room->label = $label; + $room->available = $available; + $room->status = Constants::STATUS_AVAILABLE; + + return $room; + } +} diff --git a/tests/Validator/Constraints/RoomSelectionValidatorTest.php b/tests/Validator/Constraints/RoomSelectionValidatorTest.php index 0eb2baca..0cad617d 100644 --- a/tests/Validator/Constraints/RoomSelectionValidatorTest.php +++ b/tests/Validator/Constraints/RoomSelectionValidatorTest.php @@ -8,15 +8,81 @@ use App\BusProNet\Model\Room; use App\BusProNet\Model\Travel; use App\Form\Model\BookingDto; use App\Form\Model\RoomSelectionDto; +use App\Model\RoomContingentPool; +use App\Service\RoomContingentPoolResolver; use App\Validator\Constraints\RoomSelection; use App\Validator\Constraints\RoomSelectionValidator; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class RoomSelectionValidatorTest extends ConstraintValidatorTestCase { + /** @var list */ + private array $sharedPools = []; + protected function createValidator(): RoomSelectionValidator { - return new RoomSelectionValidator(); + $poolResolver = $this->createStub(RoomContingentPoolResolver::class); + $poolResolver->method('findSharedPools')->willReturnCallback(fn (): array => $this->sharedPools); + + return new RoomSelectionValidator($poolResolver); + } + + public function testRoomsSharingAContingentMayNotTogetherExceedIt(): void + { + $bookingDto = $this->createBookingDto([ + ['id' => 2366, 'code' => '8erSudel', 'quantity' => 1], + ['id' => 2367, 'code' => '8erSudel', 'quantity' => 1], + ]); + $this->shareContingent($bookingDto, [2366, 2367], available: 1); + + $this->validator->validate($bookingDto, new RoomSelection()); + + $this->buildViolation('Diese Zimmer teilen sich ein Kontingent, von dem nur noch {{ available }} verfügbar ist: {{ rooms }}. Bitte reduziere deine Auswahl.') + ->setParameter('{{ available }}', '1') + ->setParameter('{{ rooms }}', 'Zimmer 2366, Zimmer 2367') + ->assertRaised(); + } + + public function testRoomsSharingAContingentPassWhileTheyFit(): void + { + $bookingDto = $this->createBookingDto([ + ['id' => 2366, 'code' => '8erSudel', 'quantity' => 1], + ['id' => 2367, 'code' => '8erSudel', 'quantity' => 1], + ]); + $this->shareContingent($bookingDto, [2366, 2367], available: 2); + + $this->validator->validate($bookingDto, new RoomSelection()); + + $this->assertNoViolation(); + } + + public function testAnUnselectedRoomOfASharedContingentDoesNotCount(): void + { + $bookingDto = $this->createBookingDto([ + ['id' => 2366, 'code' => '8erSudel', 'quantity' => 1], + ['id' => 2367, 'code' => '8erSudel', 'quantity' => 0], + ]); + $this->shareContingent($bookingDto, [2366, 2367], available: 1); + + $this->validator->validate($bookingDto, new RoomSelection()); + + $this->assertNoViolation(); + } + + /** + * @param list $roomIds + */ + private function shareContingent(BookingDto $bookingDto, array $roomIds, int $available): void + { + $rooms = []; + foreach ($bookingDto->travel->rooms as $room) { + if (in_array($room->id, $roomIds, true)) { + $room->available = $available; + $rooms[$room->id] = $room; + } + } + + $this->sharedPools = [new RoomContingentPool($rooms)]; } public function testNoRoomSelectedFailsValidation(): void @@ -141,6 +207,7 @@ class RoomSelectionValidatorTest extends ConstraintValidatorTestCase $room = new Room(); $room->id = $data['id']; $room->code = $data['code']; + $room->label = 'Zimmer '.$data['id']; $room->available = 10; $room->status = 'Frei'; $travel->rooms[] = $room;