fix: refuse implausible accommodation booking prices

This commit is contained in:
fromme committed 2026-09-26 15:39:04 +02:00
1 parent 773cd4f847
commit 56adf72d12
16 files changed
+628 -15

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;
}
}
+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();
}