feat: groups price calculator admin crud, booking/offer flow and api

This commit is contained in:
Björn Fromme
2026-08-03 15:25:10 +02:00
parent eabed8295a
commit 9d2aa11fdb
258 changed files with 16231 additions and 582 deletions
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace App\Tests\BusProNet\XmlParser;
use App\BusProNet\XmlParser\CrmAttributesResponseParser;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DomCrawler\Crawler;
class CrmAttributesResponseParserTest extends TestCase
{
private CrmAttributesResponseParser $parser;
protected function setUp(): void
{
$this->parser = new CrmAttributesResponseParser();
}
public function testParseAssignsGroupsManagerRoleWhenSelected(): void
{
$roles = $this->parseRoles($this->selectionXml(1477, true));
self::assertContains('ROLE_GROUPS_MANAGER', $roles);
self::assertNotContains('ROLE_GROUPS_ADMIN', $roles);
}
public function testParseAssignsGroupsAdminRoleWhenSelected(): void
{
$roles = $this->parseRoles($this->selectionXml(1478, true));
self::assertContains('ROLE_GROUPS_ADMIN', $roles);
self::assertNotContains('ROLE_GROUPS_MANAGER', $roles);
}
public function testParseAssignsNoGroupsRolesWhenNotSelected(): void
{
$roles = $this->parseRoles($this->selectionXml(1477, false));
self::assertNotContains('ROLE_GROUPS_MANAGER', $roles);
self::assertNotContains('ROLE_GROUPS_ADMIN', $roles);
self::assertSame(['ROLE_CUSTOMER'], $roles);
}
public function testParseStillAssignsExistingAdminManagerTeamerRoles(): void
{
$xmlContent = '<?xml version="1.0" encoding="utf-8"?>
<ergebnis>
<satz typ="KUNDENDATEN" />
<selektionsmerkmale>
<selektionsgruppe id="1" bezeichnung="Rollen">
<selektion id="1292" bezeichnung="Admin" aenderbar="0" auswahl="True" />
<selektion id="1293" bezeichnung="Manager" aenderbar="0" auswahl="True" />
<selektion id="1070" bezeichnung="Teamer" aenderbar="0" auswahl="True" />
</selektionsgruppe>
</selektionsmerkmale>
<crmaktionen></crmaktionen>
</ergebnis>';
$roles = $this->parseRoles($xmlContent);
self::assertContains('ROLE_ADMIN', $roles);
self::assertContains('ROLE_MANAGER', $roles);
self::assertContains('ROLE_TEAMER', $roles);
self::assertContains('ROLE_HOUSE_MANAGER', $roles);
}
/**
* @return string[]
*/
private function parseRoles(string $xmlContent): array
{
$crawler = new Crawler($xmlContent);
$resultNode = $crawler->filterXPath('//ergebnis');
return $this->parser->parse($resultNode)->roles;
}
private function selectionXml(int $id, bool $selected): string
{
return sprintf('<?xml version="1.0" encoding="utf-8"?>
<ergebnis>
<satz typ="KUNDENDATEN" />
<selektionsmerkmale>
<selektionsgruppe id="1" bezeichnung="Rollen">
<selektion id="%d" bezeichnung="Gruppenreisen" aenderbar="0" auswahl="%s" />
</selektionsgruppe>
</selektionsmerkmale>
<crmaktionen></crmaktionen>
</ergebnis>', $id, $selected ? 'True' : 'False');
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Accommodation;
use App\Controller\Groups\IndexController;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class IndexControllerTest extends TestCase
{
public function testSuccessRendersAndConsumesFlashOnFirstLoad(): void
{
$session = new Session(new MockArraySessionStorage());
$session->getFlashBag()->add('groups_booking_result', 'booking');
$request = Request::create('/groups/booking/success', 'GET');
$request->setSession($session);
$controller = $this->makeController();
$response = $controller->success($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/success.html.twig', $controller->renderedView);
self::assertSame('booking', $controller->renderedParameters['resultType']);
// The flash is read-once: a second read on the same request returns nothing.
self::assertSame([], $session->getFlashBag()->get('groups_booking_result'));
}
public function testSuccessRedirectsToLoginWhenFlashIsMissing(): void
{
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/success', 'GET');
$request->setSession($session);
$controller = $this->makeController();
$response = $controller->success($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_login', $response->headers->get('Location'));
}
private function makeController(): TestableAccommodationIndexController
{
return new TestableAccommodationIndexController(
$this->createMock(AccommodationBookingService::class),
$this->createMock(AccommodationSessionManager::class),
);
}
}
final class TestableAccommodationIndexController extends IndexController
{
/**
* @var array<string, mixed>
*/
public array $renderedParameters = [];
public string $renderedView = '';
/**
* @param array<string, mixed> $parameters
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return new RedirectResponse('/'.$route, $status);
}
/**
* @param array<string, mixed> $parameters
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
$this->renderedView = $view;
$this->renderedParameters = $parameters;
return new Response('ok');
}
}
@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Accommodation;
use App\BpnConnect\ContingentsClient;
use App\Controller\Groups\Step1Controller;
use App\Entity\Groups\Accommodation;
use App\Form\Model\AccommodationBookingDto;
use App\Repository\Groups\AccommodationPriceRepository;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use App\Service\CalendarGridBuilder;
use App\Service\GroupsPriceCalculator;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Contracts\Cache\CacheInterface;
class Step1ControllerTest extends TestCase
{
public function testPostWithValidDatesUpdatesSessionAndRedirects(): void
{
$dto = new AccommodationBookingDto();
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-1', 'POST', [
'date_from' => '2026-08-03',
'date_to' => '2026-08-07',
]);
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService
->method('applyDates')
->willReturnCallback(static function (AccommodationBookingDto $dto): void {
$dto->dateFrom = new \DateTimeImmutable('2026-08-03');
$dto->dateTo = new \DateTimeImmutable('2026-08-07');
});
$bookingService
->method('loadAccommodation')
->with(1)
->willReturn($accommodation);
$bookingService
->method('computeInitialPaxCount')
->willReturn(4);
$controller = $this->makeController($bookingService, $sessionManager);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_step_2', $response->headers->get('Location'));
$savedDto = $sessionManager->getOrFail($request);
self::assertSame(2, $savedDto->currentStep);
self::assertSame(4, $savedDto->paxCount);
self::assertNull($savedDto->selectedBoardServiceId);
self::assertSame([], $savedDto->selectedAdditionalServiceIds);
}
public function testPostWithInvalidDatesRedirectsBackWithFlash(): void
{
$dto = new AccommodationBookingDto();
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-1', 'POST', [
'date_from' => 'not-a-date',
'date_to' => '2026-08-07',
]);
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService
->method('applyDates')
->willThrowException(new \InvalidArgumentException('Ungültiges Datumsformat. Erwartet: YYYY-MM-DD.'));
$controller = $this->makeController($bookingService, $sessionManager);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_step_1', $response->headers->get('Location'));
}
private function makeController(
AccommodationBookingService $bookingService,
AccommodationSessionManager $sessionManager,
): TestableAccommodationStep1Controller {
return new TestableAccommodationStep1Controller(
$bookingService,
$sessionManager,
$this->createMock(ContingentsClient::class),
$this->createMock(AccommodationPriceRepository::class),
new PriceTimelineBuilder(),
$this->createMock(CacheInterface::class),
new CalendarGridBuilder(),
new GroupsPriceCalculator(new PriceTimelineBuilder(), ['runningCostsEur' => 0, 'runningCostsChf' => 0, 'undersubscription30Eur' => 0, 'undersubscription30Chf' => 0, 'undersubscription40Eur' => 0, 'undersubscription40Chf' => 0]),
);
}
}
final class TestableAccommodationStep1Controller extends Step1Controller
{
public function __construct(
AccommodationBookingService $bookingService,
AccommodationSessionManager $sessionManager,
ContingentsClient $contingentsClient,
AccommodationPriceRepository $priceRepository,
PriceTimelineBuilder $priceTimelineBuilder,
CacheInterface $cache,
CalendarGridBuilder $calendarGridBuilder,
GroupsPriceCalculator $priceCalculator,
) {
parent::__construct(
$bookingService,
$sessionManager,
$contingentsClient,
$priceRepository,
$priceTimelineBuilder,
$cache,
$calendarGridBuilder,
$priceCalculator,
);
}
/**
* @param array<string, mixed> $parameters
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return new RedirectResponse('/'.$route, $status);
}
/**
* @param array<string, mixed> $parameters
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
throw new \LogicException('Render should not be called in this test.');
}
protected function addFlash(string $type, mixed $message): void
{
}
}
@@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Accommodation;
use App\Controller\Groups\Step2Controller;
use App\Entity\Groups\Accommodation;
use App\Form\Model\AccommodationBookingDto;
use App\Model\InquiryStatus;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use App\Service\GroupsPriceCalculator;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class Step2ControllerTest extends TestCase
{
public function testSubmitRecomputesBookingModeAfterFormBinding(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 2;
$dto->accommodationId = 1;
$dto->dateFrom = new \DateTimeImmutable('2026-03-01');
$dto->dateTo = new \DateTimeImmutable('2026-03-05');
$dto->paxCount = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-2', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$form = $this->createMock(FormInterface::class);
$form
->method('handleRequest')
->willReturnCallback(function () use ($dto, $form): FormInterface {
$dto->paxCount = 3;
return $form;
});
$form
->method('isSubmitted')
->willReturn(true);
$form
->method('isValid')
->willReturn(true);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService
->method('loadAccommodation')
->with(1)
->willReturn($accommodation);
$bookingService
->method('loadPrices')
->with($dto, $accommodation)
->willReturn([]);
$bookingService
->method('loadAvailableServices')
->with($dto, $accommodation)
->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$bookingService
->expects(self::once())
->method('computeInquiryStatus')
->with(self::callback(static fn (AccommodationBookingDto $submittedDto): bool => 3 === $submittedDto->paxCount), [])
->willReturn(new InquiryStatus(true, ['Mindestaufenthalt: 5 Nächte (gebucht: 4)']));
$controller = new TestableAccommodationStep2Controller(
$bookingService,
$sessionManager,
new GroupsPriceCalculator(new PriceTimelineBuilder(), ['runningCostsEur' => 0, 'runningCostsChf' => 0, 'undersubscription30Eur' => 0, 'undersubscription30Chf' => 0, 'undersubscription40Eur' => 0, 'undersubscription40Chf' => 0]),
$form,
);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/groups/booking/step-3', $response->headers->get('Location'));
self::assertTrue($sessionManager->getOrFail($request)->isInquiry);
}
}
final class TestableAccommodationStep2Controller extends Step2Controller
{
/**
* @param FormInterface<mixed> $form
*/
public function __construct(
AccommodationBookingService $bookingService,
AccommodationSessionManager $sessionManager,
GroupsPriceCalculator $priceCalculator,
private readonly FormInterface $form,
) {
parent::__construct($bookingService, $sessionManager, $priceCalculator);
}
/**
* @return FormInterface<mixed>
*/
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
return $this->form;
}
/**
* @param array<string, mixed> $parameters
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return new RedirectResponse('/groups/booking/step-3', $status);
}
/**
* @param array<string, mixed> $parameters
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
throw new \LogicException('Render should not be called in this test.');
}
}
@@ -0,0 +1,224 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Accommodation;
use App\Controller\Groups\Step3Controller;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AdditionalService;
use App\Entity\Groups\BoardService;
use App\Form\Model\AccommodationBookingDto;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class Step3ControllerTest extends TestCase
{
public function testSummaryReceivesSelectedServiceCatalogs(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 3;
$dto->accommodationId = 1;
$dto->dateFrom = new \DateTimeImmutable('2026-03-01');
$dto->dateTo = new \DateTimeImmutable('2026-03-05');
$dto->selectedBoardServiceId = 10;
$dto->selectedAdditionalServiceIds = [20];
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-3', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$form = $this->createFormMock(submitted: false, valid: false);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$boardService = (new BoardService())->setLabel('Halbpension')->setPrice(1000);
$additionalService = (new AdditionalService())->setLabel('Skipass')->setPrice(2000);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService
->method('loadAccommodation')
->with(1)
->willReturn($accommodation);
$bookingService
->expects(self::once())
->method('loadAvailableServices')
->with($dto, $accommodation)
->willReturn([
'boardServices' => [$boardService],
'additionalServices' => [$additionalService],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [$additionalService],
]);
$controller = new TestableAccommodationStep3Controller($bookingService, $sessionManager, $form);
$response = $controller->index($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/step_3.html.twig', $controller->renderedView);
self::assertSame([$boardService], $controller->renderedParameters['ctx']->boardServices);
self::assertSame([$additionalService], $controller->renderedParameters['ctx']->additionalServices);
}
public function testValidSubmitRedirectsToStep4WithoutPersisting(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 3;
$dto->accommodationId = 1;
$dto->isInquiry = false;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-3', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$form = $this->createFormMock(submitted: true, valid: true);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$bookingService->expects(self::never())->method('finalizeBooking');
$controller = new TestableAccommodationStep3Controller($bookingService, $sessionManager, $form);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_step_4', $response->getTargetUrl());
self::assertSame(4, $dto->currentStep);
self::assertSame($dto, $sessionManager->getDto($request));
}
public function testInvalidSubmitReRendersFormWithErrors(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 3;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-3', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$form = $this->createFormMock(submitted: true, valid: false);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$controller = new TestableAccommodationStep3Controller($bookingService, $sessionManager, $form);
$response = $controller->index($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/step_3.html.twig', $controller->renderedView);
self::assertSame(3, $dto->currentStep);
self::assertSame($dto, $sessionManager->getDto($request));
}
private function createFormMock(bool $submitted, bool $valid): FormInterface
{
$form = $this->createMock(FormInterface::class);
$form->method('handleRequest')->willReturnSelf();
$form->method('isSubmitted')->willReturn($submitted);
$form->method('isValid')->willReturn($valid);
return $form;
}
}
final class TestableAccommodationStep3Controller extends Step3Controller
{
/**
* @var array<string, mixed>
*/
public array $renderedParameters = [];
public string $renderedView = '';
public function __construct(
AccommodationBookingService $bookingService,
AccommodationSessionManager $sessionManager,
private readonly FormInterface $form,
) {
parent::__construct($bookingService, $sessionManager);
}
/**
* @return FormInterface<mixed>
*/
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
return $this->form;
}
/**
* @param array<string, mixed> $parameters
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return new RedirectResponse('/'.$route, $status);
}
/**
* @param array<string, mixed> $parameters
*/
protected function generateUrl(string $route, array $parameters = [], int $referenceType = 1): string
{
return '/'.$route;
}
protected function addFlash(string $type, mixed $message): void
{
// no-op: avoids requiring a full service container in these unit tests
}
/**
* @param array<string, mixed> $parameters
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
$this->renderedView = $view;
$this->renderedParameters = $parameters;
return new Response('ok');
}
}
@@ -0,0 +1,304 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Api;
use App\Controller\Api\AccommodationBookingController;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Repository\Groups\AccommodationBookingRepository;
use App\Service\AccommodationBookingBreakdownCalculator;
use App\Service\AccommodationBookingService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
class AccommodationBookingControllerTest extends TestCase
{
public function testSingleReturnsBookingDataForKnownUuid(): void
{
$accommodation = new Accommodation();
$accommodation->setName('Berghotel');
$accommodation->setCalendarCode('CAL123');
$accommodation->setCmsCode('CMS456');
$accommodation->setMaxAdolescentAge(15);
$accommodation->setCurrency('EUR');
$booking = new AccommodationBooking();
$booking->setAccommodation($accommodation);
$booking->setDateFrom(new \DateTimeImmutable('2026-07-20'));
$booking->setDateTo(new \DateTimeImmutable('2026-07-25'));
$booking->setPaxCount(40);
$booking->setMinorsCount(2);
$booking->setChildrenCount(1);
$booking->setGroupName('Schulklasse 7b');
$booking->setSalutation('Frau');
$booking->setFirstName('Mia');
$booking->setLastName('Muster');
$booking->setEmail('[email protected]');
$booking->setPhone('+49123456789');
$booking->setStreet('Musterstr. 1');
$booking->setZip('12345');
$booking->setCity('Musterstadt');
$booking->setRemarks('Bitte am Bahnhof abholen');
$booking->setBoardServiceLabel('Halbpension');
$booking->setBoardServicePrice(1500);
$booking->addAdditionalServiceSnapshot('Bettwäsche', 500, 'flat', 3);
$booking->setAccommodationDiscount(10);
$booking->setBoardServiceDiscount(20);
$booking->setAdditionalServicesDiscount(30);
$booking->setIsInquiry(false);
$booking->setAcceptedAt(new \DateTimeImmutable('2026-07-15T10:00:00+00:00'));
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->expects(self::once())
->method('findOneBy')
->with(['uuid' => $booking->getUuid()])
->willReturn($booking);
$breakdown = ['total' => 12345, 'currency' => 'EUR'];
$booking->setPriceSnapshot($breakdown, 11111, 'EUR', 1);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator
->expects(self::once())
->method('compute')
->with($booking)
->willReturn($breakdown);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::never())->method('acceptBooking');
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $bookingService);
$response = $controller->single($booking->getUuid());
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame([
'uuid' => $booking->getUuid(),
'status' => 'booking',
'dateFrom' => '2026-07-20',
'dateTo' => '2026-07-25',
'nights' => 5,
'paxCount' => 40,
'minorsCount' => 2,
'childrenCount' => 1,
'groupName' => 'Schulklasse 7b',
'acceptedAt' => '2026-07-15T10:00:00+00:00',
'personalData' => [
'salutation' => 'Frau',
'firstName' => 'Mia',
'lastName' => 'Muster',
'email' => '[email protected]',
'phone' => '+49123456789',
'street' => 'Musterstr. 1',
'zip' => '12345',
'city' => 'Musterstadt',
'remarks' => 'Bitte am Bahnhof abholen',
],
'accommodation' => [
'calendarCode' => 'CAL123',
'cmsCode' => 'CMS456',
],
'boardService' => [
'label' => 'Halbpension',
'price' => 1500,
],
'additionalServices' => [
[
'label' => 'Bettwäsche',
'price' => 500,
'type' => 'flat',
],
],
'accommodationDiscount' => 10,
'boardServiceDiscount' => 20,
'additionalServicesDiscount' => 30,
'totalPrice' => 11111,
'pricingCurrency' => 'EUR',
'pricingVersion' => 1,
'priceBreakdown' => $breakdown,
], $payload);
// CMS-only accommodation fields must not leak into the response.
self::assertArrayNotHasKey('name', $payload['accommodation']);
self::assertArrayNotHasKey('maxAdolescentAge', $payload['accommodation']);
self::assertArrayNotHasKey('currency', $payload['accommodation']);
}
public function testSingleReturnsInquiryStatusWhenBookingIsInquiry(): void
{
$booking = new AccommodationBooking();
$booking->setDateFrom(new \DateTimeImmutable('2026-08-01'));
$booking->setDateTo(new \DateTimeImmutable('2026-08-02'));
$booking->setGroupName('Verein e.V.');
$booking->setFirstName('Tom');
$booking->setLastName('Beispiel');
$booking->setEmail('[email protected]');
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->method('findOneBy')
->with(['uuid' => $booking->getUuid()])
->willReturn($booking);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $this->createMock(AccommodationBookingService::class));
$response = $controller->single($booking->getUuid());
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame('inquiry', $payload['status']);
self::assertNull($payload['priceBreakdown']);
self::assertNull($payload['acceptedAt']);
}
public function testSingleReturnsNotFoundForUnknownUuid(): void
{
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->expects(self::once())
->method('findOneBy')
->with(['uuid' => 'unknown-uuid'])
->willReturn(null);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->expects(self::never())->method('compute');
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $this->createMock(AccommodationBookingService::class));
$response = $controller->single('unknown-uuid');
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame(Response::HTTP_NOT_FOUND, $response->getStatusCode());
self::assertSame(['message' => 'Not found'], $payload);
}
public function testAcceptTransitionsInquiryToBookingAndSetsAcceptedAt(): void
{
$booking = new AccommodationBooking();
$booking->setDateFrom(new \DateTimeImmutable('2026-08-01'));
$booking->setDateTo(new \DateTimeImmutable('2026-08-02'));
$booking->setGroupName('Verein e.V.');
$booking->setFirstName('Tom');
$booking->setLastName('Beispiel');
$booking->setEmail('[email protected]');
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->expects(self::once())
->method('findOneBy')
->with(['uuid' => $booking->getUuid()])
->willReturn($booking);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService
->expects(self::once())
->method('acceptBooking')
->with($booking)
->willReturnCallback(static function (AccommodationBooking $b): void {
$b->setIsInquiry(false);
$b->setAcceptedAt(new \DateTimeImmutable());
});
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $bookingService);
$response = $controller->accept($booking->getUuid());
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('booking', $payload['status']);
self::assertFalse($booking->isInquiry());
self::assertNotNull($booking->getAcceptedAt());
self::assertSame($booking->getAcceptedAt()->format(\DATE_ATOM), $payload['acceptedAt']);
}
public function testAcceptIsIdempotentWhenBookingAlreadyAccepted(): void
{
$acceptedAt = new \DateTimeImmutable('2026-07-15T10:00:00+00:00');
$booking = new AccommodationBooking();
$booking->setDateFrom(new \DateTimeImmutable('2026-08-01'));
$booking->setDateTo(new \DateTimeImmutable('2026-08-02'));
$booking->setGroupName('Verein e.V.');
$booking->setFirstName('Tom');
$booking->setLastName('Beispiel');
$booking->setEmail('[email protected]');
$booking->setIsInquiry(false);
$booking->setAcceptedAt($acceptedAt);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->method('findOneBy')
->with(['uuid' => $booking->getUuid()])
->willReturn($booking);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::once())->method('acceptBooking')->with($booking);
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $bookingService);
$response = $controller->accept($booking->getUuid());
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('booking', $payload['status']);
self::assertSame($acceptedAt, $booking->getAcceptedAt());
self::assertSame($acceptedAt->format(\DATE_ATOM), $payload['acceptedAt']);
}
public function testAcceptReturnsNotFoundForUnknownUuid(): void
{
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository
->expects(self::once())
->method('findOneBy')
->with(['uuid' => 'unknown-uuid'])
->willReturn(null);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->expects(self::never())->method('compute');
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::never())->method('acceptBooking');
$controller = new AccommodationBookingController($bookingRepository, $breakdownCalculator, $this->serializer(), $bookingService);
$response = $controller->accept('unknown-uuid');
$payload = json_decode((string) $response->getContent(), true, 512, JSON_THROW_ON_ERROR);
self::assertSame(Response::HTTP_NOT_FOUND, $response->getStatusCode());
self::assertSame(['message' => 'Not found'], $payload);
}
private function serializer(): Serializer
{
$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());
return new Serializer(
[
new DateTimeNormalizer(),
new ObjectNormalizer($classMetadataFactory, propertyTypeExtractor: new ReflectionExtractor()),
],
[new JsonEncoder()],
);
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Api;
use App\BpnConnect\ContingentsClient;
use App\Controller\Api\ContingentController;
use App\Entity\Groups\AccommodationPrice;
use App\Repository\Groups\AccommodationPriceRepository;
use App\Repository\Groups\AccommodationRepository;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\Cache\CacheInterface;
class ContingentControllerTest extends TestCase
{
public function testEnrichEntryIncludesPricingMetadata(): void
{
$controller = new ContingentController(
$this->createMock(ContingentsClient::class),
$this->createMock(AccommodationRepository::class),
$this->createMock(AccommodationPriceRepository::class),
$this->createMock(CacheInterface::class),
new PriceTimelineBuilder(),
);
$price = new AccommodationPrice();
$price->setDateFrom(new \DateTimeImmutable('2026-07-01'));
$price->setDateTo(new \DateTimeImmutable('2026-07-31'));
$price->setIncludedPax(4);
$price->setPricePerNight(12345);
$price->setPriceAdditionalPerson(1500);
$price->setMinNights(3);
$method = new \ReflectionMethod($controller, 'enrichEntry');
$result = $method->invoke($controller, '2026-07-06', 'available', [$price], 'EUR');
self::assertSame(4, $result['includedPax']);
self::assertSame(3, $result['minNights']);
self::assertSame(123.45, $result['pricePerNight']);
self::assertSame('EUR', $result['currency']);
}
}
@@ -0,0 +1,411 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Groups;
use App\Controller\Groups\OfferController;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Repository\Groups\AccommodationBookingRepository;
use App\Service\AccommodationBookingBreakdownCalculator;
use App\Service\AccommodationBookingLinkSigner;
use App\Service\AccommodationBookingService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class OfferControllerTest extends TestCase
{
public function testAccessAuthorizesSessionAndRedirectsToView(): void
{
$booking = new AccommodationBooking();
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->with(['uuid' => $booking->getUuid()])->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isValidLinkRequest')->willReturn(true);
$linkSigner->expects(self::once())->method('authorizeSession')->with(self::anything(), $booking);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->access($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid()));
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_offer_view?uuid='.$booking->getUuid(), $response->getTargetUrl());
}
public function testAccessRendersUnavailableForInvalidLink(): void
{
$booking = new AccommodationBooking();
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isValidLinkRequest')->willReturn(false);
$linkSigner->expects(self::never())->method('authorizeSession');
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->access($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid()));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('groups/booking/offer_unavailable.html.twig', $controller->renderedView);
}
public function testAccessRendersUnavailableForUnknownUuid(): void
{
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn(null);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->expects(self::never())->method('isValidLinkRequest');
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->access('unknown-uuid', Request::create('/groups/booking/offer/unknown-uuid'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('groups/booking/offer_unavailable.html.twig', $controller->renderedView);
}
public function testViewRendersOfferWhenSessionAuthorized(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$booking->setAccommodation(new Accommodation());
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->with(['uuid' => $booking->getUuid()])->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->with($booking)->willReturn(['total' => 1000]);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::never())->method('acceptBooking');
$bookingService->method('loadHotelCmsData')->willReturn(null);
$controller = new TestableOfferController($bookingRepository, $linkSigner, $breakdownCalculator, $bookingService);
$request = Request::create('/groups/booking/offer/'.$booking->getUuid().'/view');
$request->setSession(new Session(new MockArraySessionStorage()));
$response = $controller->view($booking->getUuid(), $request);
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('<html>offer</html>', $response->getContent());
self::assertSame('groups/booking/offer.html.twig', $controller->renderedView);
self::assertSame($booking, $controller->renderedParameters['booking']);
self::assertSame(['total' => 1000], $controller->renderedParameters['priceBreakdown']);
self::assertSame($booking->getAccommodation(), $controller->renderedParameters['ctx']->accommodation);
}
public function testViewRendersUnavailableWhenSessionNotAuthorized(): void
{
$booking = new AccommodationBooking();
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(false);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->view($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid().'/view'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('groups/booking/offer_unavailable.html.twig', $controller->renderedView);
}
public function testConfirmGetRendersModalWithFreshForm(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->with(['uuid' => $booking->getUuid()])->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(false);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
$confirmationForm,
);
$response = $controller->confirm($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertSame('groups/booking/_offer_accept_confirmation_modal.html.twig', $controller->renderedView);
self::assertSame($booking, $controller->renderedParameters['booking']);
self::assertSame($confirmationForm, $controller->renderedParameters['confirmationForm']);
}
public function testConfirmPostValidAcceptsBookingAndRedirects(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::once())->method('acceptBooking')->with($booking);
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(true);
$confirmationForm->method('isValid')->willReturn(true);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$bookingService,
$confirmationForm,
);
$request = Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm', 'POST');
$response = $controller->confirm($booking->getUuid(), $request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_offer_view?uuid='.$booking->getUuid(), $response->getTargetUrl());
self::assertSame([['type' => 'success', 'message' => 'Deine Buchung ist bestätigt.']], $controller->flashes);
}
public function testConfirmPostValidViaHtmxReturnsHxRedirect(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::once())->method('acceptBooking')->with($booking);
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(true);
$confirmationForm->method('isValid')->willReturn(true);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$bookingService,
$confirmationForm,
);
$request = Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm', 'POST');
$request->headers->set('HX-Request', 'true');
$response = $controller->confirm($booking->getUuid(), $request);
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertTrue($response->headers->has('HX-Redirect'));
}
public function testConfirmPostInvalidReRendersModalWithoutAccepting(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->expects(self::never())->method('acceptBooking');
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(true);
$confirmationForm->method('isValid')->willReturn(false);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$bookingService,
$confirmationForm,
);
$response = $controller->confirm($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm', 'POST'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertFalse($response->headers->has('HX-Redirect'));
self::assertSame('groups/booking/_offer_accept_confirmation_modal.html.twig', $controller->renderedView);
}
public function testConfirmRedirectsWhenAlreadyAccepted(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(false);
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(true);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->confirm($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm'));
self::assertInstanceOf(RedirectResponse::class, $response);
}
public function testConfirmRedirectsWhenSessionNotAuthorized(): void
{
$booking = new AccommodationBooking();
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn($booking);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('isSessionAuthorized')->willReturn(false);
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->confirm($booking->getUuid(), Request::create('/groups/booking/offer/'.$booking->getUuid().'/confirm'));
self::assertInstanceOf(RedirectResponse::class, $response);
}
public function testConfirmRedirectsForUnknownUuid(): void
{
$bookingRepository = $this->createMock(AccommodationBookingRepository::class);
$bookingRepository->method('findOneBy')->willReturn(null);
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->expects(self::never())->method('isSessionAuthorized');
$controller = new TestableOfferController(
$bookingRepository,
$linkSigner,
$this->createMock(AccommodationBookingBreakdownCalculator::class),
$this->createMock(AccommodationBookingService::class),
);
$response = $controller->confirm('unknown-uuid', Request::create('/groups/booking/offer/unknown-uuid/confirm'));
self::assertInstanceOf(RedirectResponse::class, $response);
}
}
final class TestableOfferController extends OfferController
{
public ?string $renderedView = null;
/** @var array<string, mixed> */
public array $renderedParameters = [];
public function __construct(
AccommodationBookingRepository $bookingRepository,
AccommodationBookingLinkSigner $linkSigner,
AccommodationBookingBreakdownCalculator $breakdownCalculator,
AccommodationBookingService $bookingService,
private readonly ?FormInterface $confirmationForm = null,
) {
parent::__construct($bookingRepository, $linkSigner, $breakdownCalculator, $bookingService);
}
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
return $this->confirmationForm ?? throw new \LogicException('No confirmation form mock configured for this test.');
}
protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
{
return 'https://example.test/agb/';
}
/**
* @var array<int, array{type: string, message: mixed}>
*/
public array $flashes = [];
protected function addFlash(string $type, mixed $message): void
{
$this->flashes[] = ['type' => $type, 'message' => $message];
}
/**
* @param array<string, mixed> $parameters
*/
protected function generateUrl(string $route, array $parameters = [], int $referenceType = 1): string
{
return '/'.$route.'?'.http_build_query($parameters);
}
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
$this->renderedView = $view;
$this->renderedParameters = $parameters;
if ('groups/booking/offer.html.twig' === $view) {
$content = $parameters['booking']->isInquiry() ? '<html>offer</html>' : '<html>confirmed</html>';
} else {
$content = '<html>unavailable</html>';
}
$response ??= new Response();
$response->setContent($content);
return $response;
}
}
@@ -0,0 +1,402 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller\Groups;
use App\Controller\Groups\Step4Controller;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Form\Model\AccommodationBookingDto;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
class Step4ControllerTest extends TestCase
{
public function testIndexRendersRecapWhenStepFourReached(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$dto->isInquiry = false;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $this->createMock(FormInterface::class));
$response = $controller->index($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/step_4.html.twig', $controller->renderedView);
self::assertSame($dto, $controller->renderedParameters['dto']);
}
public function testIndexRedirectsToStep3WhenNotYetReached(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 3;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$controller = new TestableStep4Controller(
$this->createMock(AccommodationBookingService::class),
$sessionManager,
$this->createMock(FormInterface::class),
);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_step_3', $response->getTargetUrl());
}
public function testIndexPostWithValidCsrfPersistsAsInquiryAndRedirects(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$booking = (new AccommodationBooking())->setIsInquiry(true);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$bookingService->method('loadPrices')->willReturn([]);
$bookingService->expects(self::once())->method('finalizeBooking')->willReturn($booking);
$inquiryForm = $this->createMock(FormInterface::class);
$inquiryForm->method('handleRequest')->willReturnSelf();
$inquiryForm->method('isSubmitted')->willReturn(true);
$inquiryForm->method('isValid')->willReturn(true);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $inquiryForm);
$response = $controller->index($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_success', $response->getTargetUrl());
self::assertTrue($dto->forceInquiry);
self::assertNull($sessionManager->getDto($request));
}
public function testIndexPostWithInvalidFormThrowsAccessDenied(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$bookingService->expects(self::never())->method('finalizeBooking');
$inquiryForm = $this->createMock(FormInterface::class);
$inquiryForm->method('handleRequest')->willReturnSelf();
$inquiryForm->method('isSubmitted')->willReturn(true);
$inquiryForm->method('isValid')->willReturn(false);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $inquiryForm);
$this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class);
$controller->index($request);
}
public function testConfirmInquiryGetRendersModal(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4/confirm-inquiry', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$controller = new TestableStep4Controller(
$this->createMock(AccommodationBookingService::class),
$sessionManager,
$this->createMock(FormInterface::class),
);
$response = $controller->confirmInquiry($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/_step4_inquiry_confirmation_modal.html.twig', $controller->renderedView);
}
public function testConfirmInquiryRedirectsToStep3WhenNotYetReached(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 3;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4/confirm-inquiry', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$controller = new TestableStep4Controller(
$this->createMock(AccommodationBookingService::class),
$sessionManager,
$this->createMock(FormInterface::class),
);
$response = $controller->confirmInquiry($request);
self::assertInstanceOf(RedirectResponse::class, $response);
self::assertSame('/app_groups_booking_step_3', $response->getTargetUrl());
}
public function testConfirmGetRendersModalWithFreshForm(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4/confirm', 'GET');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->expects(self::never())->method('finalizeBooking');
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(false);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $confirmationForm);
$response = $controller->confirm($request);
self::assertSame(200, $response->getStatusCode());
self::assertSame('groups/booking/_step4_booking_confirmation_modal.html.twig', $controller->renderedView);
self::assertSame($confirmationForm, $controller->renderedParameters['confirmationForm']);
self::assertSame($dto, $sessionManager->getDto($request));
}
public function testConfirmPostValidPersistsAndRedirects(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4/confirm', 'POST');
$request->setSession($session);
$request->headers->set('HX-Request', 'true');
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$booking = (new AccommodationBooking())->setIsInquiry(false);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->method('loadAvailableServices')->willReturn([
'boardServices' => [],
'additionalServices' => [],
'groupedAdditionalServices' => [],
'ungroupedAdditionalServices' => [],
]);
$bookingService->method('loadPrices')->willReturn([]);
$bookingService->expects(self::once())->method('finalizeBooking')->willReturn($booking);
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(true);
$confirmationForm->method('isValid')->willReturn(true);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $confirmationForm);
$response = $controller->confirm($request);
self::assertSame(200, $response->getStatusCode());
self::assertTrue($response->headers->has('HX-Redirect'));
self::assertNull($sessionManager->getDto($request));
}
public function testConfirmPostInvalidReRendersModalWithoutPersisting(): void
{
$dto = new AccommodationBookingDto();
$dto->currentStep = 4;
$dto->accommodationId = 1;
$session = new Session(new MockArraySessionStorage());
$request = Request::create('/groups/booking/step-4/confirm', 'POST');
$request->setSession($session);
$sessionManager = new AccommodationSessionManager();
$sessionManager->save($request, $dto);
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$bookingService = $this->createMock(AccommodationBookingService::class);
$bookingService->method('loadAccommodation')->with(1)->willReturn($accommodation);
$bookingService->expects(self::never())->method('finalizeBooking');
$confirmationForm = $this->createMock(FormInterface::class);
$confirmationForm->method('handleRequest')->willReturnSelf();
$confirmationForm->method('isSubmitted')->willReturn(true);
$confirmationForm->method('isValid')->willReturn(false);
$controller = new TestableStep4Controller($bookingService, $sessionManager, $confirmationForm);
$response = $controller->confirm($request);
self::assertSame(200, $response->getStatusCode());
self::assertFalse($response->headers->has('HX-Redirect'));
self::assertSame('groups/booking/_step4_booking_confirmation_modal.html.twig', $controller->renderedView);
self::assertNotNull($sessionManager->getDto($request));
}
}
final class TestableStep4Controller extends Step4Controller
{
/**
* @var array<string, mixed>
*/
public array $renderedParameters = [];
public string $renderedView = '';
public function __construct(
AccommodationBookingService $bookingService,
AccommodationSessionManager $sessionManager,
private readonly FormInterface $form,
) {
parent::__construct($bookingService, $sessionManager);
}
/**
* @return FormInterface<mixed>
*/
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
return $this->form;
}
protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
{
return 'https://example.test/agb/';
}
/**
* @param array<string, mixed> $parameters
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return new RedirectResponse('/'.$route, $status);
}
/**
* @param array<string, mixed> $parameters
*/
protected function generateUrl(string $route, array $parameters = [], int $referenceType = 1): string
{
return '/'.$route;
}
protected function addFlash(string $type, mixed $message): void
{
// no-op: avoids requiring a full service container in these unit tests
}
/**
* @param array<string, mixed> $parameters
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
$this->renderedView = $view;
$this->renderedParameters = $parameters;
return new Response('ok');
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form;
use App\Form\AccommodationStep2Type;
use App\Form\Model\AccommodationBookingDto;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Forms;
class AccommodationStep2TypeTest extends TestCase
{
public function testChildrenLabelIsBuiltFromMaxAdolescentAgeOption(): void
{
$form = Forms::createFormFactoryBuilder()
->getFormFactory()
->create(AccommodationStep2Type::class, new AccommodationBookingDto(), [
'max_adolescent_age' => 15,
]);
self::assertSame(
'davon Kinder (415 Jahre)',
$form->get('childrenCount')->getConfig()->getOption('label'),
);
}
public function testBlankOptionalChildCountersAreNormalizedToZero(): void
{
$dto = new AccommodationBookingDto();
$form = Forms::createFormFactoryBuilder()
->getFormFactory()
->create(AccommodationStep2Type::class, $dto);
$form->submit([
'paxCount' => '2',
'minorsCount' => '',
'childrenCount' => '',
'selectedBoardServiceId' => '',
'selectedAdditionalServiceIds' => [],
]);
self::assertTrue($form->isSynchronized());
self::assertSame(0, $dto->minorsCount);
self::assertSame(0, $dto->childrenCount);
}
public function testGroupedAdditionalServiceValuesCanSubmitUnderSelectionGroupKeys(): void
{
$dto = new AccommodationBookingDto();
$form = Forms::createFormFactoryBuilder()
->getFormFactory()
->create(AccommodationStep2Type::class, $dto, [
'additional_service_choices' => [
'Ski service' => 101,
'Board service' => 202,
],
]);
$form->submit([
'paxCount' => '2',
'minorsCount' => '0',
'childrenCount' => '0',
'selectedBoardServiceId' => '',
'selectedAdditionalServiceIds' => [
'Ski extras' => '101',
'Board extras' => '202',
],
]);
self::assertTrue($form->isSynchronized());
self::assertSame([101, 202], array_values($dto->selectedAdditionalServiceIds));
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Tests\Model;
use App\Model\ContingentCalendarQuery;
use App\Model\ContingentPricesQuery;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Validation;
class ContingentQueryTest extends TestCase
{
public function testCalendarQueryAcceptsValidRange(): void
{
$query = new ContingentCalendarQuery('HOTEL_1', '2026-01-01', '2026-12-31');
self::assertCount(0, $this->validator()->validate($query));
self::assertSame('2026-01-01', $query->dateFromDate()->format('Y-m-d'));
}
/**
* @dataProvider invalidCalendarQueries
*/
public function testCalendarQueryRejectsInvalidInput(ContingentCalendarQuery $query): void
{
self::assertGreaterThan(0, $this->validator()->validate($query)->count());
}
public function invalidCalendarQueries(): iterable
{
yield 'normalized invalid date' => [new ContingentCalendarQuery('HOTEL', '2026-02-31', '2026-03-01')];
yield 'reversed range' => [new ContingentCalendarQuery('HOTEL', '2026-03-02', '2026-03-01')];
yield 'range over 366 days' => [new ContingentCalendarQuery('HOTEL', '2026-01-01', '2027-01-03')];
yield 'invalid hotel code' => [new ContingentCalendarQuery('HOTEL CODE', '2026-01-01', '2026-01-02')];
}
public function testPricesQueryRequiresFourDigitYear(): void
{
self::assertCount(0, $this->validator()->validate(new ContingentPricesQuery('HOTEL', 2026)));
self::assertGreaterThan(0, $this->validator()->validate(new ContingentPricesQuery('HOTEL', 26))->count());
}
private function validator(): \Symfony\Component\Validator\Validator\ValidatorInterface
{
return Validation::createValidatorBuilder()
->enableAttributeMapping()
->getValidator();
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Entity\Groups\AccommodationBooking;
use App\Repository\Groups\AccommodationPriceRepository;
use App\Service\AccommodationBookingBreakdownCalculator;
use App\Service\GroupsPriceCalculator;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
class AccommodationBookingBreakdownCalculatorTest extends TestCase
{
public function testComputeReturnsStoredSnapshotWithoutLoadingCurrentPrices(): void
{
$snapshot = ['total' => 12345, 'currency' => 'EUR'];
$booking = new AccommodationBooking();
$booking->setPriceSnapshot($snapshot, 12345, 'EUR', 1);
$priceRepository = $this->createMock(AccommodationPriceRepository::class);
$priceRepository->expects(self::never())->method('findByHotelCodeAndDateRange');
$calculator = new AccommodationBookingBreakdownCalculator(
new GroupsPriceCalculator(new PriceTimelineBuilder(), [
'runningCostsEur' => 0,
'runningCostsChf' => 0,
'undersubscription30Eur' => 0,
'undersubscription30Chf' => 0,
'undersubscription40Eur' => 0,
'undersubscription40Chf' => 0,
]),
$priceRepository,
);
self::assertSame($snapshot, $calculator->compute($booking));
}
}
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Entity\Groups\AccommodationBooking;
use App\Service\AccommodationBookingLinkSigner;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class AccommodationBookingLinkSignerTest extends TestCase
{
public function testSignThenIsValidLinkRequestSucceeds(): void
{
$booking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$signedUrl = $signer->sign($booking);
$request = Request::create($signedUrl);
self::assertTrue($signer->isValidLinkRequest($request, $booking));
}
public function testTamperedQueryParamFails(): void
{
$booking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$signedUrl = $signer->sign($booking);
self::assertTrue($signer->isValidLinkRequest(Request::create($signedUrl), $booking));
// Flip the `t` value while keeping the original _hash — signature no longer matches.
$tamperedUrl = preg_replace('/(?<=[?&]t=)\d+/', '999999999', $signedUrl);
self::assertNotNull($tamperedUrl);
self::assertFalse($signer->isValidLinkRequest(Request::create($tamperedUrl), $booking));
}
public function testRegeneratedLinkInvalidatesThePreviousOne(): void
{
$booking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$signedUrl = $signer->sign($booking);
$request = Request::create($signedUrl);
// Regenerating overwrites accessLinkIssuedAt — the old signed `t` no longer matches.
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable('+1 minute'));
self::assertFalse($signer->isValidLinkRequest($request, $booking));
}
public function testExpiredLinkFails(): void
{
$booking = new AccommodationBooking();
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable('-91 days'));
$signer = $this->createSigner();
$signedUrl = $signer->sign($booking);
$request = Request::create($signedUrl);
self::assertFalse($signer->isValidLinkRequest($request, $booking));
}
public function testMissingAccessLinkIssuedAtFails(): void
{
$booking = new AccommodationBooking();
$signer = $this->createSigner();
$request = Request::create('https://example.com/groups/booking/offer/'.$booking->getUuid().'?t=123');
self::assertFalse($signer->isValidLinkRequest($request, $booking));
}
public function testSignThrowsWithoutAccessLinkIssuedAt(): void
{
$booking = new AccommodationBooking();
$signer = $this->createSigner();
$this->expectException(\LogicException::class);
$signer->sign($booking);
}
public function testExpiresAtIsNinetyDaysAfterIssuedAt(): void
{
$issuedAt = new \DateTimeImmutable('2026-01-01T00:00:00+00:00');
$booking = new AccommodationBooking();
$booking->setAccessLinkIssuedAt($issuedAt);
$signer = $this->createSigner();
self::assertSame('2026-04-01T00:00:00+00:00', $signer->expiresAt($booking)?->format(\DATE_ATOM));
}
public function testSessionIsAuthorizedAfterAuthorizeSession(): void
{
$booking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$request = $this->requestWithSession();
self::assertFalse($signer->isSessionAuthorized($request, $booking));
$signer->authorizeSession($request, $booking);
self::assertTrue($signer->isSessionAuthorized($request, $booking));
}
public function testSessionAuthorizationIsPerBooking(): void
{
$booking = $this->bookingWithAccessLink();
$otherBooking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$request = $this->requestWithSession();
$signer->authorizeSession($request, $booking);
self::assertTrue($signer->isSessionAuthorized($request, $booking));
self::assertFalse($signer->isSessionAuthorized($request, $otherBooking));
}
public function testSessionAuthorizationIsRevokedWhenLinkIsRegenerated(): void
{
$booking = $this->bookingWithAccessLink();
$signer = $this->createSigner();
$request = $this->requestWithSession();
$signer->authorizeSession($request, $booking);
self::assertTrue($signer->isSessionAuthorized($request, $booking));
// Regenerating the access link overwrites accessLinkIssuedAt — the
// previously-authorized session no longer matches.
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable('+1 minute'));
self::assertFalse($signer->isSessionAuthorized($request, $booking));
}
public function testSessionAuthorizationFailsPastTtlEvenIfSessionMatches(): void
{
$booking = new AccommodationBooking();
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable('-91 days'));
$signer = $this->createSigner();
$request = $this->requestWithSession();
$signer->authorizeSession($request, $booking);
self::assertFalse($signer->isSessionAuthorized($request, $booking));
}
public function testSessionAuthorizationFailsWithoutAccessLinkIssuedAt(): void
{
$booking = new AccommodationBooking();
$signer = $this->createSigner();
$request = $this->requestWithSession();
self::assertFalse($signer->isSessionAuthorized($request, $booking));
}
private function requestWithSession(): Request
{
$request = Request::create('https://example.com/');
$request->setSession(new Session(new MockArraySessionStorage()));
return $request;
}
private function bookingWithAccessLink(): AccommodationBooking
{
$booking = new AccommodationBooking();
$booking->setPaxCount(10);
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable());
return $booking;
}
private function createSigner(): AccommodationBookingLinkSigner
{
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator
->method('generate')
->willReturnCallback(static fn (string $name, array $parameters) => sprintf(
'https://example.com/groups/booking/offer/%s?t=%s',
$parameters['uuid'],
$parameters['t'],
));
return new AccommodationBookingLinkSigner($urlGenerator, 'test-secret');
}
}
@@ -0,0 +1,359 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Email\Mailer;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Entity\Groups\AccommodationPrice;
use App\Model\AccommodationBookingQueryParams;
use App\Repository\Groups\AccommodationPriceRepository;
use App\Repository\Groups\AccommodationRepository;
use App\Repository\Groups\AdditionalServiceRepository;
use App\Repository\Groups\BoardServiceRepository;
use App\Service\AccommodationBookingBreakdownCalculator;
use App\Service\AccommodationBookingLinkSigner;
use App\Service\AccommodationBookingService;
use App\Service\CmsDataProvider;
use App\Service\PriceTimelineBuilder;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
class AccommodationBookingServiceTest extends TestCase
{
public function testInitFromParamsAcceptsStrictCalendarDates(): void
{
$service = $this->createServiceWithAccommodation();
$dto = $service->initFromParams(new AccommodationBookingQueryParams('HOTEL', '2026-02-28', '2026-03-01'));
self::assertSame('2026-02-28', $dto->dateFrom?->format('Y-m-d'));
self::assertSame('2026-03-01', $dto->dateTo?->format('Y-m-d'));
}
public function testInitFromParamsPrefillsPaxCountFromEffectiveMinPax(): void
{
$price = (new AccommodationPrice())
->setDateFrom(new \DateTimeImmutable('2026-02-01'))
->setDateTo(new \DateTimeImmutable('2026-03-31'))
->setIncludedPax(4);
$service = $this->createServiceWithAccommodation([$price]);
$dto = $service->initFromParams(new AccommodationBookingQueryParams('HOTEL', '2026-02-28', '2026-03-01'));
self::assertSame(4, $dto->paxCount);
}
public function testInitFromParamsRejectsNormalizedInvalidCalendarDates(): void
{
$service = $this->createServiceWithAccommodation();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Ungültiges Datumsformat. Erwartet: YYYY-MM-DD.');
$service->initFromParams(new AccommodationBookingQueryParams('HOTEL', '2026-02-31', '2026-03-05'));
}
public function testIssueAccessLinkForDirectBookingSetsTimestampForDirectBooking(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::once())->method('flush');
$service = $this->createServiceWithAccommodation(entityManager: $entityManager);
$booking = new AccommodationBooking();
$booking->setIsInquiry(false);
$service->issueAccessLinkForDirectBooking($booking);
self::assertNotNull($booking->getAccessLinkIssuedAt());
}
public function testIssueAccessLinkForDirectBookingNoOpsForInquiry(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('flush');
$service = $this->createServiceWithAccommodation(entityManager: $entityManager);
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$service->issueAccessLinkForDirectBooking($booking);
self::assertNull($booking->getAccessLinkIssuedAt());
}
public function testIssueAccessLinkForDirectBookingNoOpsWhenAlreadySet(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('flush');
$service = $this->createServiceWithAccommodation(entityManager: $entityManager);
$booking = new AccommodationBooking();
$booking->setIsInquiry(false);
$issuedAt = new \DateTimeImmutable('2026-01-01');
$booking->setAccessLinkIssuedAt($issuedAt);
$service->issueAccessLinkForDirectBooking($booking);
self::assertSame($issuedAt, $booking->getAccessLinkIssuedAt());
}
public function testSendCustomerConfirmationEmailAlwaysSendsWithLinkWhenIssued(): void
{
$booking = new AccommodationBooking();
$booking->setEmail('[email protected]');
$booking->setIsInquiry(false);
$booking->setAccessLinkIssuedAt(new \DateTimeImmutable());
$linkSigner = $this->createMock(AccommodationBookingLinkSigner::class);
$linkSigner->method('sign')->with($booking)->willReturn('https://example.com/offer/signed-link');
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(['total' => 1000, 'currency' => 'EUR']);
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail')
->with(
self::callback(static fn (array $context) => 'https://example.com/offer/signed-link' === $context['accessLink']),
self::callback(static fn (array $options) => '[email protected]' === $options['to']
&& 'email/accommodation_booking_customer.html.twig' === $options['template']),
);
$service = $this->createServiceWithAccommodation(mailer: $mailer, linkSigner: $linkSigner, breakdownCalculator: $breakdownCalculator);
$service->sendCustomerConfirmationEmail($booking);
}
public function testSendCustomerConfirmationEmailSendsWithoutLinkForInquiry(): void
{
$booking = new AccommodationBooking();
$booking->setEmail('[email protected]');
$booking->setIsInquiry(true);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::once())
->method('createAndSendEmail')
->with(
self::callback(static fn (array $context) => null === $context['accessLink']),
self::anything(),
);
$service = $this->createServiceWithAccommodation(mailer: $mailer, breakdownCalculator: $breakdownCalculator);
$service->sendCustomerConfirmationEmail($booking);
}
public function testSendCustomerConfirmationEmailLogsAndSwallowsMailerFailures(): void
{
$booking = new AccommodationBooking();
$booking->setEmail('[email protected]');
$booking->setIsInquiry(true);
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$mailer = $this->createMock(Mailer::class);
$mailer->method('createAndSendEmail')->willThrowException(new \RuntimeException('SMTP down'));
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::once())->method('error');
$service = $this->createServiceWithAccommodation(mailer: $mailer, breakdownCalculator: $breakdownCalculator, logger: $logger);
$service->sendCustomerConfirmationEmail($booking);
}
public function testRegenerateAccessLinkOverwritesAccessLinkIssuedAt(): void
{
$booking = new AccommodationBooking();
$booking->setEmail('[email protected]');
$booking->setIsInquiry(true);
$previousIssuedAt = new \DateTimeImmutable('2026-01-01');
$booking->setAccessLinkIssuedAt($previousIssuedAt);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::once())->method('flush');
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('compute')->willReturn(null);
$mailer = $this->createMock(Mailer::class);
$mailer->expects(self::never())->method('createAndSendEmail');
$service = $this->createServiceWithAccommodation(
entityManager: $entityManager,
mailer: $mailer,
breakdownCalculator: $breakdownCalculator,
);
$service->regenerateAccessLink($booking);
self::assertNotSame($previousIssuedAt, $booking->getAccessLinkIssuedAt());
}
public function testAcceptBookingTransitionsInquiryToBookingAndSendsNotifications(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::once())->method('flush');
$booking = new AccommodationBooking();
$booking->setIsInquiry(true);
$booking->setEmail('[email protected]');
$mailer = $this->createMock(Mailer::class);
$mailer
->expects(self::exactly(2))
->method('createAndSendEmail')
->with(
self::anything(),
self::callback(static fn (array $options) => in_array($options['to'], ['[email protected]', '[email protected]'], true)
&& in_array($options['template'], ['email/offer_accepted.html.twig', 'email/offer_accepted_customer.html.twig'], true)),
);
$service = $this->createServiceWithAccommodation(entityManager: $entityManager, mailer: $mailer);
$service->acceptBooking($booking);
self::assertFalse($booking->isInquiry());
self::assertNotNull($booking->getAcceptedAt());
}
public function testAcceptBookingIsIdempotentAndSendsNoNotifications(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('flush');
$mailer = $this->createMock(Mailer::class);
$mailer->expects(self::never())->method('createAndSendEmail');
$service = $this->createServiceWithAccommodation(entityManager: $entityManager, mailer: $mailer);
$booking = new AccommodationBooking();
$booking->setIsInquiry(false);
$service->acceptBooking($booking);
self::assertNull($booking->getAcceptedAt());
}
public function testSendOfferAcceptedNotificationEmailLogsAndSwallowsMailerFailures(): void
{
$booking = new AccommodationBooking();
$booking->setIsInquiry(false);
$mailer = $this->createMock(Mailer::class);
$mailer->method('createAndSendEmail')->willThrowException(new \RuntimeException('SMTP down'));
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::once())->method('error');
$service = $this->createServiceWithAccommodation(mailer: $mailer, logger: $logger);
$service->sendOfferAcceptedNotificationEmail($booking);
}
public function testSendOfferAcceptedCustomerEmailLogsAndSwallowsMailerFailures(): void
{
$booking = new AccommodationBooking();
$booking->setEmail('[email protected]');
$booking->setIsInquiry(false);
$mailer = $this->createMock(Mailer::class);
$mailer->method('createAndSendEmail')->willThrowException(new \RuntimeException('SMTP down'));
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::once())->method('error');
$service = $this->createServiceWithAccommodation(mailer: $mailer, logger: $logger);
$service->sendOfferAcceptedCustomerEmail($booking);
}
public function testRefreshPriceSnapshotStoresDiscountedFinalTotal(): void
{
$booking = new AccommodationBooking();
$booking->setAccommodationDiscount(10);
$booking->setBoardServiceDiscount(20);
$booking->setAdditionalServicesDiscount(50);
$breakdown = [
'total' => 12345,
'currency' => 'CHF',
'basePrice' => 8000,
'additionalPersonsPrice' => 2000,
'boardPrice' => 1000,
'servicesPrice' => 500,
];
$breakdownCalculator = $this->createMock(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator
->expects(self::once())
->method('computeCurrent')
->with($booking)
->willReturn($breakdown);
$service = $this->createServiceWithAccommodation(breakdownCalculator: $breakdownCalculator);
$service->refreshPriceSnapshot($booking);
// accommodation: (8000+2000)*10% = 1000, board: 1000*20% = 200, services: 500*50% = 250
self::assertSame($breakdown, $booking->getPriceBreakdown());
self::assertSame(12345 - 1000 - 200 - 250, $booking->getTotalPrice());
self::assertSame('CHF', $booking->getPricingCurrency());
self::assertSame(1, $booking->getPricingVersion());
}
/**
* @param AccommodationPrice[] $prices
*/
private function createServiceWithAccommodation(
array $prices = [],
?EntityManagerInterface $entityManager = null,
?Mailer $mailer = null,
?LoggerInterface $logger = null,
?AccommodationBookingLinkSigner $linkSigner = null,
?AccommodationBookingBreakdownCalculator $breakdownCalculator = null,
): AccommodationBookingService {
$accommodation = (new Accommodation())
->setName('Hotel')
->setCalendarCode('HOTEL')
->setMaxAdolescentAge(17);
$accommodationRepo = $this->createMock(AccommodationRepository::class);
$accommodationRepo
->method('findOneBy')
->with(['calendarCode' => 'HOTEL'])
->willReturn($accommodation);
$priceRepo = $this->createMock(AccommodationPriceRepository::class);
$priceRepo
->method('findByHotelCodeAndDateRange')
->willReturn($prices);
return new AccommodationBookingService(
$accommodationRepo,
$priceRepo,
$this->createMock(AdditionalServiceRepository::class),
$this->createMock(BoardServiceRepository::class),
new PriceTimelineBuilder(),
$entityManager ?? $this->createMock(EntityManagerInterface::class),
$mailer ?? $this->createMock(Mailer::class),
$logger ?? $this->createMock(LoggerInterface::class),
$this->createMock(CmsDataProvider::class),
$linkSigner ?? $this->createMock(AccommodationBookingLinkSigner::class),
$breakdownCalculator ?? $this->createMock(AccommodationBookingBreakdownCalculator::class),
'[email protected]',
);
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Service\CmsDataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
class CmsDataProviderTest extends TestCase
{
public function testGetHotelDetailsMapsSnakeCaseFieldsToDto(): void
{
$client = new MockHttpClient(fn () => new MockResponse(json_encode([
'success' => true,
'name' => 'Hotel Alpin',
'address' => "Musterstraße 1\n1234 Musterort",
'description' => '<p>Beschreibung</p>',
'features' => '<p>Ausstattung</p>',
'room_types' => '<p>Zimmer</p>',
'additional_information' => '<p>Weitere Infos</p>',
'images' => ['resized' => ['l' => [['url' => 'l.jpg', 'alt' => 'Alt']]]],
'icons' => ['sauna' => ['label' => 'Sauna', 'value' => true]],
'region' => [
'name' => 'Alpenregion',
'latitude' => 47.1,
'longitude' => 11.2,
'webcam' => 'https://webcam.test',
'ski_area' => '<p>Skigebiet</p>',
'ski_area_extended' => '<p>Mehr Skigebiet</p>',
'description' => '<p>Region</p>',
'news' => '<p>News</p>',
'length' => '42',
'altitude' => '1800',
'lifts' => '5',
'images' => ['resized' => ['l' => []]],
'region_maps' => ['map1.jpg', 'map2.jpg'],
],
], JSON_THROW_ON_ERROR)));
$provider = new CmsDataProvider($client, new ArrayAdapter(), 'test-key');
$data = $provider->getHotelDetails('HOTEL1');
self::assertNotNull($data);
self::assertSame('Hotel Alpin', $data->name);
self::assertSame("Musterstraße 1\n1234 Musterort", $data->address);
self::assertSame('<p>Zimmer</p>', $data->roomTypes);
self::assertSame('<p>Weitere Infos</p>', $data->additionalInformation);
self::assertSame(['sauna' => ['label' => 'Sauna', 'value' => true]], $data->icons);
self::assertNotNull($data->region);
self::assertSame('Alpenregion', $data->region->name);
self::assertSame('<p>Skigebiet</p>', $data->region->skiArea);
self::assertSame('<p>Mehr Skigebiet</p>', $data->region->skiAreaExtended);
self::assertSame(['map1.jpg', 'map2.jpg'], $data->region->regionMaps);
self::assertSame(42, $data->region->length);
self::assertSame(1800, $data->region->altitude);
self::assertSame(5, $data->region->lifts);
self::assertSame(47.1, $data->region->latitude);
self::assertSame(11.2, $data->region->longitude);
}
public function testGetHotelDetailsReturnsNullOnFailure(): void
{
$client = new MockHttpClient(fn () => new MockResponse('', ['http_code' => 500]));
$provider = new CmsDataProvider($client, new ArrayAdapter(), 'test-key');
self::assertNull($provider->getHotelDetails('UNKNOWN'));
}
}
+261
View File
@@ -0,0 +1,261 @@
<?php
declare(strict_types=1);
namespace App\Tests\Service;
use App\Entity\Groups\AccommodationPrice;
use App\Enum\Groups\PriceType;
use App\Service\PriceTimelineBuilder;
use PHPUnit\Framework\TestCase;
class PriceTimelineBuilderTest extends TestCase
{
private PriceTimelineBuilder $builder;
protected function setUp(): void
{
$this->builder = new PriceTimelineBuilder();
}
// --- buildTimeline ---
public function testReturnsEmptyArrayForNoPrices(): void
{
$result = $this->builder->buildTimeline([], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertSame([], $result);
}
public function testSingleBasePriceWithinYear(): void
{
$price = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000, priceAdditionalPerson: 2000, includedPax: 2);
$result = $this->builder->buildTimeline([$price], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(1, $result);
$this->assertSame('2026-01-01', $result[0]->dateFrom);
$this->assertSame('2026-03-31', $result[0]->dateTo);
$this->assertSame(150.0, $result[0]->pricePerNight);
$this->assertSame(20.0, $result[0]->priceAdditionalPerson);
$this->assertSame(2, $result[0]->includedPax);
$this->assertNull($result[0]->type);
$this->assertNull($result[0]->defaultPricePerNight);
$this->assertNull($result[0]->defaultPriceAdditionalPerson);
$this->assertSame('EUR', $result[0]->currency);
}
public function testBasePriceStartingBeforeYearIsClamped(): void
{
$price = $this->makePrice('2025-12-01', '2026-03-31', pricePerNight: 10000);
$result = $this->builder->buildTimeline([$price], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(1, $result);
$this->assertSame('2026-01-01', $result[0]->dateFrom);
$this->assertSame('2026-03-31', $result[0]->dateTo);
}
public function testBasePriceEndingAfterYearIsClamped(): void
{
$price = $this->makePrice('2026-10-01', '2027-01-31', pricePerNight: 10000);
$result = $this->builder->buildTimeline([$price], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(1, $result);
$this->assertSame('2026-10-01', $result[0]->dateFrom);
$this->assertSame('2026-12-31', $result[0]->dateTo);
}
public function testDiscountSplitsBasePeriodIntoThreeRows(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000, type: PriceType::DISCOUNT);
$result = $this->builder->buildTimeline([$base, $discount], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(3, $result);
$this->assertSame('2026-01-01', $result[0]->dateFrom);
$this->assertSame('2026-01-14', $result[0]->dateTo);
$this->assertNull($result[0]->type);
$this->assertSame('2026-01-15', $result[1]->dateFrom);
$this->assertSame('2026-01-31', $result[1]->dateTo);
$this->assertSame('discount', $result[1]->type);
$this->assertSame('2026-02-01', $result[2]->dateFrom);
$this->assertSame('2026-03-31', $result[2]->dateTo);
$this->assertNull($result[2]->type);
}
public function testDiscountRowIncludesDefaultPrice(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000, priceAdditionalPerson: 3000);
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000, priceAdditionalPerson: 2000, type: PriceType::DISCOUNT);
$result = $this->builder->buildTimeline([$base, $discount], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$discountRow = $result[1];
$this->assertSame(120.0, $discountRow->pricePerNight);
$this->assertSame(150.0, $discountRow->defaultPricePerNight);
$this->assertSame(20.0, $discountRow->priceAdditionalPerson);
$this->assertSame(30.0, $discountRow->defaultPriceAdditionalPerson);
}
public function testBaseRowsHaveNullDefaultPriceFields(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000, type: PriceType::DISCOUNT);
$result = $this->builder->buildTimeline([$base, $discount], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertNull($result[0]->defaultPricePerNight);
$this->assertNull($result[0]->defaultPriceAdditionalPerson);
$this->assertNull($result[2]->defaultPricePerNight);
$this->assertNull($result[2]->defaultPriceAdditionalPerson);
}
public function testDiscountWithNoBasePriceHasNullDefaultPrice(): void
{
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000, type: PriceType::DISCOUNT);
$result = $this->builder->buildTimeline([$discount], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(1, $result);
$this->assertSame('discount', $result[0]->type);
$this->assertNull($result[0]->defaultPricePerNight);
}
public function testGapBetweenTwoPricesIsOmitted(): void
{
$first = $this->makePrice('2026-01-01', '2026-01-31', pricePerNight: 10000);
$second = $this->makePrice('2026-03-01', '2026-03-31', pricePerNight: 20000);
$result = $this->builder->buildTimeline([$first, $second], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(2, $result);
$this->assertSame('2026-01-01', $result[0]->dateFrom);
$this->assertSame('2026-01-31', $result[0]->dateTo);
$this->assertSame('2026-03-01', $result[1]->dateFrom);
$this->assertSame('2026-03-31', $result[1]->dateTo);
}
public function testOverrideSplitsBasePeriod(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$override = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 18000, type: PriceType::OVERRIDE);
$result = $this->builder->buildTimeline([$base, $override], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(3, $result);
$this->assertNull($result[0]->type);
$this->assertSame('override', $result[1]->type);
$this->assertSame(180.0, $result[1]->pricePerNight);
$this->assertNull($result[2]->type);
}
public function testDiscountOverTwoDifferentBasePricesProducesTwoDiscountRows(): void
{
// The discount spans two different base price periods. Even though the discount entity
// is the same, the rows must NOT be merged because defaultPricePerNight differs.
$baseA = $this->makePrice('2026-01-01', '2026-01-20', pricePerNight: 10000);
$baseB = $this->makePrice('2026-01-21', '2026-03-31', pricePerNight: 12000);
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 8000, type: PriceType::DISCOUNT);
$result = $this->builder->buildTimeline([$baseA, $baseB, $discount], new \DateTimeImmutable('2026-01-01'), new \DateTimeImmutable('2026-12-31'), 'EUR');
$this->assertCount(4, $result);
$this->assertSame('2026-01-01', $result[0]->dateFrom);
$this->assertSame('2026-01-14', $result[0]->dateTo);
$this->assertNull($result[0]->type);
$this->assertSame('2026-01-15', $result[1]->dateFrom);
$this->assertSame('2026-01-20', $result[1]->dateTo);
$this->assertSame('discount', $result[1]->type);
$this->assertSame(100.0, $result[1]->defaultPricePerNight); // baseA
$this->assertSame('2026-01-21', $result[2]->dateFrom);
$this->assertSame('2026-01-31', $result[2]->dateTo);
$this->assertSame('discount', $result[2]->type);
$this->assertSame(120.0, $result[2]->defaultPricePerNight); // baseB
$this->assertSame('2026-02-01', $result[3]->dateFrom);
$this->assertSame('2026-03-31', $result[3]->dateTo);
$this->assertNull($result[3]->type);
}
// --- resolveWinner ---
public function testResolveWinnerReturnsNullForEmptyArray(): void
{
$this->assertNull($this->builder->resolveWinner([]));
}
public function testResolveWinnerReturnsSingleCandidate(): void
{
$price = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 10000);
$this->assertSame($price, $this->builder->resolveWinner([$price]));
}
public function testResolveWinnerPrefersDiscountOverBase(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$discount = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000, type: PriceType::DISCOUNT);
$this->assertSame($discount, $this->builder->resolveWinner([$base, $discount]));
}
public function testResolveWinnerPrefersOverrideOverBase(): void
{
$base = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$override = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 18000, type: PriceType::OVERRIDE);
$this->assertSame($override, $this->builder->resolveWinner([$base, $override]));
}
public function testResolveWinnerPrefersDiscountOverOverride(): void
{
$override = $this->makePrice('2026-01-01', '2026-01-31', pricePerNight: 18000, type: PriceType::OVERRIDE);
$discount = $this->makePrice('2026-01-01', '2026-01-31', pricePerNight: 12000, type: PriceType::DISCOUNT);
$this->assertSame($discount, $this->builder->resolveWinner([$override, $discount]));
}
public function testResolveWinnerPrefersShorterPeriodOnEqualTypeTie(): void
{
$wide = $this->makePrice('2026-01-01', '2026-03-31', pricePerNight: 15000);
$narrow = $this->makePrice('2026-01-15', '2026-01-31', pricePerNight: 12000);
$this->assertSame($narrow, $this->builder->resolveWinner([$wide, $narrow]));
}
public function testResolveWinnerPrefersLaterStartOnEqualLengthTie(): void
{
// Both cover 30 days; the one starting later should win.
$earlier = $this->makePrice('2026-01-01', '2026-01-30', pricePerNight: 15000);
$later = $this->makePrice('2026-02-01', '2026-03-02', pricePerNight: 12000);
$this->assertSame($later, $this->builder->resolveWinner([$earlier, $later]));
}
private function makePrice(
string $dateFrom,
string $dateTo,
int $pricePerNight,
int $priceAdditionalPerson = 0,
int $includedPax = 2,
?PriceType $type = null,
): AccommodationPrice {
$price = new AccommodationPrice();
$price->setDateFrom(new \DateTimeImmutable($dateFrom));
$price->setDateTo(new \DateTimeImmutable($dateTo));
$price->setPricePerNight($pricePerNight);
$price->setPriceAdditionalPerson($priceAdditionalPerson);
$price->setIncludedPax($includedPax);
$price->setType($type);
return $price;
}
}