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

+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