Files
fewo-stommer/app/Pricing/PriceCalculator.php
LarsandClaude Opus 5.5 3bcfc09417
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
- Paket 8: Zahlungsarten (Gast an uns, laut Portal, Auszahlung, Erstattung),
  Portalbeträge als Angaben mit Quelle, Übersicht nach Zuständigkeit (R09).
- Paket 5: Ändern mit Folgenvorschau, vereinbart oder dem Gast vorgeschlagen
  (signierter Link), ein Stornoweg mit Grund und Erstattung, Portalstorno erst
  nach Bestätigung.
- Paket 6: eigene Nutzung, Besuch und Sperre als Vorgang mit Kurabgabe und
  Aufenthaltsbestätigung; Bestandsübernahme der Sperren mit identischem Export.
- Wirksame Einstellungen (Expertenansicht), Abnahmekatalog T01–T14, Ergebnis-,
  Abnahme- und Konfigurationsdokument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:16:47 +01:00

233 lines
9.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Pricing;
use App\Availability\GapFinder;
use App\Enums\ExtraPricing;
use App\Enums\OfferKind;
use App\Enums\QuoteLineType;
use App\Models\Extra;
use App\Models\Property;
use App\Models\Season;
use App\Models\SpecialOffer;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
class PriceCalculator
{
public function __construct(private GapFinder $gaps = new GapFinder) {}
/**
* Price a stay. Special offers are applied automatically; $bookedAt (default: now) decides
* time-dependent offers such as last minute or early bird.
*
* @throws QuoteException
*/
public function calculate(Property $property, StayRequest $stay, ?CarbonImmutable $bookedAt = null): PriceQuote
{
if ($stay->departure->lessThanOrEqualTo($stay->arrival)) {
throw QuoteException::invalidPeriod();
}
if ($stay->guests < 1 || $stay->guests > $property->max_guests) {
throw QuoteException::invalidGuestCount($property->max_guests);
}
$nights = $stay->nights();
$nightSeasons = $this->seasonPerNight($property, $stay);
$bookedAt ??= CarbonImmutable::now();
$offers = $this->applicableOffers($property, $stay, $nightSeasons, $bookedAt);
$arrivalSeason = $nightSeasons[0];
if ($nights < $arrivalSeason->min_nights && ! $this->minimumStayRelaxed($property, $stay, $offers)) {
throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name);
}
$lines = $this->accommodationLines($nightSeasons);
$appliedOffers = $this->bestOffers($offers, $nightSeasons);
foreach ($appliedOffers as ['offer' => $offer, 'discount' => $discount]) {
$lines[] = new QuoteLine(QuoteLineType::Discount, $offer->name, 1, -$discount, -$discount);
}
$extraGuests = max(0, $stay->guests - $property->included_guests);
if ($extraGuests > 0 && $property->extra_guest_fee_per_night > 0) {
$lines[] = new QuoteLine(
QuoteLineType::ExtraGuest,
"Zusätzliche Person ({$extraGuests} × {$nights} Nächte)",
$extraGuests * $nights,
$property->extra_guest_fee_per_night,
$extraGuests * $nights * $property->extra_guest_fee_per_night,
);
}
if ($property->cleaning_fee > 0) {
$lines[] = new QuoteLine(QuoteLineType::Cleaning, 'Endreinigung & Service', 1, $property->cleaning_fee, $property->cleaning_fee);
}
array_push($lines, ...$this->extraLines($property, $stay->extras, $nights));
return new PriceQuote(
arrival: $stay->arrival,
departure: $stay->departure,
guests: $stay->guests,
lines: $lines,
depositPercent: $property->deposit_percent,
balanceDueOn: $stay->arrival->subDays($property->balance_due_days_before_arrival),
promoCodeApplied: $stay->promoCode === null ? null : collect($appliedOffers)->contains(fn (array $applied): bool => $applied['offer']->code !== null),
);
}
/**
* @return non-empty-list<Season>
*/
private function seasonPerNight(Property $property, StayRequest $stay): array
{
/** @var Collection<int, Season> $seasons */
$seasons = $property->seasons()->overlapping($stay->arrival, $stay->departure)->get();
$nightSeasons = [];
for ($night = $stay->arrival; $night->lessThan($stay->departure); $night = $night->addDay()) {
$nightSeasons[] = $seasons->first(fn (Season $season): bool => $season->containsNight($night))
?? throw QuoteException::noRateForNight($night);
}
return $nightSeasons;
}
/**
* One line per consecutive run of nights in the same season.
*
* @param non-empty-list<Season> $nightSeasons
* @return list<QuoteLine>
*/
private function accommodationLines(array $nightSeasons): array
{
/** @var list<array{season: Season, nights: int}> $runs */
$runs = [];
foreach ($nightSeasons as $season) {
$lastRun = array_key_last($runs);
if ($lastRun !== null && $runs[$lastRun]['season']->is($season)) {
$runs[$lastRun]['nights']++;
} else {
$runs[] = ['season' => $season, 'nights' => 1];
}
}
return array_map(fn (array $run): QuoteLine => new QuoteLine(
QuoteLineType::Accommodation,
"{$run['season']->name} ({$run['nights']} ".($run['nights'] === 1 ? 'Nacht' : 'Nächte').')',
$run['nights'],
$run['season']->nightly_rate,
$run['nights'] * $run['season']->nightly_rate,
), $runs);
}
/**
* Whether a stay shorter than the season's minimum is still allowed: an applicable offer waives it, or –
* never below the property's absolute minimum – the stay fills a calendar gap completely, or it ends on the
* typical changeover day (so the following week stays bookable).
*
* @param Collection<int, SpecialOffer> $offers
*/
private function minimumStayRelaxed(Property $property, StayRequest $stay, Collection $offers): bool
{
if ($offers->contains(fn (SpecialOffer $offer): bool => $offer->waives_min_stay)) {
return true;
}
if ($stay->nights() < max(1, (int) $property->min_stay_absolute)) {
return false;
}
if ($property->min_stay_until_changeover && $property->changeover_weekday !== null && $stay->departure->isoWeekday() === $property->changeover_weekday) {
return true;
}
return $property->min_stay_fill_gaps && $this->gaps->gapContaining($property, $stay->arrival, $stay->departure) === $stay->nights();
}
/**
* Active offers whose conditions the stay meets. The calendar gap is only looked up if a gap filler exists.
*
* @param non-empty-list<Season> $nightSeasons
* @return Collection<int, SpecialOffer>
*/
private function applicableOffers(Property $property, StayRequest $stay, array $nightSeasons, CarbonImmutable $bookedAt): Collection
{
$offers = $property->specialOffers()->active()->get();
$gapNights = $offers->contains(fn (SpecialOffer $offer): bool => $offer->kind === OfferKind::GapFiller)
? $this->gaps->gapContaining($property, $stay->arrival, $stay->departure)
: null;
return $offers->filter(fn (SpecialOffer $offer): bool => $offer->appliesTo($stay, $nightSeasons[0]->name, $bookedAt, $gapNights))->values();
}
/**
* The guest gets whichever is cheaper for them: the single best non-combinable offer,
* or all combinable offers together (capped at the accommodation price).
*
* @param Collection<int, SpecialOffer> $offers
* @param non-empty-list<Season> $nightSeasons
* @return list<array{offer: SpecialOffer, discount: int}>
*/
private function bestOffers(Collection $offers, array $nightSeasons): array
{
$nightlyRates = array_map(fn (Season $season): int => $season->nightly_rate, $nightSeasons);
$accommodation = array_sum($nightlyRates);
$candidates = $offers
->map(fn (SpecialOffer $offer): array => ['offer' => $offer, 'discount' => $offer->discountFor($nightlyRates)])
->filter(fn (array $candidate): bool => $candidate['discount'] > 0);
[$combinable, $exclusive] = $candidates->partition(fn (array $candidate): bool => $candidate['offer']->is_combinable);
$bestExclusive = $exclusive->sortByDesc('discount')->first();
$combined = [];
$remaining = $accommodation;
foreach ($combinable->sortByDesc('discount') as $candidate) {
$discount = min($candidate['discount'], $remaining);
if ($discount > 0) {
$combined[] = ['offer' => $candidate['offer'], 'discount' => $discount];
$remaining -= $discount;
}
}
$combinedTotal = $accommodation - $remaining;
if ($bestExclusive !== null && $bestExclusive['discount'] >= $combinedTotal) {
return [$bestExclusive];
}
return $combined;
}
/**
* @param array<int, int> $extraQuantities
* @return list<QuoteLine>
*/
public function extraLines(Property $property, array $extraQuantities, int $nights): array
{
$extraQuantities = array_filter($extraQuantities, fn (int $quantity): bool => $quantity > 0);
if ($extraQuantities === []) {
return [];
}
$extras = $property->extras()->active()->whereKey(array_keys($extraQuantities))->get()->keyBy('id');
$lines = [];
foreach ($extraQuantities as $extraId => $quantity) {
/** @var Extra $extra */
$extra = $extras->get($extraId) ?? throw QuoteException::unknownExtra($extraId);
$units = $extra->pricing === ExtraPricing::PerNight ? $quantity * $nights : $quantity;
$lines[] = new QuoteLine(QuoteLineType::Extra, $extra->name, $units, $extra->price, $units * $extra->price);
}
return $lines;
}
}