Compare commits

...
2 Commits
Author SHA1 Message Date
fromme 2aa98b81fe feat: dedicated login page for oauth2 logins 2026-09-27 13:43:17 +02:00
fromme 56adf72d12 fix: refuse implausible accommodation booking prices 2026-09-26 15:39:04 +02:00
24 changed files with 1004 additions and 84 deletions

No files matched your search

@@ -6,11 +6,13 @@ namespace App\Controller\Admin\AccommodationBooking;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Admin\Groups\AccommodationBookingChangeAccommodationType;
use App\Htmx\HxTrait;
use App\Service\AccommodationBookingService;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -49,7 +51,24 @@ class ChangeAccommodationController extends AbstractController
$selected = $form->get('accommodation')->getData();
if ($selected instanceof Accommodation && $selected !== $booking->getAccommodation()) {
$this->bookingService->changeAccommodation($booking, $selected);
try {
$this->bookingService->changeAccommodation($booking, $selected);
} catch (ImplausibleBookingPriceException $e) {
// The house that was picked prices this stay implausibly high, so the change
// did not happen. Reported in the modal the office is standing in front of —
// the same treatment the create and edit forms give it.
$this->logger->error('Refused to change accommodation over an implausible booking total', [
'exception' => $e,
'id' => $booking->getId(),
'accommodation' => $selected->getCalendarCode(),
]);
$form->addError(new FormError(ImplausibleBookingPriceException::FORM_ERROR_MESSAGE));
return $this->render('admin/accommodation_booking/modal_change_accommodation.html.twig', [
'booking' => $booking,
'form' => $form,
]);
}
$this->addFlash('success', 'Das Gruppenhaus wurde geändert. Bitte wähle die Leistungen neu aus.');
@@ -6,12 +6,15 @@ namespace App\Controller\Admin\AccommodationBooking;
use App\Entity\Groups\AccommodationBooking;
use App\Entity\User;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Admin\Groups\AccommodationBookingCreateType;
use App\Htmx\HxRedirectResponse;
use App\Service\AccommodationBookingService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -45,8 +48,7 @@ class CreateController extends AbstractController
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->bookingService->refreshPriceSnapshot($booking);
if ($form->isSubmitted() && $form->isValid() && $this->refreshPriceSnapshot($form, $booking)) {
$this->entityManager->persist($booking);
$this->entityManager->flush();
@@ -65,4 +67,31 @@ class CreateController extends AbstractController
'form' => $form,
]);
}
/**
* The price is computed after validation, so an implausible total cannot be a constraint on
* the form — it is reported as one anyway, because the office's next move is to go and fix
* the house's prices, not to read an error page.
*
* @param FormInterface<AccommodationBooking> $form
*/
private function refreshPriceSnapshot(FormInterface $form, AccommodationBooking $booking): bool
{
try {
$this->bookingService->refreshPriceSnapshot($booking);
return true;
} catch (ImplausibleBookingPriceException $e) {
$this->logger->error('Refused to store an implausible accommodation booking total', [
'exception' => $e,
'id' => $booking->getId(),
'accommodation' => $booking->getAccommodation()?->getCalendarCode(),
'paxCount' => $booking->getPaxCount(),
'nights' => $booking->getNights(),
]);
$form->addError(new FormError(ImplausibleBookingPriceException::FORM_ERROR_MESSAGE));
return false;
}
}
}
@@ -7,6 +7,7 @@ namespace App\Controller\Admin\AccommodationBooking;
use App\Entity\Groups\AccommodationBooking;
use App\Entity\Groups\AdditionalService;
use App\Entity\Groups\BoardService;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Admin\Groups\AccommodationBookingType;
use App\Repository\Groups\AdditionalServiceRepository;
use App\Repository\Groups\BoardServiceRepository;
@@ -15,6 +16,8 @@ use App\Service\AccommodationBookingService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -121,7 +124,15 @@ class EditController extends AbstractController
}
}
$this->bookingService->refreshPriceSnapshot($booking);
if (!$this->refreshPriceSnapshot($form, $booking)) {
// The submitted changes stay on the entity but are never flushed, so the form
// comes back filled in with the error on it. Logging is safe here: the database
// handler writes through DBAL, not the EntityManager.
return $this->render('admin/accommodation_booking/edit.html.twig', [
'booking' => $booking,
'form' => $form,
]);
}
// Editing never moves the booking on and never mails the customer: every status
// change is its own named action (Angebot senden, bestätigen, absagen), so the
@@ -154,4 +165,31 @@ class EditController extends AbstractController
'form' => $form,
]);
}
/**
* The price is computed after validation, so an implausible total cannot be a constraint on
* the form — it is reported as one anyway, because the office's next move is to go and fix
* the house's prices, not to read an error page.
*
* @param FormInterface<AccommodationBooking> $form
*/
private function refreshPriceSnapshot(FormInterface $form, AccommodationBooking $booking): bool
{
try {
$this->bookingService->refreshPriceSnapshot($booking);
return true;
} catch (ImplausibleBookingPriceException $e) {
$this->logger->error('Refused to store an implausible accommodation booking total', [
'exception' => $e,
'id' => $booking->getId(),
'accommodation' => $booking->getAccommodation()?->getCalendarCode(),
'paxCount' => $booking->getPaxCount(),
'nights' => $booking->getNights(),
]);
$form->addError(new FormError(ImplausibleBookingPriceException::FORM_ERROR_MESSAGE));
return false;
}
}
}
@@ -8,6 +8,7 @@ use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AdditionalService;
use App\Entity\Groups\BoardService;
use App\Exception\AccommodationSessionNotFoundException;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\AccommodationBookingConfirmationType;
use App\Form\AccommodationInquiryConfirmationType;
use App\Form\Model\AccommodationBookingDto;
@@ -16,6 +17,7 @@ use App\Model\AccommodationBookingContext;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use App\Service\AccommodationTermsUrlProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -28,6 +30,7 @@ class Step4Controller extends AbstractController
private readonly AccommodationBookingService $bookingService,
private readonly AccommodationSessionManager $sessionManager,
private readonly AccommodationTermsUrlProvider $termsUrlProvider,
private readonly LoggerInterface $logger,
) {
}
@@ -51,7 +54,9 @@ class Step4Controller extends AbstractController
}
$dto->forceInquiry = true;
$this->persistBooking($request, $dto, $accommodation, $services);
if (null !== $failure = $this->persistBooking($request, $dto, $accommodation, $services)) {
return $failure;
}
return $this->redirectToRoute('app_groups_booking_success');
}
@@ -102,7 +107,9 @@ class Step4Controller extends AbstractController
if ($confirmationForm->isSubmitted() && $confirmationForm->isValid()) {
$services = $this->bookingService->loadAvailableServices($dto, $accommodation);
$this->persistBooking($request, $dto, $accommodation, $services);
if (null !== $failure = $this->persistBooking($request, $dto, $accommodation, $services)) {
return $failure;
}
return $this->htmxRedirect($request, $this->generateUrl('app_groups_booking_success'));
}
@@ -148,12 +155,35 @@ class Step4Controller extends AbstractController
* groupedAdditionalServices: array<string, AdditionalService[]>,
* ungroupedAdditionalServices: AdditionalService[]
* } $services
*
* @return Response|null a response to return instead of the success redirect, or null when
* the booking was stored
*/
private function persistBooking(Request $request, AccommodationBookingDto $dto, Accommodation $accommodation, array $services): void
private function persistBooking(Request $request, AccommodationBookingDto $dto, Accommodation $accommodation, array $services): ?Response
{
$prices = $this->bookingService->loadPrices($dto, $accommodation);
$booking = $this->bookingService->finalizeBooking($dto, $accommodation, $prices, $services);
try {
$booking = $this->bookingService->finalizeBooking($dto, $accommodation, $prices, $services);
} catch (ImplausibleBookingPriceException $e) {
// The bounded inputs are already rejected in step 2, so what is left is a mistyped
// catalog price for this house — nothing the customer can act on and nothing to show
// them an error page over. The session survives so the desk can pick the inquiry up
// by phone with the data still in hand.
$this->logger->error('Refused to store an implausible accommodation booking total', [
'exception' => $e,
'accommodation' => $accommodation->getCalendarCode(),
'paxCount' => $dto->paxCount,
'nights' => $dto->getNights(),
]);
$this->addFlash('error', 'Die Anfrage konnte nicht abgeschlossen werden. Bitte wende dich direkt an uns — wir kümmern uns darum.');
return $this->htmxRedirect($request, $this->generateUrl('app_groups_booking_error'));
}
$this->addFlash('groups_booking_result', $booking->getOrigin()->value);
$this->sessionManager->clear($request);
return null;
}
}
+53 -12
View File
@@ -5,6 +5,7 @@ namespace App\Controller;
use App\Form\Model\BookingDto;
use App\Service\BookingSessionManager;
use App\Service\BookingSummaryAssembler;
use League\Bundle\OAuth2ServerBundle\Manager\ClientManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -21,13 +22,28 @@ class SecurityController extends AbstractController
Request $request,
BookingSessionManager $bookingSessionService,
BookingSummaryAssembler $summaryDataService,
ClientManagerInterface $clientManager,
): Response {
// flag this request in the session as external OAuth2 request if
// applicable to immediately logout the current user after successful
// authentication (see App\EventListener\AuthorizationCodeListener).
// Read before the booking flow is decided, because it overrules it.
$session = $request->getSession();
$targetPath = $session->get('_security.main.target_path');
$isOauth2 = \is_string($targetPath) && str_contains($targetPath, '/authorize');
$session->set('_oauth2', $isOauth2);
// Check if this is a booking flow (BookingDto exists in session)
$bookingDto = $bookingSessionService->getBookingDto($request, BookingDto::MODE_CREATE);
$isBookingFlow = null !== $bookingDto;
$hasPendingBooking = null !== $bookingDto;
// A pending authorization wins over a half-finished booking. Otherwise the target path
// below is overwritten with booking step 1, the user is sent there after logging in, and
// the application that asked for the authorization never receives its code.
$isBookingFlow = $hasPendingBooking && false === $isOauth2;
// If authenticated and in booking flow, proceed to Step 1
if (null !== $this->getUser() && true === $isBookingFlow) {
if (null !== $this->getUser() && true === $hasPendingBooking) {
return $this->redirectToRoute('app_booking_create_step_1');
}
@@ -39,21 +55,18 @@ class SecurityController extends AbstractController
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
// flag this request in the session as external OAuth2 request if
// applicable to immediately logout the current user after successful
// authentication (see App\EventListener\AuthorizationCodeListener).
$session = $request->getSession();
$targetPath = $session->get('_security.main.target_path');
$isOauth2 = null !== $targetPath && str_contains($targetPath, '/authorize');
$session->set('_oauth2', $isOauth2);
// For booking flow, set target path to Step 1 (after successful auth, redirect there)
if (true === $isBookingFlow) {
$session->set('_security.main.target_path', $this->generateUrl('app_booking_create_step_1'));
}
// Render booking login template if in booking flow, otherwise standard login
$template = true === $isBookingFlow ? 'booking/create/authenticate.html.twig' : 'security/login.html.twig';
// Render booking login template if in booking flow, the self-explaining one when another
// application sent them here to authorize it, otherwise standard login
$template = match (true) {
$isBookingFlow => 'booking/create/authenticate.html.twig',
$isOauth2 => 'security/login_oauth2.html.twig',
default => 'security/login.html.twig',
};
// Fetch CMS data for booking flow (uses cache warmed in IndexController)
$cmsData = null;
@@ -72,9 +85,37 @@ class SecurityController extends AbstractController
'travel_date_to' => $bookingDto?->travel->dateTo,
'cmsData' => $cmsData,
'oauth2' => $isOauth2,
'client_name' => $isOauth2 ? $this->authorizingClientName($clientManager, $targetPath) : null,
]);
}
/**
* The display name of the application that sent the user here to authorize it, so the login page
* can name it instead of leaving the user wondering why the site changed.
*
* Derived from the pending target path on every render rather than stashed on the session: a
* failed login redirects back to this route and the target path survives, so the name comes back
* with it. Returns null when the client cannot be resolved, and the page falls back to neutral
* wording rather than failing -- this runs before authentication.
*/
private function authorizingClientName(ClientManagerInterface $clientManager, ?string $targetPath): ?string
{
$query = null !== $targetPath ? parse_url($targetPath, \PHP_URL_QUERY) : null;
if (!\is_string($query) || '' === $query) {
return null;
}
parse_str($query, $params);
$clientId = $params['client_id'] ?? null;
if (!\is_string($clientId) || '' === $clientId) {
return null;
}
$name = $clientManager->find($clientId)?->getName() ?? '';
return '' !== $name ? $name : null;
}
#[Route('/logout', name: 'app_logout')]
#[IsGranted('ROLE_USER')]
public function logout(): void
+51 -1
View File
@@ -12,11 +12,13 @@ use App\Entity\User;
use App\Enum\Groups\AccommodationBookingOrigin;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Enum\Groups\AdditionalServiceType;
use App\Exception\ImplausibleBookingPriceException;
use App\Repository\Groups\AccommodationBookingRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
#[ORM\Entity(repositoryClass: AccommodationBookingRepository::class)]
class AccommodationBooking implements BlameableEntityInterface, TimestampableEntityInterface
@@ -24,6 +26,24 @@ class AccommodationBooking implements BlameableEntityInterface, TimestampableEnt
use BlameableEntity;
use TimestampableEntity;
/**
* Plausibility ceilings for the two figures every price in the breakdown is multiplied by.
* Both sit above anything the group houses actually see — the largest booking on record is
* 150 people for 18 nights — and exist so that a mistyped year or pax count is answered with
* a form error rather than a price nobody meant.
*/
public const int MAX_PAX = 250;
public const int MAX_NIGHTS = 30;
/**
* And the ceiling on the product of the two, in minor units: a million euros against a
* largest-ever booking of some 42,000. The inputs above cannot reach it, so what it catches
* is a mistyped catalog price, the one factor of the total that is not bounded per booking.
* Deliberately well inside what the INT column holds — the column's range is not a price
* limit, and a total that needs more room is a mistake rather than a wider column.
*/
public const int MAX_TOTAL_PRICE = 100_000_000;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
@@ -40,9 +60,11 @@ class AccommodationBooking implements BlameableEntityInterface, TimestampableEnt
private ?\DateTimeImmutable $dateFrom = null;
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
#[Assert\GreaterThan(propertyPath: 'dateFrom', message: 'Das Abreisedatum muss nach dem Anreisedatum liegen.')]
private ?\DateTimeImmutable $dateTo = null;
#[ORM\Column]
#[Assert\Range(min: 0, max: self::MAX_PAX)]
private int $paxCount = 0;
#[ORM\Column]
@@ -68,6 +90,7 @@ class AccommodationBooking implements BlameableEntityInterface, TimestampableEnt
#[ORM\Column(type: Types::JSON, nullable: true)]
private ?array $priceBreakdown = null;
/** In minor units, like every other price here, and never above self::MAX_TOTAL_PRICE. */
#[ORM\Column(nullable: true)]
private ?int $totalPrice = null;
@@ -232,6 +255,25 @@ class AccommodationBooking implements BlameableEntityInterface, TimestampableEnt
return $this->dateFrom->diff($this->dateTo)->days;
}
/**
* Reported on dateTo, the field a mistyped year is corrected in — a stay of 200 years is
* always the departure date being wrong, never the arrival.
*/
#[Assert\Callback]
public function validateStayLength(ExecutionContextInterface $context): void
{
if (null === $this->dateFrom || null === $this->dateTo) {
return;
}
if ($this->getNights() > self::MAX_NIGHTS) {
$context->buildViolation('Der Aufenthalt darf höchstens {{ max }} Nächte umfassen — bitte Anreise und Abreise prüfen.')
->setParameter('{{ max }}', (string) self::MAX_NIGHTS)
->atPath('dateTo')
->addViolation();
}
}
public function getPaxCount(): int
{
return $this->paxCount;
@@ -336,9 +378,17 @@ class AccommodationBooking implements BlameableEntityInterface, TimestampableEnt
return $this->priceBreakdown;
}
/** @param array<string, mixed> $priceBreakdown */
/**
* @param array<string, mixed> $priceBreakdown
*
* @throws ImplausibleBookingPriceException if the total is too large to be a real price
*/
public function setPriceSnapshot(array $priceBreakdown, int $totalPrice, string $currency, int $version): self
{
if ($totalPrice > self::MAX_TOTAL_PRICE) {
throw new ImplausibleBookingPriceException($totalPrice, $this->paxCount, $this->getNights());
}
$this->priceBreakdown = $priceBreakdown;
$this->totalPrice = $totalPrice;
$this->pricingCurrency = $currency;
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Exception;
use App\Entity\Groups\AccommodationBooking;
/**
* Thrown when a computed accommodation booking total is too large to be a real price.
*
* The total is a product of pax count, nights and catalog prices, so a single mistyped figure
* anywhere in that chain can produce a number nobody could owe. Storing it is pointless — it
* would go out on an offer — and a signed INT column answers it with SQLSTATE 22003, which says
* nothing about where the mistake is. Failing here instead names the price and the inputs it
* came from.
*/
class ImplausibleBookingPriceException extends \RuntimeException
{
/**
* What the backoffice is told. The total itself is in the log; the actionable part is the
* house's price rows, which is where the stray digit is.
*/
public const string FORM_ERROR_MESSAGE = 'Der berechnete Gesamtpreis ist unplausibel hoch. Bitte die Preise und Leistungen des Gruppenhauses prüfen.';
public function __construct(int $totalPrice, int $paxCount, int $nights, ?\Throwable $previous = null)
{
parent::__construct(
sprintf(
'Refusing to store an implausible booking total of %d (ceiling %d, in minor units) for %d people over %d nights — check the catalog prices for this house.',
$totalPrice,
AccommodationBooking::MAX_TOTAL_PRICE,
$paxCount,
$nights,
),
0,
$previous,
);
}
}
+7 -3
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Form\Model;
use App\Entity\Groups\AccommodationBooking;
use Symfony\Component\Validator\Constraints as Assert;
class AccommodationBookingDto
@@ -16,13 +17,16 @@ class AccommodationBookingDto
public ?\DateTimeImmutable $dateTo = null;
#[Assert\Positive(message: 'invalid', groups: ['step_3'])]
// step_2 is where the customer types these, so that is the group that has to carry the
// bounds: the price is computed from them on the same screen, and an implausible figure
// reaching step 4 only surfaces as a failure to store the booking.
#[Assert\Range(min: 1, max: AccommodationBooking::MAX_PAX, notInRangeMessage: 'invalid', groups: ['step_2', 'step_3'])]
public int $paxCount = 1;
#[Assert\PositiveOrZero(message: 'invalid', groups: ['step_3'])]
#[Assert\Range(min: 0, max: AccommodationBooking::MAX_PAX, notInRangeMessage: 'invalid', groups: ['step_2', 'step_3'])]
public int $minorsCount = 0;
#[Assert\PositiveOrZero(message: 'invalid', groups: ['step_3'])]
#[Assert\Range(min: 0, max: AccommodationBooking::MAX_PAX, notInRangeMessage: 'invalid', groups: ['step_2', 'step_3'])]
public int $childrenCount = 0;
#[Assert\NotNull(message: 'required', groups: ['step_2'])]
+22 -3
View File
@@ -13,6 +13,7 @@ use App\Entity\Groups\AdditionalService;
use App\Entity\Groups\BoardService;
use App\Enum\Groups\AccommodationBookingOrigin;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Model\AccommodationBookingDto;
use App\Model\AccommodationBookingContext;
use App\Model\AccommodationBookingQueryParams;
@@ -79,7 +80,8 @@ class AccommodationBookingService
/**
* Parses and validates raw date strings, then sets them on the DTO.
*
* @throws \InvalidArgumentException if dates are invalid or dateTo ≤ dateFrom
* @throws \InvalidArgumentException if dates are invalid, dateTo ≤ dateFrom, or the stay
* exceeds AccommodationBooking::MAX_NIGHTS
*/
public function applyDates(AccommodationBookingDto $dto, string $dateFromRaw, string $dateToRaw): void
{
@@ -94,6 +96,10 @@ class AccommodationBookingService
throw new \InvalidArgumentException('Das Abreisedatum muss nach dem Anreisedatum liegen.');
}
if ($dateFrom->diff($dateTo)->days > AccommodationBooking::MAX_NIGHTS) {
throw new \InvalidArgumentException(sprintf('Der Aufenthalt darf höchstens %d Nächte umfassen.', AccommodationBooking::MAX_NIGHTS));
}
$dto->dateFrom = $dateFrom->setTime(0, 0, 0);
$dto->dateTo = $dateTo->setTime(0, 0, 0);
}
@@ -566,6 +572,9 @@ class AccommodationBookingService
* their access link, and swapping the house underneath them would rewrite what they were
* offered.
* Idempotent — a no-op for a booking that is not a draft or already sits at $accommodation.
*
* @throws ImplausibleBookingPriceException if the new house prices the stay implausibly high;
* the booking is left at its old house
*/
public function changeAccommodation(AccommodationBooking $booking, Accommodation $accommodation): void
{
@@ -580,8 +589,18 @@ class AccommodationBookingService
$booking->setBoardServiceOriginalId(null);
$booking->setAdditionalServices([]);
// Clears the snapshot by itself when the new house has no price for the booked range.
$this->refreshPriceSnapshot($booking);
try {
// Clears the snapshot by itself when the new house has no price for the booked range.
$this->refreshPriceSnapshot($booking);
} catch (ImplausibleBookingPriceException $e) {
// The swap and the dropped services are already on the managed entity, and the next
// flush in this request would write them without a price. Reloading the row puts the
// booking back at its old house so the caller can report the refusal on a record that
// still matches the database.
$this->entityManager->refresh($booking);
throw $e;
}
$this->entityManager->flush();
}
+1 -13
View File
@@ -1,18 +1,6 @@
<div class="flex items-center justify-between">
<a href="{{ path('app_account') }}" title="zu meinem Account">
{# The operating entity depends on where the accommodation is, so its logo wins over the host's #}
{% set country_logo = accommodation|default(null) and accommodation.country ? accommodation.country.logo : null %}
{% if country_logo %}
<img src="{{ asset('build/images/' ~ country_logo) }}" alt="" class="h-14 my-1 w-auto">
{% elseif booking_theme() == 'sbw' %}
<img src="{{ asset('build/images/logo_sbw.svg') }}" alt="" class="h-10 my-2 w-auto">
{% elseif booking_theme() == 'ser' %}
<img src="{{ asset('build/images/logo_ser.svg') }}" alt="" class="h-10 my-2 w-auto">
{% elseif booking_theme() == 'snz' %}
<img src="{{ asset('build/images/logo_snz.svg') }}" alt="" class="h-10 my-2 w-auto">
{% else %}
<img src="{{ asset('build/images/logo_ep.svg') }}" alt="" class="h-10 my-2 w-auto">
{% endif %}
{% include '_partials/_logo.html.twig' %}
</a>
<div class="flex items-center space-x-2">
{% if is_granted('ROLE_USER') %}
+47
View File
@@ -0,0 +1,47 @@
{# The login form itself, shared by security/login.html.twig and security/login_oauth2.html.twig so
the field names, the CSRF token id and the error rendering cannot drift between the two pages.
Expects `error` and `last_username` from the including template's context. #}
{% if error %}
{% include '_partials/_alert.html.twig' with { 'level': 'error', messages: [ error.messageKey|trans(error.messageData, 'security') ] } %}
{% endif %}
<div class="pb-4">
<form action="{{ path('app_login') }}" method="post">
<div class="mb-4">
<label for="username" class="mb-1 font-semibold text-white">
E-Mail:
</label>
<input type="email"
id="username"
name="_username"
value="{{ last_username }}"
class="form-field"
required
autocomplete="username">
</div>
<div class="mb-4" {{ stimulus_controller('password-reveal') }}>
<label for="password" class="mb-1 font-semibold text-white">
Passwort:
</label>
<div class="relative">
<input type="password"
id="password"
name="_password"
class="form-field"
{{ stimulus_target('password-reveal', 'field') }}
required
autocomplete="current-password">
<button type="button"
{{ stimulus_action('password-reveal', 'toggle') }}
class="absolute top-0 right-0 mt-2 mr-2">
{{ icon('eye', 'w-6 h-6 text-gray-500') }}
</button>
</div>
</div>
<div class="flex flex-col lg:flex-row space-y-2 lg:space-y-0 lg:space-x-2 mt-4">
<button type="submit" class="button button--primary">
Login
</button>
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</form>
</div>
+15
View File
@@ -0,0 +1,15 @@
{# The brand logo, extracted from _header.html.twig so the OAuth2 login chrome can show the same
logo without inheriting the account links that go with it. Takes an optional `accommodation`. #}
{# The operating entity depends on where the accommodation is, so its logo wins over the host's #}
{% set country_logo = accommodation|default(null) and accommodation.country ? accommodation.country.logo : null %}
{% if country_logo %}
<img src="{{ asset('build/images/' ~ country_logo) }}" alt="" class="h-14 my-1 w-auto">
{% elseif booking_theme() == 'sbw' %}
<img src="{{ asset('build/images/logo_sbw.svg') }}" alt="" class="h-10 my-2 w-auto">
{% elseif booking_theme() == 'ser' %}
<img src="{{ asset('build/images/logo_ser.svg') }}" alt="" class="h-10 my-2 w-auto">
{% elseif booking_theme() == 'snz' %}
<img src="{{ asset('build/images/logo_snz.svg') }}" alt="" class="h-10 my-2 w-auto">
{% else %}
<img src="{{ asset('build/images/logo_ep.svg') }}" alt="" class="h-10 my-2 w-auto">
{% endif %}
+14
View File
@@ -0,0 +1,14 @@
{# Chrome for a login that is serving an external OAuth2 authorization.
Only the logo survives from the normal header: the account and logout links are dead ends in the
middle of an authorization, and the marketing column of the standard login page is noise when the
user did not come here to read about MyE&P. The footer's legal links stay -- this page collects
credentials, so dropping them would be the wrong direction.
The background is inherited unchanged, which is why the shared form partial's `text-white`
styling still works here. #}
{% extends 'layout.html.twig' %}
{% block header %}
{% include '_partials/_logo.html.twig' %}
{% endblock %}
+1 -44
View File
@@ -7,50 +7,7 @@
Login<br>MyE&amp;P
</h1>
{% include '_partials/_flashes.html.twig' %}
{% if error %}
{% include '_partials/_alert.html.twig' with { 'level': 'error', messages: [ error.messageKey|trans(error.messageData, 'security') ] } %}
{% endif %}
<div class="pb-4">
<form action="{{ path('app_login') }}" method="post" hx-history="false">
<div class="mb-4">
<label for="username" class="mb-1 font-semibold text-white">
E-Mail:
</label>
<input type="email"
id="username"
name="_username"
value="{{ last_username }}"
class="form-field"
required
autocomplete="username">
</div>
<div class="mb-4" {{ stimulus_controller('password-reveal') }}>
<label for="password" class="mb-1 font-semibold text-white">
Passwort:
</label>
<div class="relative">
<input type="password"
id="password"
name="_password"
class="form-field"
{{ stimulus_target('password-reveal', 'field') }}
required
autocomplete="current-password">
<button type="button"
{{ stimulus_action('password-reveal', 'toggle') }}
class="absolute top-0 right-0 mt-2 mr-2">
{{ icon('eye', 'w-6 h-6 text-gray-500') }}
</button>
</div>
</div>
<div class="flex flex-col lg:flex-row space-y-2 lg:space-y-0 lg:space-x-2 mt-4">
<button type="submit" class="button button--primary">
Login
</button>
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</form>
</div>
{% include '_partials/_login_form.html.twig' %}
<div class="flex space-x-2">
<a href="{{ path('app_reset_password') }}"
class="text-white underline">
+37
View File
@@ -0,0 +1,37 @@
{# The login page as seen by someone who was sent here by another E&P application (ephub, myep-team)
to authorize it. Its job is to explain why they are suddenly on a different website and that they
will be sent back, which the standard login page never said.
The grid is the one from security/login.html.twig, minus its marketing column: that keeps the
form column at exactly the width it has on the standard login page. #}
{% extends 'layout_oauth2.html.twig' %}
{% block content %}
<div class="grid grid-cols-1 md:grid-cols-2 gap-8 px-4 lg:px-8 py-8 lg:py-16">
<div>
<h1 class="text-white uppercase pb-4 mb-8 border-b border-primary-bg/40">
{% if client_name %}
Anmelden für<br>{{ client_name }}
{% else %}
Login<br>MyE&amp;P
{% endif %}
</h1>
<p class="mb-6 text-white">
Melde dich mit deinem MyE&amp;P-Konto an. Anschließend wirst du automatisch
{% if client_name %}zu {{ client_name }} {% endif %}zurückgeleitet.
</p>
{% include '_partials/_login_form.html.twig' %}
<div class="flex space-x-2">
<a href="{{ path('app_reset_password') }}" class="text-white underline">
Passwort vergessen?
</a>
<a href="{{ path('app_registration') }}" class="text-white underline">
Jetzt registrieren
</a>
</div>
</div>
</div>
{% endblock %}
@@ -8,6 +8,7 @@ use App\Controller\Admin\AccommodationBooking\ChangeAccommodationController;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Exception\ImplausibleBookingPriceException;
use App\Service\AccommodationBookingService;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
@@ -87,6 +88,36 @@ class ChangeAccommodationControllerTest extends TestCase
self::assertSame('success', $controller->flashes[0]['type']);
}
public function testAHouseThatPricesImplausiblyIsReportedInTheModal(): void
{
// The service leaves the booking at its old house and rethrows; the office has to see why
// the change did not happen, on the modal it just submitted, not as an error page.
$booking = $this->draft();
$bookingService = $this->createStub(AccommodationBookingService::class);
$bookingService->method('changeAccommodation')
->willThrowException(new ImplausibleBookingPriceException(AccommodationBooking::MAX_TOTAL_PRICE + 1, 40, 2));
$field = $this->createStub(FormInterface::class);
$field->method('getData')->willReturn(new Accommodation());
$form = $this->createMock(FormInterface::class);
$form->method('handleRequest')->willReturn($form);
$form->method('isSubmitted')->willReturn(true);
$form->method('isValid')->willReturn(true);
$form->method('get')->with('accommodation')->willReturn($field);
$form->expects(self::once())->method('addError');
$controller = $this->buildController($bookingService, $form);
$response = $controller->index($booking, $this->request('POST'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode());
self::assertFalse($response->headers->has('HX-Redirect'), 'the modal stays open on the error');
self::assertSame('admin/accommodation_booking/modal_change_accommodation.html.twig', $controller->renderedView);
self::assertSame([], $controller->flashes, 'nothing was changed, so nothing is reported as success');
}
public function testPickingTheSameHouseIsNotReportedAsAChange(): void
{
$booking = $this->draft();
@@ -7,6 +7,7 @@ namespace App\Tests\Controller\Admin\AccommodationBooking;
use App\Controller\Admin\AccommodationBooking\CreateController;
use App\Entity\Groups\AccommodationBooking;
use App\Entity\User;
use App\Exception\ImplausibleBookingPriceException;
use App\Service\AccommodationBookingService;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
@@ -32,6 +33,37 @@ class CreateControllerTest extends TestCase
self::assertSame($user, $controller->capturedBooking?->getManagedBy());
}
public function testAnImplausiblePriceComesBackAsAFormErrorWithoutSaving(): void
{
// Same as on the edit form: the fix is in the house's price rows, so the office is told
// on the form it is standing in front of, and nothing is written.
$bookingService = $this->createStub(AccommodationBookingService::class);
$bookingService->method('refreshPriceSnapshot')
->willThrowException(new ImplausibleBookingPriceException(AccommodationBooking::MAX_TOTAL_PRICE + 1, 40, 2));
$form = $this->createMock(FormInterface::class);
$form->method('handleRequest')->willReturn($form);
$form->method('isSubmitted')->willReturn(true);
$form->method('isValid')->willReturn(true);
$form->expects(self::once())->method('addError');
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('persist');
$entityManager->expects(self::never())->method('flush');
$controller = new TestableCreateController(
$entityManager,
$this->createStub(LoggerInterface::class),
$bookingService,
$form,
new User('[email protected]'),
);
$response = $controller->index(Request::create('/admin/accommodation-booking/create', 'POST'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode(), 'the modal is re-rendered, not redirected');
}
private function buildController(?UserInterface $user): TestableCreateController
{
$form = $this->createStub(FormInterface::class);
@@ -8,6 +8,7 @@ use App\Controller\Admin\AccommodationBooking\EditController;
use App\Entity\Groups\AccommodationBooking;
use App\Entity\User;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Exception\ImplausibleBookingPriceException;
use App\Repository\Groups\AdditionalServiceRepository;
use App\Repository\Groups\BoardServiceRepository;
use App\Repository\UserRepository;
@@ -46,6 +47,39 @@ class EditControllerTest extends TestCase
self::assertSame($status, $booking->getStatus(), 'editing leaves the status where it was');
}
public function testAnImplausiblePriceComesBackAsAFormErrorWithoutSaving(): void
{
// The office can fix this — in the house's price rows — so it belongs on the form rather
// than on an error page, and nothing may be flushed in the meantime.
$bookingService = $this->createStub(AccommodationBookingService::class);
$bookingService->method('refreshPriceSnapshot')
->willThrowException(new ImplausibleBookingPriceException(AccommodationBooking::MAX_TOTAL_PRICE + 1, 40, 2));
$form = $this->createMock(FormInterface::class);
$form->method('handleRequest')->willReturn($form);
$form->method('isSubmitted')->willReturn(true);
$form->method('isValid')->willReturn(true);
$form->method('has')->willReturn(false);
$form->expects(self::once())->method('addError');
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::never())->method('flush');
$controller = new TestableEditController(
$entityManager,
$this->createStub(LoggerInterface::class),
$this->createStub(BoardServiceRepository::class),
$this->createStub(AdditionalServiceRepository::class),
$this->createStub(UserRepository::class),
$bookingService,
$form,
);
$response = $controller->index(new AccommodationBooking(), Request::create('/admin/accommodation-booking/1/edit', 'POST'));
self::assertSame(Response::HTTP_OK, $response->getStatusCode(), 'the form is re-rendered, not redirected');
}
/**
* @return iterable<string, array{AccommodationBookingStatus}>
*/
@@ -8,11 +8,13 @@ use App\Controller\Groups\Booking\Step4Controller;
use App\Entity\Groups\Accommodation;
use App\Entity\Groups\AccommodationBooking;
use App\Enum\Groups\AccommodationBookingOrigin;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Model\AccommodationBookingDto;
use App\Service\AccommodationBookingService;
use App\Service\AccommodationSessionManager;
use App\Service\AccommodationTermsUrlProvider;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -302,6 +304,96 @@ class Step4ControllerTest extends TestCase
self::assertNull($sessionManager->getDto($request));
}
public function testConfirmPostEndsOnTheErrorPageWhenThePriceIsImplausible(): void
{
// A mistyped catalog price is the one way an implausible total still gets computed, and
// the customer must not meet it as a 500 — SQLSTATE 22003 on /admin is what started this.
$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);
$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->method('finalizeBooking')
->willThrowException(new ImplausibleBookingPriceException(AccommodationBooking::MAX_TOTAL_PRICE + 1, 40, 2));
$confirmationForm = $this->createStub(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('/app_groups_booking_error', $response->headers->get('HX-Redirect'));
// The session survives: the desk still has the inquiry to pick up by phone.
self::assertNotNull($sessionManager->getDto($request));
}
public function testIndexPostEndsOnTheErrorPageWhenThePriceIsImplausible(): 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->method('loadPrices')->willReturn([]);
$bookingService->method('finalizeBooking')
->willThrowException(new ImplausibleBookingPriceException(AccommodationBooking::MAX_TOTAL_PRICE + 1, 40, 2));
$inquiryForm = $this->createStub(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_error', $response->getTargetUrl());
}
public function testConfirmPostInvalidReRendersModalWithoutPersisting(): void
{
$dto = new AccommodationBookingDto();
@@ -358,6 +450,7 @@ final class TestableStep4Controller extends Step4Controller
$bookingService,
$sessionManager,
new AccommodationTermsUrlProvider(['AT' => '', 'CH' => '', 'IT' => ''], 'https://example.test/agb/'),
new NullLogger(),
);
}
+208
View File
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace App\Tests\Controller;
use App\BusProNet\Model\Travel;
use App\Controller\SecurityController;
use App\Form\Model\BookingDto;
use App\Service\BookingSessionManager;
use App\Service\BookingSummaryAssembler;
use League\Bundle\OAuth2ServerBundle\Manager\ClientManagerInterface;
use League\Bundle\OAuth2ServerBundle\Model\Client;
use PHPUnit\Framework\TestCase;
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\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityControllerTest extends TestCase
{
private const AUTHORIZE_PATH = '/authorize?response_type=code&client_id=abc123&redirect_uri=https%3A%2F%2Fephub.example%2Fcallback';
public function testAnAuthorizeTargetPathRendersTheSelfExplainingLoginPageNamingTheClient(): void
{
$controller = $this->createController();
$controller->clientManager
->expects(self::once())
->method('find')
->with('abc123')
->willReturn(new Client('EPHub', 'abc123', null));
$response = $controller->login(...$this->arguments($controller, self::AUTHORIZE_PATH));
self::assertSame(200, $response->getStatusCode());
self::assertSame('security/login_oauth2.html.twig', $controller->renderedView);
self::assertTrue($controller->renderedParameters['oauth2']);
self::assertSame('EPHub', $controller->renderedParameters['client_name']);
}
public function testWithoutAnAuthorizeTargetPathTheStandardLoginPageIsRendered(): void
{
$controller = $this->createController();
$controller->clientManager->expects(self::never())->method('find');
$response = $controller->login(...$this->arguments($controller, null));
self::assertSame(200, $response->getStatusCode());
self::assertSame('security/login.html.twig', $controller->renderedView);
self::assertFalse($controller->renderedParameters['oauth2']);
self::assertNull($controller->renderedParameters['client_name']);
}
/**
* The name is cosmetic and this runs before authentication, so an unknown client must degrade
* to neutral wording rather than break the login.
*/
public function testAnUnresolvableClientIdFallsBackToNeutralWording(): void
{
$controller = $this->createController();
$controller->clientManager
->expects(self::once())
->method('find')
->willReturn(null);
$response = $controller->login(...$this->arguments($controller, self::AUTHORIZE_PATH));
self::assertSame(200, $response->getStatusCode());
self::assertSame('security/login_oauth2.html.twig', $controller->renderedView);
self::assertNull($controller->renderedParameters['client_name']);
}
public function testAnAuthorizeTargetPathWithoutAClientIdFallsBackToNeutralWording(): void
{
$controller = $this->createController();
$controller->clientManager->expects(self::never())->method('find');
$response = $controller->login(...$this->arguments($controller, '/authorize'));
self::assertSame(200, $response->getStatusCode());
self::assertSame('security/login_oauth2.html.twig', $controller->renderedView);
self::assertNull($controller->renderedParameters['client_name']);
}
/**
* A booking left half-finished in the same browser used to overwrite the pending target path
* with booking step 1, so the application that asked for the authorization never got its code.
*/
public function testAPendingAuthorizationWinsOverAHalfFinishedBooking(): void
{
$controller = $this->createController(bookingDto: $this->createBookingDto());
$controller->clientManager
->expects(self::once())
->method('find')
->willReturn(new Client('EPHub', 'abc123', null));
$session = $this->createSession(self::AUTHORIZE_PATH);
$response = $controller->login(...$this->arguments($controller, self::AUTHORIZE_PATH, $session));
self::assertSame(200, $response->getStatusCode());
self::assertSame('security/login_oauth2.html.twig', $controller->renderedView);
self::assertSame(self::AUTHORIZE_PATH, $session->get('_security.main.target_path'));
}
public function testAHalfFinishedBookingStillWinsWhenThereIsNoAuthorization(): void
{
$controller = $this->createController(bookingDto: $this->createBookingDto());
$controller->clientManager->expects(self::never())->method('find');
$session = $this->createSession(null);
$response = $controller->login(...$this->arguments($controller, null, $session));
self::assertSame(200, $response->getStatusCode());
self::assertSame('booking/create/authenticate.html.twig', $controller->renderedView);
self::assertSame('/booking/create/step-1', $session->get('_security.main.target_path'));
}
/**
* @return array{AuthenticationUtils, Request, BookingSessionManager, BookingSummaryAssembler, ClientManagerInterface}
*/
private function arguments(TestableSecurityController $controller, ?string $targetPath, ?Session $session = null): array
{
$request = Request::create('/', 'GET');
$request->setSession($session ?? $this->createSession($targetPath));
return [
$controller->authenticationUtils,
$request,
$controller->bookingSessionManager,
$controller->summaryAssembler,
$controller->clientManager,
];
}
private function createSession(?string $targetPath): Session
{
$session = new Session(new MockArraySessionStorage());
if (null !== $targetPath) {
$session->set('_security.main.target_path', $targetPath);
}
return $session;
}
private function createBookingDto(): BookingDto
{
$travel = new Travel();
$travel->id = 123;
return new BookingDto($travel, 77);
}
private function createController(?BookingDto $bookingDto = null): TestableSecurityController
{
$authenticationUtils = $this->createStub(AuthenticationUtils::class);
$authenticationUtils->method('getLastAuthenticationError')->willReturn(null);
$authenticationUtils->method('getLastUsername')->willReturn('');
$bookingSessionManager = $this->createStub(BookingSessionManager::class);
$bookingSessionManager->method('getBookingDto')->willReturn($bookingDto);
return new TestableSecurityController(
$authenticationUtils,
$bookingSessionManager,
$this->createStub(BookingSummaryAssembler::class),
$this->createMock(ClientManagerInterface::class),
);
}
}
final class TestableSecurityController extends SecurityController
{
/**
* @var array<string, mixed>
*/
public array $renderedParameters = [];
public string $renderedView = '';
public function __construct(
public readonly AuthenticationUtils $authenticationUtils,
public readonly BookingSessionManager $bookingSessionManager,
public readonly BookingSummaryAssembler $summaryAssembler,
public readonly ClientManagerInterface $clientManager,
) {
}
protected function getUser(): ?UserInterface
{
return null;
}
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
$this->renderedView = $view;
$this->renderedParameters = $parameters;
return new Response('ok');
}
protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
return '/booking/create/step-1';
}
}
@@ -7,6 +7,7 @@ namespace App\Tests\Entity\Groups;
use App\Entity\Groups\AccommodationBooking;
use App\Enum\Groups\AccommodationBookingOrigin;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Exception\ImplausibleBookingPriceException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
@@ -87,6 +88,36 @@ class AccommodationBookingTest extends TestCase
}
}
public function testAnImplausibleTotalIsRefusedRatherThanStored(): void
{
// The pax count and the nights are capped, so what gets here is a catalog price with a
// digit too many. A stored total would end up on an offer; the INT column would answer
// it with SQLSTATE 22003 and say nothing about the cause.
$booking = new AccommodationBooking();
$booking->setDateFrom(new \DateTimeImmutable('2026-09-23'));
$booking->setDateTo(new \DateTimeImmutable('2026-09-25'));
$booking->setPaxCount(40);
$this->expectException(ImplausibleBookingPriceException::class);
$booking->setPriceSnapshot(['total' => AccommodationBooking::MAX_TOTAL_PRICE + 1], AccommodationBooking::MAX_TOTAL_PRICE + 1, 'EUR', 1);
}
public function testATotalAtTheCeilingIsStillStored(): void
{
$booking = new AccommodationBooking();
$booking->setPriceSnapshot(['total' => AccommodationBooking::MAX_TOTAL_PRICE], AccommodationBooking::MAX_TOTAL_PRICE, 'EUR', 1);
self::assertSame(AccommodationBooking::MAX_TOTAL_PRICE, $booking->getTotalPrice());
}
public function testTheCeilingLeavesTheIntColumnRoomToSpare(): void
{
// The ceiling exists to keep implausible prices out, not to use up the column: a total
// that needs more room than this is a mistake, never a wider column.
self::assertLessThan(2147483647, AccommodationBooking::MAX_TOTAL_PRICE);
}
public function testTheLabelIsIndependentOfWhereTheBookingCameFrom(): void
{
// Origin answers "how did this come about" and is deliberately not the same
@@ -109,6 +109,60 @@ class AccommodationBookingTypeTest extends TestCase
self::assertCount(0, $this->validate($booking, ['Default']));
}
/**
* The overflow this guards against reached production as an out-of-range write on
* total_price: every figure in the breakdown is multiplied by the pax count and the
* nights, so an implausible input for either produces an implausible total.
*/
public function testADepartureBeforeTheArrivalIsRejected(): void
{
$booking = $this->bookingFor('2026-09-23', '2026-09-20', 30);
$violations = $this->validate($booking, ['Default']);
self::assertCount(1, $violations);
self::assertSame('dateTo', $violations[0]->getPropertyPath());
}
public function testAMistypedYearIsRejectedRatherThanPriced(): void
{
// 2226 instead of 2026 — one wrong digit, 200 years of running costs.
$booking = $this->bookingFor('2026-09-23', '2226-09-25', 30);
$violations = $this->validate($booking, ['Default']);
self::assertCount(1, $violations);
self::assertSame('dateTo', $violations[0]->getPropertyPath());
}
public function testAnImplausiblePaxCountIsRejected(): void
{
$booking = $this->bookingFor('2026-09-23', '2026-09-25', AccommodationBooking::MAX_PAX + 1);
$violations = $this->validate($booking, ['Default']);
self::assertCount(1, $violations);
self::assertSame('paxCount', $violations[0]->getPropertyPath());
}
public function testTheLargestBookingOnRecordStillPasses(): void
{
// 150 people for 18 nights: the ceilings must not get in the way of real business.
$booking = $this->bookingFor('2026-09-23', '2026-10-11', 150);
self::assertCount(0, $this->validate($booking, ['Default']));
}
private function bookingFor(string $dateFrom, string $dateTo, int $paxCount): AccommodationBooking
{
$booking = new AccommodationBooking();
$booking->setDateFrom(new \DateTimeImmutable($dateFrom));
$booking->setDateTo(new \DateTimeImmutable($dateTo));
$booking->setPaxCount($paxCount);
return $booking;
}
/**
* @return string[]
*/
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Tests\Form\Model;
use App\Entity\Groups\AccommodationBooking;
use App\Form\Model\AccommodationBookingDto;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validation;
class AccommodationBookingDtoTest extends TestCase
{
/**
* Step 2 is the screen the customer types the head count on, and the one that prices it.
* Bounding it only in step_3 left the figure to surface two steps later, as a booking that
* could not be stored.
*/
#[DataProvider('implausibleHeadCounts')]
public function testAnImplausibleHeadCountIsRejectedWhereItIsEntered(string $property, int $value): void
{
$dto = new AccommodationBookingDto();
$dto->{$property} = $value;
$properties = array_map(
static fn ($violation) => $violation->getPropertyPath(),
iterator_to_array($this->validate($dto, ['step_2'])),
);
self::assertContains($property, $properties);
}
/**
* @return iterable<string, array{string, int}>
*/
public static function implausibleHeadCounts(): iterable
{
yield 'pax above the ceiling' => ['paxCount', AccommodationBooking::MAX_PAX + 1];
yield 'pax below one' => ['paxCount', 0];
yield 'negative pax' => ['paxCount', -5];
yield 'minors above the ceiling' => ['minorsCount', AccommodationBooking::MAX_PAX + 1];
yield 'negative minors' => ['minorsCount', -1];
yield 'children above the ceiling' => ['childrenCount', AccommodationBooking::MAX_PAX + 1];
}
public function testAFullHouseStillPasses(): void
{
$dto = new AccommodationBookingDto();
$dto->paxCount = AccommodationBooking::MAX_PAX;
$dto->minorsCount = 4;
$dto->childrenCount = 60;
$dto->selectedBoardServiceId = 1;
self::assertCount(0, $this->validate($dto, ['step_2']));
}
/**
* @param string[] $groups
*/
private function validate(AccommodationBookingDto $dto, array $groups): ConstraintViolationListInterface
{
return Validation::createValidatorBuilder()
->enableAttributeMapping()
->getValidator()
->validate($dto, null, $groups);
}
}
@@ -12,6 +12,7 @@ use App\Entity\Groups\AccommodationPrice;
use App\Enum\Groups\AccommodationBookingOrigin;
use App\Enum\Groups\AccommodationBookingStatus;
use App\Enum\Groups\AdditionalServiceType;
use App\Exception\ImplausibleBookingPriceException;
use App\Form\Model\AccommodationBookingDto;
use App\Model\AccommodationBookingQueryParams;
use App\Repository\Groups\AccommodationPriceRepository;
@@ -65,6 +66,18 @@ class AccommodationBookingServiceTest extends TestCase
$service->initFromParams(new AccommodationBookingQueryParams('HOTEL', '2026-02-31', '2026-03-05'));
}
public function testApplyDatesRejectsAnImplausiblyLongStay(): void
{
// The customer picks from a calendar, so this is a hand-built URL rather than a typo —
// the cap is the same one the backoffice form enforces on the entity.
$service = $this->createServiceWithAccommodation();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('Der Aufenthalt darf höchstens %d Nächte umfassen.', AccommodationBooking::MAX_NIGHTS));
$service->applyDates(new AccommodationBookingDto(), '2026-02-28', '2226-03-01');
}
public function testIssueAccessLinkForDirectBookingSetsTimestampForDirectBooking(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);
@@ -962,6 +975,33 @@ class AccommodationBookingServiceTest extends TestCase
self::assertNull($booking->getTotalPrice(), 'the frozen price belonged to the old house');
}
public function testChangeAccommodationLeavesNothingHalfAppliedWhenTheNewHousePricesImplausibly(): void
{
// The swap and the dropped services are already on the managed entity by the time the
// price is computed, so a refusal has to put the row back rather than leave a booking
// sitting at a new house with no price.
$breakdown = ['total' => AccommodationBooking::MAX_TOTAL_PRICE + 1, 'currency' => 'EUR'];
$breakdownCalculator = $this->createStub(AccommodationBookingBreakdownCalculator::class);
$breakdownCalculator->method('computeCurrent')->willReturn($breakdown);
$breakdownCalculator->method('withDiscounts')
->willReturn($breakdown + ['discounts' => [], 'discountedTotal' => AccommodationBooking::MAX_TOTAL_PRICE + 1]);
$entityManager = $this->createMock(EntityManagerInterface::class);
$entityManager->expects(self::once())->method('refresh');
$entityManager->expects(self::never())->method('flush');
$service = $this->createServiceWithAccommodation(
entityManager: $entityManager,
breakdownCalculator: $breakdownCalculator,
);
$booking = $this->draftWithServices();
$this->expectException(ImplausibleBookingPriceException::class);
$service->changeAccommodation($booking, (new Accommodation())->setName('Berghaus')->setCalendarCode('BERG'));
}
public function testChangeAccommodationNoOpsForANonDraft(): void
{
$entityManager = $this->createMock(EntityManagerInterface::class);