Files
fewo-stommer/app/Pricing/PriceCalculator.php
T
Lars StommerandClaude Opus 5.5 08b6582fa1 Phase 2: Kalender, Anfrage, Vorreservierung & Sonderangebote
- Gäste, Buchungen (Status-Workflow), Sperrzeiten, Sonderangebote
- Vorreservierung mit Haltezeit je Wohnung; abgelaufene Holds geben den Kalender sofort frei, Cron setzt Status und benachrichtigt
- Sonderangebote/Sonderkonditionen: %, € pro Aufenthalt, Sonderpreis/Nacht, Gratis-Nächte; Bedingungen u. a. Saison, Vorlauf, Wochentag, Nächte, Aktionscode; bestes Einzel- vs. kombinierte Angebote
- Öffentliche Seite /buchen: Belegungskalender, Live-Preis, Anfrageformular (Honeypot, Rate-Limit)
- E-Mails: Angebot an Gast, Benachrichtigung Vermieter, Bestätigung, Absage, Ablauf
- Filament: Anfragen & Buchungen (bestätigen, ablehnen, verlängern, stornieren, Telefonbuchung), Gäste, Sperrzeiten, Sonderangebote
- Deutsche Validierungstexte

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:43:12 +02:00

185 lines
7.1 KiB
PHP
Raw 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\Enums\ExtraPricing;
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
{
/**
* 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);
$arrivalSeason = $nightSeasons[0];
if ($nights < $arrivalSeason->min_nights) {
throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name);
}
$lines = $this->accommodationLines($nightSeasons);
$appliedOffers = $this->bestOffers($property, $stay, $nightSeasons, $bookedAt ?? CarbonImmutable::now());
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);
}
/**
* 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 non-empty-list<Season> $nightSeasons
* @return list<array{offer: SpecialOffer, discount: int}>
*/
private function bestOffers(Property $property, StayRequest $stay, array $nightSeasons, CarbonImmutable $bookedAt): array
{
$nightlyRates = array_map(fn (Season $season): int => $season->nightly_rate, $nightSeasons);
$accommodation = array_sum($nightlyRates);
$candidates = $property->specialOffers()->active()->get()
->filter(fn (SpecialOffer $offer): bool => $offer->appliesTo($stay, $nightSeasons[0]->name, $bookedAt))
->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>
*/
private 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;
}
}