Compare commits

...
3 Commits
22 changed files with 789 additions and 70 deletions

No files matched your search

-18
View File
@@ -76,24 +76,6 @@ $rsyncOptions = [
'timeout' => 300,
];
// The provider's rsync (3.5.0) fails to chdir into a destination whose path traverses
// symlinks, which /home/www/p704161 does: `change_dir#1 ... Too many levels of symbolic
// links (40)`. Verified: the same directory rsyncs fine when addressed relative to $HOME.
// Only contrib/rsync.php hands a path to rsync; every other task goes through the SSH
// shell, which resolves the absolute path without trouble, so deploy_path stays absolute.
set('remote_home', '/home/www/p704161');
set('rsync_dest', function () {
$releasePath = get('release_path');
$home = rtrim(get('remote_home'), '/').'/';
if (!str_starts_with($releasePath, $home)) {
return $releasePath;
}
return substr($releasePath, strlen($home));
});
host('prod')
->setHostname('185.243.135.29')
->setRemoteUser('p704161')
+21 -10
View File
@@ -9,15 +9,6 @@ abstract class AbstractParser
{
use TypeConversionTrait;
protected function getIntOrNullAttribute(?string $value): ?int
{
if (null === $value || '' === $value) {
return null;
}
return (int) $value;
}
protected function getStringOrNullValue(Crawler $node): ?string
{
return 0 < $node->count() ? $node->text() : null;
@@ -64,7 +55,27 @@ abstract class AbstractParser
return null;
}
return $node->attr($attribute);
$value = $node->attr($attribute);
if (null !== $value) {
return $value;
}
// BusPro mixes casing (MinPax in the travel export, minpax in booking
// responses) and addXmlContent() makes attr() case-sensitive.
foreach ($node->getNode(0)->attributes ?? [] as $candidate) {
if (0 === strcasecmp($candidate->name, $attribute)) {
return $candidate->value;
}
}
return null;
}
protected function getIntAttrOrNullValue(Crawler $node, string $attribute): ?int
{
$value = $this->getAttrOrNullValue($node, $attribute);
return null !== $value && '' !== $value ? (int) $value : null;
}
protected function getRequiredAttrValue(Crawler $node, string $attribute, string $context): string
+2 -2
View File
@@ -381,8 +381,8 @@ class TravelParser extends AbstractParser
$room->category = $this->getAttrOrNullValue($roomNode, 'kat');
$room->boardId = (int) $this->getAttrOrNullValue($roomNode, 'idbuspro_vp');
$room->label = $this->getAttrOrNullValue($roomNode, 'zimmertext');
$room->minPax = (int) $this->getAttrOrNullValue($roomNode, 'minpax');
$room->maxPax = (int) $this->getAttrOrNullValue($roomNode, 'maxpax');
$room->minPax = $this->getIntAttrOrNullValue($roomNode, 'minpax');
$room->maxPax = $this->getIntAttrOrNullValue($roomNode, 'maxpax');
$room->nights = (int) $this->getAttrOrNullValue($roomNode, 'naechte');
$roomPrice = $this->getAttrOrNullValue($roomNode, 'preis');
$room->price = null !== $roomPrice && '' !== $roomPrice
@@ -19,6 +19,9 @@ use App\Service\BookingSessionManager;
use App\Service\ParticipantDataPrefiller;
use App\Service\RoomAssigner;
use App\Service\TravelDataProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -38,6 +41,8 @@ class Step2Controller extends AbstractBookingCreateController
private readonly TravelDataProvider $travelDataService,
private readonly RoomAssigner $roomAssignmentService,
private readonly ParticipantDataPrefiller $prepopulationService,
#[Autowire(service: 'monolog.logger.bpn')]
private readonly LoggerInterface $logger,
) {
}
@@ -62,6 +67,10 @@ class Step2Controller extends AbstractBookingCreateController
$this->travelDataService->enrichWithFreshAvailabilities($bookingCreateDto->travel);
// Ensure correct number of participants first, then prepopulate the applicant if needed.
if (null !== $redirect = $this->guardAgainstEmptyParticipantList($bookingCreateDto)) {
return $redirect;
}
$this->ensureCorrectNumberOfParticipants($bookingCreateDto);
$user = $this->getUser();
@@ -111,6 +120,49 @@ class Step2Controller extends AbstractBookingCreateController
return $this->render('booking/create/step_2.html.twig', $templateData);
}
/**
* Rejects a room selection that resolves to no participants at all.
*
* A selected room with a quantity always yields at least one participant, so a zero count means the
* travel data carries no room occupancy. Rendering step 2 anyway would show an empty participant list
* that still validates and lets the booking continue to step 3.
*/
private function guardAgainstEmptyParticipantList(BookingDto $bookingCreateDto): ?RedirectResponse
{
$selectedRooms = $bookingCreateDto->getSelectedRooms();
if ([] === $selectedRooms) {
return null;
}
if (0 < $this->calculateParticipantsCount($bookingCreateDto->roomSelections, $bookingCreateDto->travel)) {
return null;
}
$rooms = [];
foreach ($selectedRooms as $roomSelection) {
$rooms[] = [
'roomId' => $roomSelection->id,
'quantity' => $roomSelection->quantity,
'capacity' => $roomSelection->capacity,
];
}
$this->handleApiError(
$this->logger,
'Room selection resolves to zero participants; travel data carries no room occupancy.',
[
'travelId' => $bookingCreateDto->travel->id,
'travelCode' => $bookingCreateDto->travel->code,
'hotelId' => $bookingCreateDto->hotelId,
'rooms' => $rooms,
],
'Die Zimmerdaten dieser Reise sind unvollständig. Bitte wähle dein Zimmer erneut oder kontaktiere uns.'
);
return $this->redirectToRoute('app_booking_create_step_1');
}
/**
* Ensures the booking DTO has the expected number of participant objects based on room selections.
*/
@@ -139,7 +191,7 @@ class Step2Controller extends AbstractBookingCreateController
foreach ($roomSelections as $roomSelection) {
$room = $rooms[$roomSelection->id];
$participantsCount += $room->minPax * $roomSelection->quantity;
$participantsCount += ($room->minPax ?? 1) * $roomSelection->quantity;
}
return $participantsCount;
+1 -1
View File
@@ -209,7 +209,7 @@ class BookingParticipantType extends AbstractType
if ($this->fieldStateProvider->shouldIncludeField('email', $bookingDto, $participantIndex)) {
$form->add('email', EmailType::class, $this->mergeFieldState([
'label' => 'E-Mail',
'required' => !$personalDataOptional,
'required' => false,
'property_path' => 'participant.email',
'attr' => [
'autocomplete' => 'leave-me-alone-chrome',
+33 -4
View File
@@ -12,11 +12,20 @@ use App\BusProNet\Model\Service;
use App\Validator\Constraints as AppAssert;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use function Symfony\Component\String\u;
#[AppAssert\Participant(groups: ['booking_edit', 'booking_create'])]
class ParticipantDto
{
/**
* Age below which a participant counts as a child.
*
* Children may share an email address with an adult and are not required to have one of
* their own; both rules go through isChild(), so this is the only place the age lives.
*/
public const CHILD_AGE_THRESHOLD = 16;
/**
* List of dynamic participant fields that can be conditionally hidden/shown.
*/
@@ -70,8 +79,14 @@ class ParticipantDto
#[Assert\NotNull(message: 'Bitte angeben', groups: ['strict_required'])]
public ?\DateTimeImmutable $dateOfBirth = null;
// Requiredness is delegated to requiresOwnEmail() so the constraint and the field state
// conditions cannot state the rule differently.
#[Assert\Email(message: 'Bitte eine gültige E-Mail Adresse angeben', mode: 'strict', groups: ['booking_edit', 'booking_create'])]
#[Assert\NotBlank(message: 'Bitte angeben', groups: ['strict_required'])]
#[Assert\When(
expression: 'this.requiresOwnEmail()',
constraints: [new Assert\NotBlank(message: 'Bitte angeben')],
groups: ['strict_required']
)]
public ?string $email = null;
public ?string $mobile = null;
@@ -345,11 +360,25 @@ class ParticipantDto
* A child is defined as someone under the specified age threshold (default: 16 years).
* This classification is used for email uniqueness validation (children can share emails with adults).
*
* @param int $ageThreshold The age threshold for child classification (default: 16)
*
* @return bool True if participant is under the age threshold, false otherwise or if age unknown
*/
public function isChild(int $ageThreshold = 16): bool
/**
* Decides whether this participant has to supply an email address of their own.
*
* The applicant is the booking's contact and always has to be reachable. Everyone else only
* needs an address once they are old enough to have one, so children are exempt. An unknown
* date of birth counts as an adult, following isChild().
*
* Single source for the rule: the Assert\When on $email enforces it, and the 'required'
* field state conditions in CreateFieldStateProvider/EditFieldStateProvider render the
* matching mandatory marker.
*/
public function requiresOwnEmail(): bool
{
return $this->isApplicant() || false === $this->isChild();
}
public function isChild(int $ageThreshold = self::CHILD_AGE_THRESHOLD): bool
{
$age = $this->getAge();
+6 -1
View File
@@ -24,12 +24,17 @@ class RoomSelectType extends AbstractType
$data = $event->getData();
$form = $event->getForm();
$choices = ['-' => 0];
if (0 < $data->maxQuantity) {
$choices += array_combine(range(1, $data->maxQuantity), range(1, $data->maxQuantity));
}
$form->add('quantity', StepSelectChoiceType::class, [
'label' => false,
'required' => true,
'min_value' => 0,
'max_value' => $data->maxQuantity,
'choices' => ['-' => 0] + array_combine(range(1, $data->maxQuantity), range(1, $data->maxQuantity)),
'choices' => $choices,
]);
});
}
@@ -113,7 +113,9 @@ abstract class AbstractFieldStateProvider implements FieldStateProviderInterface
* Supported state types:
* - 'readonly': Adds readonly HTML attribute to the field
* - 'disabled': Disables the field completely
* - 'required': Makes the field mandatory
* - 'required': Determines whether the field is mandatory. Unlike the states above this is
* authoritative in both directions: the condition result is assigned as-is, so it can also
* clear a 'required' option set by the form type.
* - 'static_text': Field should be rendered as static text (checked separately via shouldRenderAsStaticText())
* - 'hidden': Field excluded from form entirely (checked via shouldIncludeField())
*
@@ -137,20 +139,30 @@ abstract class AbstractFieldStateProvider implements FieldStateProviderInterface
$attributes = [];
foreach ($this->fieldStateConditions[$fieldName] as $stateType => $condition) {
if ($condition->evaluate($bookingDto, $participantIndex, $formData)) {
switch ($stateType) {
case 'readonly':
$attributes['readonly'] = true;
break;
case 'disabled':
$stateModifications['disabled'] = true;
break;
case 'required':
$stateModifications['required'] = true;
break;
// Note: 'static_text' and 'hidden' are intentionally not handled here
// They are checked via shouldRenderAsStaticText() and shouldIncludeField()
}
$isMet = $condition->evaluate($bookingDto, $participantIndex, $formData);
// 'required' is a determination the provider owns outright, so it is assigned either
// way and can clear the form type's base option. 'readonly' and 'disabled' are
// escalations: a condition can only ever switch them on, never hand back control of a
// field the form type deliberately locked down.
if ('required' === $stateType) {
$stateModifications['required'] = $isMet;
continue;
}
if (false === $isMet) {
continue;
}
switch ($stateType) {
case 'readonly':
$attributes['readonly'] = true;
break;
case 'disabled':
$stateModifications['disabled'] = true;
break;
// Note: 'static_text' and 'hidden' are intentionally not handled here
// They are checked via shouldRenderAsStaticText() and shouldIncludeField()
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Form\Service\Condition;
use App\Form\Model\BookingDto;
use App\Form\Service\Contract\FieldConditionInterface;
/**
* Condition that checks whether the booking belongs to an internal agency.
*
* Internal agency bookings are made by staff on behalf of a customer, so they are exempt
* from several rules that protect customer-entered data: personal data stays editable and
* fields that are mandatory for customers may be left blank.
*
* This is the plain flag on its own. FirstParticipantReadOnlyCondition and
* PersonalDataMutabilityCondition also consult it, but combine it with further criteria.
*/
class InternalAgencyBookingCondition implements FieldConditionInterface
{
/**
* Evaluates whether the booking is an internal agency booking.
*
* @param BookingDto $bookingDto The current booking data (create or edit)
* @param int $participantIndex The index of the participant being evaluated (unused)
* @param array<string, mixed> $formData Current form data (unused)
*
* @return bool True if the booking was made by an internal agency
*/
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool
{
return $bookingDto->isInternalAgencyBooking();
}
/**
* The agency code is a property of the booking, not of any form field.
*
* @return string[] Always empty
*/
public function getDependentFields(): array
{
return [];
}
public function getDescription(): string
{
return 'Checks if the booking is an internal agency booking';
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Form\Service\Condition;
use App\Form\Model\BookingDto;
use App\Form\Service\Contract\FieldConditionInterface;
/**
* Condition that mirrors ParticipantDto::requiresOwnEmail() into the field state layer.
*
* It deliberately holds no logic of its own. The rule for who needs an email address is
* enforced by the Assert\When on ParticipantDto::$email; this condition exists so the
* mandatory marker rendered next to the field is derived from that same method rather than
* from a second, independently maintained composition of age and applicant conditions.
*/
class RequiresOwnEmailCondition implements FieldConditionInterface
{
/**
* Evaluates whether the participant has to supply an email address of their own.
*
* @param BookingDto $bookingDto The current booking data (create or edit)
* @param int $participantIndex The index of the participant being evaluated
* @param array<string, mixed> $formData Current form data (unused)
*
* @return bool True if the participant needs their own email address
*/
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool
{
$participant = $bookingDto->getParticipant($participantIndex);
// A participant that does not exist yet is treated as needing an address, matching the
// "unknown counts as an adult" stance of ParticipantDto::isChild().
return null === $participant || $participant->requiresOwnEmail();
}
/**
* The rule reads the date of birth, so the state has to be recalculated when it changes.
*
* @return string[] Array containing 'dateOfBirth'
*/
public function getDependentFields(): array
{
return ['dateOfBirth'];
}
public function getDescription(): string
{
return 'Checks if the participant needs an email address of their own';
}
}
@@ -20,6 +20,7 @@ use App\Form\Service\Condition\FirstParticipantReadOnlyCondition;
use App\Form\Service\Condition\MultipleParticipantsCondition;
use App\Form\Service\Condition\RentalInsuranceAvailableCondition;
use App\Form\Service\Condition\RentalSelectionCondition;
use App\Form\Service\Condition\RequiresOwnEmailCondition;
use App\Form\Service\Condition\RoomSelectionCondition;
use App\Form\Service\Condition\ServiceSubTypeCondition;
use App\Form\Service\Condition\SingleRoomTypeCondition;
@@ -113,6 +114,7 @@ class CreateFieldStateProvider extends AbstractFieldStateProvider
$this->fieldStateConditions['email'] = [
'static_text' => $firstParticipantReadOnlyCondition,
'required' => new RequiresOwnEmailCondition(),
];
// Mobile field: static text for first participant (when read-only), required for first participant (guest bookings)
+17 -16
View File
@@ -7,7 +7,6 @@ namespace App\Form\Service;
use App\BusProNet\Utility\DirectionMapper;
use App\Form\Model\BookingDto;
use App\Form\Service\Abstract\AbstractFieldStateProvider;
use App\Form\Service\Contract\FieldConditionInterface;
use App\Form\Service\Condition\AdditionalServicesMutabilityCondition;
use App\Form\Service\Condition\AgeRangeCondition;
use App\Form\Service\Condition\BookingModeCondition;
@@ -16,10 +15,12 @@ use App\Form\Service\Condition\DateOfBirthProvidedCondition;
use App\Form\Service\Condition\FieldValueCondition;
use App\Form\Service\Condition\FirstParticipantCondition;
use App\Form\Service\Condition\FirstParticipantReadOnlyCondition;
use App\Form\Service\Condition\InternalAgencyBookingCondition;
use App\Form\Service\Condition\PersonalDataMutabilityCondition;
use App\Form\Service\Condition\PickupsMutabilityCondition;
use App\Form\Service\Condition\RentalInsuranceAvailableCondition;
use App\Form\Service\Condition\RentalSelectionCondition;
use App\Form\Service\Condition\RequiresOwnEmailCondition;
use App\Form\Service\Condition\RoomSelectionCondition;
use App\Form\Service\Condition\ServiceSubTypeCondition;
use App\Form\Service\Condition\SkiPassSelectionCondition;
@@ -69,16 +70,8 @@ class EditFieldStateProvider extends AbstractFieldStateProvider
// TODO: Remove the block below and move 'firstName', 'lastName', 'dateOfBirth' into the
// 'gender'/'nationality' loop once BPN reliably handles name and date-of-birth changes for participants.
// Until then, name and DOB are always read-only for non-internal agency regardless of the BPN flag.
$corePersonalDataReadOnlyCondition = new class implements FieldConditionInterface {
public function evaluate(BookingDto $bookingDto, int $participantIndex, array $formData): bool
{
return !$bookingDto->isInternalAgencyBooking();
}
public function getDependentFields(): array { return []; }
public function getDescription(): string { return 'Name and DOB always read-only for non-internal agency (temporary)'; }
};
$internalAgencyBookingCondition = new InternalAgencyBookingCondition();
$corePersonalDataReadOnlyCondition = CompositeCondition::not($internalAgencyBookingCondition);
foreach (['firstName', 'lastName', 'dateOfBirth'] as $field) {
$this->fieldStateConditions[$field] = ['static_text' => $corePersonalDataReadOnlyCondition];
}
@@ -92,11 +85,19 @@ class EditFieldStateProvider extends AbstractFieldStateProvider
}
// Contact fields: only the applicant (index 0) is read-only — participants can always update email/phone
foreach (['email', 'mobile'] as $field) {
$this->fieldStateConditions[$field] = [
'static_text' => $firstParticipantReadOnlyCondition,
];
}
$this->fieldStateConditions['mobile'] = [
'static_text' => $firstParticipantReadOnlyCondition,
];
// Same rule as the create flow, except that internal agency bookings leave personal
// data optional throughout.
$this->fieldStateConditions['email'] = [
'static_text' => $firstParticipantReadOnlyCondition,
'required' => CompositeCondition::and(
CompositeCondition::not($internalAgencyBookingCondition),
new RequiresOwnEmailCondition(),
),
];
// Address fields - render as static text if first participant in non-internal agency OR participant not mutable
$this->fieldStateConditions['address'] = [
+1 -1
View File
@@ -110,7 +110,7 @@ class BookingConfigurator
$selection->price = $room->price;
$selection->status = $room->status;
$selection->maxQuantity = $room->available;
$selection->capacity = $room->minPax;
$selection->capacity = $room->minPax ?? 1;
$selection->quantity = $roomsIdsAndQuantities[$room->id] ?? 0;
return $selection;
@@ -6,6 +6,7 @@ namespace App\Tests\BusProNet\XmlParser;
use App\BusProNet\XmlCrawlerFactory;
use App\BusProNet\XmlParser\TravelParser;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class TravelParserTest extends TestCase
@@ -426,4 +427,35 @@ class TravelParserTest extends TestCase
$this->assertSame('2029-12-30 18:00', $pickups[1]->time->format('Y-m-d H:i'));
$this->assertSame('2029-12-30 01:00', $pickups[2]->time->format('Y-m-d H:i'));
}
/**
* The travel export writes MinPax/MaxPax capitalized while booking responses write them lowercase.
* XmlCrawlerFactory uses addXmlContent(), which makes attribute lookups case-sensitive, so both
* spellings have to resolve.
*/
#[DataProvider('roomOccupancyAttributeProvider')]
public function testGetRoomsReadsOccupancyRegardlessOfAttributeCasing(string $attributes, ?int $expectedPax): void
{
$xml = sprintf('<?xml version="1.0" encoding="utf-8"?>
<zimmer>
<preis zimmercode="4erDW" idbuspro_zimmer="95" zimmertext="4er Zimmer Dusche/WC" %s naechte="5" idbuspro_vp="2" preis="689,00" status="Frei" verfuegbar="8" />
</zimmer>', $attributes);
$crawler = XmlCrawlerFactory::create($xml);
$rooms = $this->parser->getRooms($crawler->filterXPath('//zimmer')->first());
$this->assertArrayHasKey(95, $rooms);
$this->assertSame($expectedPax, $rooms[95]->minPax);
$this->assertSame($expectedPax, $rooms[95]->maxPax);
}
/**
* @return iterable<string, array{string, int|null}>
*/
public static function roomOccupancyAttributeProvider(): iterable
{
yield 'export casing' => ['MinPax="4" MaxPax="4"', 4];
yield 'lowercase casing' => ['minpax="4" maxpax="4"', 4];
yield 'missing stays null' => ['', null];
}
}
+56
View File
@@ -204,4 +204,60 @@ class ParticipantDtoTest extends TestCase
return $insurance;
}
public function testRequiresOwnEmailIsFalseForNonApplicantChild(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertFalse($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailIsTrueForNonApplicantAdult(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$this->assertTrue($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailIsTrueForTheApplicantEvenAsAChild(): void
{
$participant = new ParticipantDto();
$participant->index = 0;
$participant->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertTrue(
$participant->requiresOwnEmail(),
'The applicant is the booking contact and always has to be reachable'
);
}
public function testRequiresOwnEmailTreatsUnknownAgeAsAdult(): void
{
$participant = new ParticipantDto();
$participant->index = 1;
$participant->dateOfBirth = null;
$this->assertTrue($participant->requiresOwnEmail());
}
public function testRequiresOwnEmailBoundaryAtChildAgeThreshold(): void
{
$exactlyThreshold = new ParticipantDto();
$exactlyThreshold->index = 1;
$exactlyThreshold->dateOfBirth = (new \DateTimeImmutable('today'))
->modify(sprintf('-%d years', ParticipantDto::CHILD_AGE_THRESHOLD));
$oneDayShort = new ParticipantDto();
$oneDayShort->index = 1;
$oneDayShort->dateOfBirth = (new \DateTimeImmutable('today'))
->modify(sprintf('-%d years', ParticipantDto::CHILD_AGE_THRESHOLD))
->modify('+1 day');
$this->assertTrue($exactlyThreshold->requiresOwnEmail());
$this->assertFalse($oneDayShort->requiresOwnEmail());
}
}
+156
View File
@@ -30,6 +30,7 @@ use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
@@ -856,6 +857,161 @@ class ParticipantEditDtoTest extends TestCase
* available ski pass. Ski pass validation depends on the travel actually offering
* passes, so a travel without them is a distinct fixture, not the default.
*/
public function testChildWithoutEmailPassesStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createChildParticipant(''),
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
public function testChildWithNullEmailPassesStrictValidation(): void
{
$child = $this->createChildParticipant('');
$child->email = null;
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$child,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
public function testChildWithMalformedEmailStillFailsEmailFormatValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createChildParticipant('not-an-email'),
]);
$violations = $this->validator->validate(
new ParticipantEditDto(
participant: $bookingDto->participants[1],
bookingContext: $bookingDto,
),
null,
['booking_create', 'strict_required']
);
$messages = [];
foreach ($violations as $violation) {
if ('participant.email' === $violation->getPropertyPath()) {
$messages[] = $violation->getMessage();
}
}
$this->assertSame(['Bitte eine gültige E-Mail Adresse angeben'], $messages);
}
public function testAdultDependentWithoutEmailFailsStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$this->createAdultParticipant(''),
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentWithUnknownDateOfBirthAndNoEmailFailsStrictValidation(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = null;
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testApplicantChildWithoutEmailStillFailsStrictValidation(): void
{
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createChildParticipant(''),
$this->createAdultParticipant('[email protected]'),
]);
$violations = $this->validateStrict($bookingDto, 0);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentTurningExactlySixteenRequiresEmail(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = (new \DateTimeImmutable('today'))->modify('-16 years');
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame(['Bitte angeben'], $this->emailRequiredMessages($violations));
}
public function testDependentOneDayShortOfSixteenDoesNotRequireEmail(): void
{
$participant = $this->createAdultParticipant('');
$participant->dateOfBirth = (new \DateTimeImmutable('today'))->modify('-16 years')->modify('+1 day');
$bookingDto = $this->createBookingDtoWithParticipants([
$this->createAdultParticipant('[email protected]'),
$participant,
]);
$violations = $this->validateStrict($bookingDto, 1);
$this->assertSame([], $this->emailRequiredMessages($violations));
}
/**
* Validates one participant with the strict group active, as the booking create flow does.
*/
private function validateStrict(BookingDto $bookingDto, int $index): ConstraintViolationListInterface
{
return $this->validator->validate(
new ParticipantEditDto(
participant: $bookingDto->participants[$index],
bookingContext: $bookingDto,
),
null,
['booking_create', 'strict_required']
);
}
/**
* Narrows a violation list down to the "email is mandatory" messages.
*
* @return list<string>
*/
private function emailRequiredMessages(ConstraintViolationListInterface $violations): array
{
$messages = [];
foreach ($violations as $violation) {
if ('participant.email' === $violation->getPropertyPath() && 'Bitte angeben' === $violation->getMessage()) {
$messages[] = $violation->getMessage();
}
}
return $messages;
}
private function createTravelOfferingSkiPasses(?int $ageFrom = null): Travel
{
$travel = $this->createTravelWithoutSkiPasses();
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form;
use App\Form\Model\RoomSelectionDto;
use App\Form\RoomSelectType;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Forms;
class RoomSelectTypeTest extends TestCase
{
/**
* @param array<string, int> $expectedChoices
*/
#[DataProvider('quantityChoiceProvider')]
public function testQuantityChoicesFollowAvailability(int $maxQuantity, array $expectedChoices): void
{
$data = new RoomSelectionDto();
$data->id = 95;
$data->maxQuantity = $maxQuantity;
$form = Forms::createFormFactory()->create(RoomSelectType::class, $data);
$this->assertSame($expectedChoices, $form->get('quantity')->getConfig()->getOption('choices'));
}
/**
* @return iterable<string, array{int, array<string, int>}>
*/
public static function quantityChoiceProvider(): iterable
{
yield 'available rooms are selectable' => [2, ['-' => 0, '1' => 1, '2' => 2]];
// range(1, 0) would return [1, 0], offering a bookable "1" for a room with no availability.
yield 'no availability offers only the placeholder' => [0, ['-' => 0]];
}
}
@@ -73,4 +73,95 @@ class CreateFieldStateProviderTest extends TestCase
'Dependent insurance field must reappear once the applicant switches away from family insurance'
);
}
public function testEmailIsNotRequiredForNonApplicantChild(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$this->assertFalse(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'A child travelling with an applicant does not need an email address of their own'
);
}
public function testEmailIsRequiredForNonApplicantAdult(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('1990-01-01'));
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsRequiredForTheApplicantEvenAsAChild(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$bookingDto->participants[0]->dateOfBirth = new \DateTimeImmutable('2015-01-01');
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 0)['required'],
'The applicant is the booking contact and always has to be reachable'
);
}
public function testEmailIsRequiredWhenDateOfBirthIsUnknown(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$bookingDto->participants[1]->dateOfBirth = null;
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'An unknown age counts as an adult'
);
}
public function testEmailRequirementFlipsWhenDateOfBirthChanges(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('2015-01-01'));
$dependent = $bookingDto->participants[1];
$this->assertFalse($this->provider->getFieldState('email', $bookingDto, 1)['required']);
$dependent->dateOfBirth = new \DateTimeImmutable('1990-01-01');
$this->assertTrue(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'Correcting a child date of birth to an adult one must reinstate the requirement'
);
}
/**
* Guards the switch from add-only to toggling 'required' state: the two fields that already
* used a 'required' condition must keep behaving exactly as before, now reporting false
* instead of omitting the key. Both declare 'required' => false as their base in the form
* type, so assigning the condition result either way is equivalent to the old add-only pass.
*/
public function testMobileAndAddressRemainRequiredOnlyForTheFirstParticipant(): void
{
$bookingDto = $this->createBookingDtoWithApplicantAndDependent(new \DateTimeImmutable('1990-01-01'));
$this->assertTrue($this->provider->getFieldState('mobile', $bookingDto, 0)['required']);
$this->assertFalse($this->provider->getFieldState('mobile', $bookingDto, 1)['required']);
$this->assertTrue($this->provider->getFieldState('address', $bookingDto, 0)['required']);
$this->assertFalse($this->provider->getFieldState('address', $bookingDto, 1)['required']);
}
private function createBookingDtoWithApplicantAndDependent(\DateTimeImmutable $dependentDateOfBirth): BookingDto
{
$travel = new Travel();
$travel->dateFrom = new \DateTimeImmutable('+30 days');
$travel->dateTo = new \DateTimeImmutable('+37 days');
$applicant = new ParticipantDto();
$applicant->index = 0;
$applicant->dateOfBirth = new \DateTimeImmutable('1980-01-01');
$dependent = new ParticipantDto();
$dependent->index = 1;
$dependent->dateOfBirth = $dependentDateOfBirth;
$bookingDto = new BookingDto($travel, 1);
$bookingDto->participants = [$applicant, $dependent];
return $bookingDto;
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Service;
use App\BusProNet\Model\Travel;
use App\BusProNet\XmlLoader\AgencyLoader;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Form\Service\EditFieldStateProvider;
use PHPUnit\Framework\TestCase;
/**
* Covers the edit-flow email requirement, which follows the same age rule as the create flow
* but stands down entirely for internal agency bookings, where staff leave personal data blank.
*/
class EditFieldStateProviderTest extends TestCase
{
private EditFieldStateProvider $provider;
protected function setUp(): void
{
$this->provider = new EditFieldStateProvider();
}
public function testEmailIsRequiredForNonApplicantAdult(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), false);
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsNotRequiredForNonApplicantChild(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('2015-01-01'), false);
$this->assertFalse($this->provider->getFieldState('email', $bookingDto, 1)['required']);
}
public function testEmailIsNotRequiredForInternalAgencyBookingsEvenForAdults(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), true);
$this->assertFalse(
$this->provider->getFieldState('email', $bookingDto, 1)['required'],
'Internal agency bookings leave personal data optional throughout'
);
}
public function testEmailIsRequiredForTheApplicantOutsideInternalAgencyBookings(): void
{
$bookingDto = $this->createBookingDto(new \DateTimeImmutable('1990-01-01'), false);
$this->assertTrue($this->provider->getFieldState('email', $bookingDto, 0)['required']);
}
private function createBookingDto(\DateTimeImmutable $dependentDateOfBirth, bool $internalAgency): BookingDto
{
$travel = new Travel();
$travel->dateFrom = new \DateTimeImmutable('+30 days');
$travel->dateTo = new \DateTimeImmutable('+37 days');
$applicant = new ParticipantDto();
$applicant->index = 0;
$applicant->dateOfBirth = new \DateTimeImmutable('1980-01-01');
$dependent = new ParticipantDto();
$dependent->index = 1;
$dependent->dateOfBirth = $dependentDateOfBirth;
$bookingDto = new BookingDto($travel, 1);
$bookingDto->participants = [$applicant, $dependent];
if (true === $internalAgency) {
$bookingDto->agencyCode = AgencyLoader::INTERNAL_AGENCY_CODE;
}
return $bookingDto;
}
}
+18 -1
View File
@@ -70,6 +70,23 @@ class BookingSummaryAssemblerTest extends TestCase
$this->assertSame(2, $summary->participantCount);
}
public function testCreateStep1CountsRoomsWithUnknownOccupancyAsZero(): void
{
$service = $this->createService();
$bookingDto = $this->createBookingDto();
$bookingDto->travel->rooms[12] = $this->createRoom(12, null);
$bookingDto->currentStep = 1;
$bookingDto->roomSelections = [
$this->createRoomSelection(10, 1),
$this->createRoomSelection(12, 2),
];
$summary = $service->getSummaryData($bookingDto);
// 1×2 for the known room; the room without occupancy contributes nothing.
$this->assertSame(2, $summary->participantCount);
}
private function createService(): BookingSummaryAssembler
{
$priceCalculator = $this->createStub(BookingPriceCalculator::class);
@@ -107,7 +124,7 @@ class BookingSummaryAssemblerTest extends TestCase
return new BookingDto($travel, 157047);
}
private function createRoom(int $id, int $maxPax): Room
private function createRoom(int $id, ?int $maxPax): Room
{
$room = new Room();
$room->id = $id;
+26
View File
@@ -272,6 +272,32 @@ class RoomAssignerTest extends TestCase
self::assertNull($bookingDto->participants[1]->assignedRoomId);
}
#[Test]
public function assignParticipantsToRoomsFallsBackToOneBedWhenOccupancyIsUnknown(): void
{
$bookingDto = $this->createBookingDtoWithRoomSelections([
['roomId' => 100, 'quantity' => 2, 'capacity' => 1],
]);
$bookingDto->participants = [
new ParticipantDto(),
new ParticipantDto(),
];
$room = new Room();
$room->id = 100;
$room->minPax = null;
$room->available = 10;
$room->status = Constants::STATUS_AVAILABLE;
$bookingDto->travel->rooms = [$room];
$this->service->assignParticipantsToRooms($bookingDto);
self::assertSame(100, $bookingDto->participants[0]->assignedRoomId);
self::assertSame(100, $bookingDto->participants[1]->assignedRoomId);
}
private function createBookingDtoWithRoomSelections(array $selections): BookingDto
{
$travel = new Travel();
@@ -247,6 +247,31 @@ class RoomPricingCalculatorTest extends TestCase
$this->assertEquals(458.0, $result[0]['totalPrice']);
}
public function testCalculateRoomPricingFallsBackToOneParticipantWhenOccupancyIsUnknown(): void
{
$room = new Room();
$room->id = 4;
$room->price = 419.0;
$room->minPax = null;
$room->label = 'Bett im Mehrbettzimmer';
$travel = new Travel();
$travel->rooms = [$room];
$roomSelection = new RoomSelectionDto();
$roomSelection->id = 4;
$roomSelection->quantity = 2;
$bookingDto = new BookingDto($travel, 1);
$bookingDto->roomSelections = [$roomSelection];
$result = $this->calculator->calculateRoomPricing($bookingDto, RoomPricingCalculator::PRICING_MODE_SELECTION);
$this->assertCount(1, $result);
$this->assertEquals(2, $result[0]['participantCount']);
$this->assertEquals(838.0, $result[0]['totalPrice']);
}
public function testCalculateRoomPricingInEditModeUsesStoredIndividualPrices(): void
{
$travel = new Travel();