feat: cap rooms sharing a contingent per booking

This commit is contained in:
fromme committed 2026-11-11 16:35:49 +01:00
1 parent 5942ecf340
commit 3d94505e8d
18 files changed
+671 -19

No files matched your search

+3
View File
@@ -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)%'
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\BpnConnect;
class RoomsClient extends AbstractApiClient
{
private const string CONTINGENT_POOLS_PATH = '/api/v1/rooms/contingent-pools';
/**
* Which room type's contingent each room type of a hotel draws on.
*
* The office sells one room at several occupancies by pointing the extra room types at the
* first one's contingent (`PartnerZimmer.IDPartnerZimmer_FS_KontiAus`). A room type with its
* own contingent maps to itself.
*
* @param int $hotelId the hotel's BusPro address id (the export's `<hotel idbuspro>`)
*
* @return array<int, int> 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;
}
}
@@ -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.
+4
View File
@@ -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<int, ParticipantCardDataDto>|null $cardsData
* @param array<int, float>|null $participantPrices
* @param array<int, RoomContingentPool> $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 = [],
) {
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Model;
use App\BusProNet\Model\Room;
/**
* Offered rooms of one travel that draw on the same BusPro contingent.
*
* BusPro reports the pool's remaining count on every member, and checks each room of a booking
* against it separately, so a booking with two members can take more than is left. Only pools
* with more than one offered member exist as objects; every other room is its own pool and is
* already capped by its own count.
*/
final readonly class RoomContingentPool
{
/**
* @param array<int, Room> $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<string>
*/
public function getLabels(): array
{
return array_values(array_map(static fn (Room $room): string => (string) $room->label, $this->rooms));
}
}
+27 -1
View File
@@ -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<RoomSelectionAdjustment> 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<RoomContingentPool> $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.
*
@@ -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);
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\BpnConnect\Exception\BpnConnectException;
use App\BpnConnect\RoomsClient;
use App\BusProNet\Model\Travel;
use App\Model\RoomContingentPool;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/**
* Groups a travel's offered rooms by the BusPro contingent they share.
*
* The link is hotel setup, not availability, so it is cached per hotel; the remaining count keeps
* coming from the travel data. When bpn-connect cannot answer, every room counts as its own pool,
* which is how bookings behaved before: bpn-connect and BusPro sit behind the same link, so a
* booking is unlikely to get through while bpn-connect is unreachable anyway.
*/
class RoomContingentPoolResolver
{
private const int CACHE_TTL_SECONDS = 3600;
public function __construct(
private readonly RoomsClient $roomsClient,
private readonly CacheInterface $cache,
#[Autowire(service: 'monolog.logger.bpn')]
private readonly LoggerInterface $logger,
) {
}
/**
* @return list<RoomContingentPool> 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<int, int> 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 [];
}
}
}
+4 -2
View File
@@ -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
{
@@ -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
+9 -3
View File
@@ -2,7 +2,7 @@
{% set htmx_change_trigger = 'change delay:300ms' %}
{% macro stepFormField(form) %}
{% macro stepFormField(form, roomId, pool = null) %}
<div class="grid grid-cols-3 pb-2">
<div class="col-span-2 pr-2">
<div class="font-semibold">
@@ -13,6 +13,12 @@
{{ form.vars.label_price_amount|format_currency('EUR') }} pro Person
{% endif %}
</div>
{% if pool is not null %}
<div class="text-sm text-gray-500">
Teilt sich das Kontingent mit: {{ pool.rooms|filter((room, id) => id != roomId)|map(room => room.label)|join(', ') }}
(zusammen noch {{ pool.available }} verfügbar)
</div>
{% endif %}
</div>
<div>
{{ form_row(form, {
@@ -70,7 +76,7 @@
Zimmer
</h3>
{% 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
</h3>
{% for roomId, room in bookingCreateContext.groupedRooms.byPax %}
{{ _self.stepFormField(form.roomSelections[roomId]) }}
{{ _self.stepFormField(form.roomSelections[roomId], roomId, bookingCreateContext.roomContingentPools[roomId] ?? null) }}
{% endfor %}
{% endif %}
</div>
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Tests\BpnConnect;
use App\BpnConnect\Exception\BpnConnectException;
use App\BpnConnect\RoomsClient;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class RoomsClientTest extends TestCase
{
public function testGetContingentPoolsQueriesTheHotelAndMapsEachRoomTypeToItsPool(): void
{
$requests = [];
$http = new MockHttpClient(function (string $method, string $url) use (&$requests): MockResponse {
$requests[] = [$method, $url];
return $this->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<string, mixed> $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');
}
}
@@ -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
);
}
@@ -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<RoomContingentPool> $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'
);
}
@@ -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'
);
@@ -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);
}
}
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\BpnConnect\RoomsClient;
use App\BusProNet\Constants;
use App\BusProNet\Model\Room;
use App\BusProNet\Model\Travel;
use App\Service\RoomContingentPoolResolver;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class RoomContingentPoolResolverTest extends TestCase
{
private const array POOLS_163113 = [
['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],
['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<array{room_type_id: int, pool_room_type_id: int}> $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<Room> $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;
}
}
@@ -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<RoomContingentPool> */
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<int> $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;