wip: refactored price overrides

This commit is contained in:
Björn Fromme committed 2026-07-16 17:13:15 +02:00
1 parent f8e4fe4d1e
commit eba1a901d6
13 files changed
+668 -118

No files matched your search

+68 -18
View File
@@ -7,7 +7,10 @@ namespace App\Controller\Api;
use App\BpnConnect\ContingentsClient;
use App\BpnConnect\Exception\BpnConnectException;
use App\Entity\Groups\AccommodationPrice;
use App\Enum\Groups\PriceType;
use App\Repository\Groups\AccommodationPriceRepository;
use App\Repository\Groups\AccommodationRepository;
use App\Service\PriceTimelineBuilder;
use Psr\Cache\InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -24,11 +27,44 @@ class ContingentController extends AbstractController
{
public function __construct(
private readonly ContingentsClient $contingentsClient,
private readonly AccommodationRepository $accommodationRepository,
private readonly AccommodationPriceRepository $priceRepository,
private readonly CacheInterface $cache,
private readonly PriceTimelineBuilder $priceTimelineBuilder,
) {
}
#[Route(path: '/contingents/prices', name: 'api_contingents_prices', methods: ['GET'])]
public function prices(Request $request): JsonResponse
{
$hotelCode = $request->query->get('hotelCode');
$yearRaw = $request->query->get('year');
if (!$hotelCode || !$yearRaw) {
return $this->json(['error' => 'hotelCode and year are required.'], Response::HTTP_BAD_REQUEST);
}
if (!preg_match('/^\d{4}$/', $yearRaw)) {
return $this->json(['error' => 'year must be a 4-digit integer.'], Response::HTTP_BAD_REQUEST);
}
$accommodation = $this->accommodationRepository->findOneBy(['calendarCode' => $hotelCode]);
if (null === $accommodation) {
return $this->json(['error' => 'hotel not found for hotelCode.'], Response::HTTP_BAD_REQUEST);
}
$year = (int) $yearRaw;
$yearStart = new \DateTimeImmutable("{$year}-01-01");
$yearEnd = new \DateTimeImmutable("{$year}-12-31");
$prices = $this->priceRepository->findByHotelCodeAndDateRange($hotelCode, $yearStart, $yearEnd);
$currency = $accommodation->getCurrency();
return $this->json($this->priceTimelineBuilder->buildTimeline($prices, $yearStart, $yearEnd, $currency));
}
#[Route(path: '/contingents/calendar', name: 'api_contingents_calendar', methods: ['GET'])]
public function calendar(Request $request): JsonResponse
{
@@ -47,6 +83,12 @@ class ContingentController extends AbstractController
return $this->json(['error' => 'dateFrom and dateTo must be in Y-m-d format.'], Response::HTTP_BAD_REQUEST);
}
$accommodation = $this->accommodationRepository->findOneBy(['calendarCode' => $hotelCode]);
if (null === $accommodation) {
return $this->json(['error' => 'hotel not found for hotelCode.'], Response::HTTP_BAD_REQUEST);
}
try {
$cacheKey = sprintf('contingents_calendar_%s_%s_%s', $hotelCode, $dateFromRaw, $dateToRaw);
$calendar = $this->cache->get($cacheKey, function (ItemInterface $item) use ($hotelCode, $dateFromRaw, $dateToRaw) {
@@ -60,8 +102,10 @@ class ContingentController extends AbstractController
$prices = $this->priceRepository->findByHotelCodeAndDateRange($hotelCode, $dateFrom, $dateTo);
$currency = $accommodation->getCurrency();
$data = array_map(
fn ($entry) => $this->enrichEntry($entry->date, $entry->status->value, $prices),
fn ($entry) => $this->enrichEntry($entry->date, $entry->status->value, $prices, $currency),
$calendar->data,
);
@@ -70,33 +114,39 @@ class ContingentController extends AbstractController
/**
* @param AccommodationPrice[] $prices
* @return array{date: string, status: string, pricePerNight: float|null, pricePerNightOverride: float|null, includedPax: int|null}
* @return array{date: string, status: string, type: string|null, pricePerNight: float|null, defaultPricePerNight: float|null, priceAdditionalPerson: float|null, defaultPriceAdditionalPerson: float|null, includedPax: int|null, minPax: int|null, minNights: int|null}
*/
private function enrichEntry(string $date, string $status, array $prices): array
private function enrichEntry(string $date, string $status, array $prices, string $currency): array
{
$day = (new \DateTimeImmutable($date))->setTime(0, 0);
$price = null;
foreach ($prices as $candidate) {
if ($candidate->getDateFrom() > $day || $candidate->getDateTo() < $day) {
continue;
}
// dateFrom and dateTo are both inclusive (last night, not checkout day)
$candidates = array_filter(
$prices,
fn($p) => $p->getDateFrom() <= $day && $p->getDateTo() >= $day,
);
if (null === $price || $candidate->getDateFrom() > $price->getDateFrom()) {
$price = $candidate;
}
$winner = $this->priceTimelineBuilder->resolveWinner($candidates);
$defaultPrice = null;
if ($winner?->getType() === PriceType::DISCOUNT) {
$defaults = array_filter($candidates, fn($p) => $p->getType() === null);
$defaultPrice = $this->priceTimelineBuilder->resolveWinner($defaults);
}
return [
'date' => $date,
'status' => $status,
'pricePerNight' => null !== $price ? round($price->getPricePerNight() / 100, 2) : null,
'pricePerNightOverride' => null !== $price?->getPricePerNightOverride() ? round($price->getPricePerNightOverride() / 100, 2) : null,
'priceAdditionalPerson' => null !== $price ? round($price->getPriceAdditionalPerson() / 100, 2) : null,
'priceAdditionalPersonOverride' => null !== $price?->getPriceAdditionalPersonOverride() ? round($price->getPriceAdditionalPersonOverride() / 100, 2) : null,
'includedPax' => $price?->getIncludedPax(),
'minPax' => $price?->getAccommodation()->getMinPaxSummer(),
'minNights' => $price?->getMinNights(),
'type' => $winner?->getType()?->value,
'pricePerNight' => $winner !== null ? round($winner->getPricePerNight() / 100, 2) : null,
'defaultPricePerNight' => $defaultPrice !== null ? round($defaultPrice->getPricePerNight() / 100, 2) : null,
'priceAdditionalPerson' => $winner !== null ? round($winner->getPriceAdditionalPerson() / 100, 2) : null,
'defaultPriceAdditionalPerson' => $defaultPrice !== null ? round($defaultPrice->getPriceAdditionalPerson() / 100, 2) : null,
'currency' => $currency,
'includedPax' => $winner?->getIncludedPax(),
'minPax' => $winner?->getAccommodation()->getMinPaxSummer(),
'minNights' => $winner?->getMinNights(),
];
}
}
+8 -31
View File
@@ -6,6 +6,7 @@ use App\Entity\BlameableEntity;
use App\Entity\BlameableEntityInterface;
use App\Entity\TimestampableEntity;
use App\Entity\TimestampableEntityInterface;
use App\Enum\Groups\PriceType;
use App\Enum\Groups\Season;
use App\Repository\Groups\AccommodationPriceRepository;
use Doctrine\DBAL\Types\Types;
@@ -31,6 +32,7 @@ class AccommodationPrice implements BlameableEntityInterface, TimestampableEntit
#[Assert\NotNull(message: 'required')]
private ?\DateTimeImmutable $dateFrom = null;
// Inclusive: the last night this price applies. A booking 01.01.–10.01. covers 9 nights (01.01.–09.01.); 10.01. is checkout.
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
#[Assert\NotNull(message: 'required')]
#[Assert\GreaterThan(propertyPath: 'dateFrom', message: 'Das Bis-Datum muss nach dem Von-Datum liegen')]
@@ -55,11 +57,8 @@ class AccommodationPrice implements BlameableEntityInterface, TimestampableEntit
#[Assert\NotNull(message: 'required')]
private ?int $minNights = null;
#[ORM\Column(nullable: true)]
private ?int $pricePerNightOverride = null;
#[ORM\Column(nullable: true)]
private ?int $priceAdditionalPersonOverride = null;
#[ORM\Column(length: 20, nullable: true, enumType: PriceType::class)]
private ?PriceType $type = null;
#[ORM\Column]
private bool $acceptUndersubscription = false;
@@ -170,40 +169,18 @@ class AccommodationPrice implements BlameableEntityInterface, TimestampableEntit
return $this;
}
public function getPricePerNightOverride(): ?int
public function getType(): ?PriceType
{
return $this->pricePerNightOverride;
return $this->type;
}
public function setPricePerNightOverride(?int $pricePerNightOverride): self
public function setType(?PriceType $type): self
{
$this->pricePerNightOverride = $pricePerNightOverride;
$this->type = $type;
return $this;
}
public function getEffectivePricePerNight(): int
{
return $this->pricePerNightOverride ?? $this->pricePerNight;
}
public function getPriceAdditionalPersonOverride(): ?int
{
return $this->priceAdditionalPersonOverride;
}
public function setPriceAdditionalPersonOverride(?int $priceAdditionalPersonOverride): self
{
$this->priceAdditionalPersonOverride = $priceAdditionalPersonOverride;
return $this;
}
public function getEffectivePriceAdditionalPerson(): int
{
return $this->priceAdditionalPersonOverride ?? $this->priceAdditionalPerson;
}
public function isAcceptUndersubscription(): bool
{
return $this->acceptUndersubscription;
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Enum\Groups;
enum PriceType: string
{
case OVERRIDE = 'override';
case DISCOUNT = 'discount';
public function priority(): int
{
return match($this) {
self::OVERRIDE => 1,
self::DISCOUNT => 2,
};
}
public function label(): string
{
return match($this) {
self::OVERRIDE => 'Override',
self::DISCOUNT => 'Rabatt',
};
}
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Form\Admin\Groups;
use App\Entity\Groups\AccommodationPrice;
use App\Enum\Groups\PriceType;
use App\Enum\Groups\Season;
use App\Form\DatepickerType;
use Symfony\Component\Form\AbstractType;
@@ -30,6 +31,13 @@ class AccommodationPriceType extends AbstractType
'html5' => true,
'widget' => 'single_text',
])
->add('type', EnumType::class, [
'label' => 'Typ',
'class' => PriceType::class,
'required' => false,
'placeholder' => 'Standard',
'choice_label' => fn($item) => $item->label(),
])
->add('season', EnumType::class, [
'label' => 'Saison',
'class' => Season::class,
@@ -46,23 +54,11 @@ class AccommodationPriceType extends AbstractType
'currency' => $options['currency'],
'divisor' => 100,
])
->add('pricePerNightOverride', MoneyType::class, [
'label' => 'Streich-Preis pro Nacht',
'required' => false,
'currency' => $options['currency'],
'divisor' => 100,
])
->add('priceAdditionalPerson', MoneyType::class, [
'label' => 'Preis weitere Person',
'currency' => $options['currency'],
'divisor' => 100,
])
->add('priceAdditionalPersonOverride', MoneyType::class, [
'label' => 'Streich-Preis weitere Person',
'required' => false,
'currency' => $options['currency'],
'divisor' => 100,
])
->add('acceptUndersubscription', CheckboxType::class, [
'label' => 'Unterbelegung akzeptieren',
'required' => false,
+159
View File
@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Entity\Groups\AccommodationPrice;
use App\Enum\Groups\PriceType;
class PriceTimelineBuilder
{
/**
* Builds a flat, non-overlapping timeline of effective price rows for the given year.
*
* Base price periods are split wherever an override or discount applies, so each
* returned row represents a contiguous date range with a single effective price.
* Periods with no price configured are omitted. Prices that start before or end after
* the queried year are clamped to its boundaries.
*
* The algorithm is an interval sweep:
* 1. Collect every dateFrom and (dateTo + 1 day) from all prices as boundary points,
* plus the year start and (yearEnd + 1 day). This ensures the sweep slices at
* every point where the set of active prices changes.
* 2. Walk adjacent boundary pairs [start, end). For each segment, find all prices
* active at `start` and resolve the winner via resolveWinner(), which prefers
* higher-priority types (DISCOUNT > OVERRIDE > base) and shorter/later periods
* on ties. When the winner is a DISCOUNT, resolveWinner() is called a second time
* on the null-type candidates to obtain the original base price, which is exposed
* as defaultPricePerNight / defaultPriceAdditionalPerson.
* 3. Consecutive segments whose winner AND default-price entity are both unchanged
* are merged into one row. Tracking the default-price entity separately prevents
* a DISCOUNT row from being incorrectly extended when the underlying base price
* changes mid-discount period. A gap (no winner) resets both trackers.
*
* @param AccommodationPrice[] $prices
*/
public function buildTimeline(
array $prices,
\DateTimeImmutable $yearStart,
\DateTimeImmutable $yearEnd,
string $currency,
): array {
if (empty($prices)) {
return [];
}
$yearEndNext = $yearEnd->modify('+1 day');
// Step 1: collect all boundary points, keyed by timestamp for deduplication.
$boundaries = [
$yearStart->getTimestamp() => $yearStart,
$yearEndNext->getTimestamp() => $yearEndNext,
];
foreach ($prices as $price) {
$from = $price->getDateFrom();
$toNext = $price->getDateTo()->modify('+1 day');
$boundaries[$from->getTimestamp()] = $from;
$boundaries[$toNext->getTimestamp()] = $toNext;
}
ksort($boundaries);
$boundaries = array_values($boundaries);
$rows = [];
$lastWinner = null;
$lastDefault = null;
// Step 2: walk each segment [start, end) and resolve the effective price.
for ($i = 0, $count = count($boundaries) - 1; $i < $count; $i++) {
$segStart = $boundaries[$i];
$segEndNext = $boundaries[$i + 1];
// Boundaries from prices outside the year are included to correctly detect
// overlaps at the year edges, but the segments themselves are skipped.
if ($segStart < $yearStart || $segStart >= $yearEndNext) {
continue;
}
$candidates = array_filter(
$prices,
fn($p) => $p->getDateFrom() <= $segStart && $p->getDateTo() >= $segStart,
);
$winner = $this->resolveWinner($candidates);
if ($winner === null) {
// Gap: reset merge state so the next winner always opens a new row.
$lastWinner = null;
$lastDefault = null;
continue;
}
$defaultWinner = null;
if ($winner->getType() === PriceType::DISCOUNT) {
$defaults = array_filter($candidates, fn($p) => $p->getType() === null);
$defaultWinner = $this->resolveWinner($defaults);
}
$segDateTo = $segEndNext->modify('-1 day');
// Step 3: extend the previous row if both the winner and the default-price entity
// are unchanged; otherwise open a new row.
if ($lastWinner === $winner && $lastDefault === $defaultWinner) {
$rows[count($rows) - 1]['dateTo'] = $segDateTo->format('Y-m-d');
} else {
$rows[] = [
'dateFrom' => $segStart->format('Y-m-d'),
'dateTo' => $segDateTo->format('Y-m-d'),
'season' => $winner->getSeason()?->value,
'includedPax' => $winner->getIncludedPax(),
'pricePerNight' => round($winner->getPricePerNight() / 100, 2),
'priceAdditionalPerson' => round($winner->getPriceAdditionalPerson() / 100, 2),
'defaultPricePerNight' => $defaultWinner !== null ? round($defaultWinner->getPricePerNight() / 100, 2) : null,
'defaultPriceAdditionalPerson' => $defaultWinner !== null ? round($defaultWinner->getPriceAdditionalPerson() / 100, 2) : null,
'currency' => $currency,
'type' => $winner->getType()?->value,
];
$lastWinner = $winner;
$lastDefault = $defaultWinner;
}
}
return $rows;
}
/**
* Resolves which price entity wins for a set of candidates active at the same point in time.
*
* Higher-priority types win: DISCOUNT (2) > OVERRIDE (1) > base/null (0).
* Ties within the same type are broken by preferring the shorter period, then the later start date.
*
* @param AccommodationPrice[] $candidates
*/
public function resolveWinner(array $candidates): ?AccommodationPrice
{
$winner = null;
foreach ($candidates as $candidate) {
if ($winner === null) {
$winner = $candidate;
continue;
}
$cp = $candidate->getType()?->priority() ?? 0;
$wp = $winner->getType()?->priority() ?? 0;
if ($cp > $wp) {
$winner = $candidate;
continue;
}
if ($cp === $wp) {
$cs = $candidate->getDateFrom()->diff($candidate->getDateTo())->days;
$ws = $winner->getDateFrom()->diff($winner->getDateTo())->days;
if ($cs < $ws || ($cs === $ws && $candidate->getDateFrom() > $winner->getDateFrom())) {
$winner = $candidate;
}
}
}
return $winner;
}
}
+9 -3
View File
@@ -172,19 +172,25 @@ class Calendar
continue;
}
$priceFormatted = number_format($price->getEffectivePricePerNight() / 100, 2, ',', '.') . ' €';
$priceFormatted = number_format($price->getPricePerNight() / 100, 2, ',', '.') . ' €';
$label = sprintf('Preis: %s/Nacht (min. %d Nächte)', $priceFormatted, $price->getMinNights());
$day = CarbonImmutable::instance($price->getDateFrom());
$end = CarbonImmutable::instance($price->getDateTo());
$span = $day->diffInDays($end);
$priority = $price->getType()?->priority() ?? 0;
$limit = $day->addYears(3);
// $end is the last night (inclusive), so <= is correct
while ($day <= $end && $day <= $limit) {
$key = $day->format('Y-m-d');
$map[$key] ??= ['price' => null, 'board' => null, 'additional' => null];
if ($map[$key]['price'] === null || $span < $map[$key]['price']['span']) {
$map[$key]['price'] = ['label' => $label, 'span' => $span];
$existing = $map[$key]['price'];
$replace = $existing === null
|| $priority > $existing['priority']
|| ($priority === $existing['priority'] && $span < $existing['span']);
if ($replace) {
$map[$key]['price'] = ['label' => $label, 'span' => $span, 'priority' => $priority];
}
$day = $day->addDay();
}