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>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 09:43:12 +02:00
1 parent 2e9a391b37
commit 08b6582fa1
79 files changed
+6213 -76

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingConfirmed;
use App\Models\Booking;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free.
*/
class ConfirmBooking
{
public function __construct(private AvailabilityChecker $availability) {}
/**
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true): void
{
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
}
DB::transaction(function () use ($booking): void {
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$booking->update([
'status' => BookingStatus::Confirmed,
'hold_expires_at' => null,
'confirmed_at' => now(),
]);
});
if ($notifyGuest) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
}
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\NewReservation;
use App\Mail\ReservationReceived;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Turns a guest request into a reservation that holds the dates for the property's hold time,
* and sends the quote to the guest and a notification to the landlord.
*/
class CreateReservation
{
public function __construct(
private PriceCalculator $calculator,
private AvailabilityChecker $availability,
) {}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
throw ReservationException::notAvailable();
}
$quote = $this->calculator->calculate($property, $stay);
$guest = Guest::firstOrNew(['email' => mb_strtolower($guestData['email'])]);
$guest->fill($guestData)->fill(['email' => mb_strtolower($guestData['email'])])->save();
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
'guests' => $stay->guests,
'extras' => array_filter($stay->extras),
'promo_code' => $quote->promoCodeApplied ? $stay->promoCode : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => now()->addHours($property->hold_hours),
'message' => $message,
]);
});
if ($sendMails) {
$this->sendMails($booking);
}
return $booking;
}
/**
* A failing mail server must not lose the reservation; failures are reported and visible in the log.
*/
private function sendMails(Booking $booking): void
{
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
Mail::to(config('fewo.notification_email'))->send(new NewReservation($booking));
} catch (Throwable $exception) {
report($exception);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingDeclined;
use App\Models\Booking;
use Illuminate\Support\Facades\Mail;
class DeclineBooking
{
/**
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true): void
{
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
}
$booking->update([
'status' => BookingStatus::Declined,
'hold_expires_at' => null,
]);
if ($notifyGuest) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingDeclined($booking));
}
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Mail\ReservationExpired;
use App\Models\Booking;
use Illuminate\Support\Facades\Mail;
/**
* Marks reservations whose hold time is over as expired and tells the landlord.
* The calendar already treats them as free once the hold time is over; this only updates the status.
*/
class ExpireReservations
{
public function handle(): int
{
$expired = Booking::query()
->where('status', BookingStatus::Reserved)
->where('hold_expires_at', '<=', now())
->with(['guest', 'property'])
->get();
foreach ($expired as $booking) {
$booking->update(['status' => BookingStatus::Expired]);
Mail::to(config('fewo.notification_email'))->send(new ReservationExpired($booking));
}
return $expired->count();
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Availability;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* Works on nights: a stay from $from to $until occupies the nights $from … $until - 1 day,
* so changeover days (departure and arrival on the same day) are possible.
*/
class AvailabilityChecker
{
public function isAvailable(Property $property, CarbonImmutable $from, CarbonImmutable $until, ?Booking $ignore = null): bool
{
$bookingConflict = $property->bookings()
->occupying()
->overlapping($from, $until)
->when($ignore, fn ($query) => $query->whereKeyNot($ignore->getKey()))
->exists();
return ! $bookingConflict && ! $property->blockedPeriods()->overlapping($from, $until)->exists();
}
/**
* Occupied nights within [$from, $until) as a set of 'Y-m-d' strings.
*
* @return array<string, true>
*/
public function occupiedNights(Property $property, CarbonImmutable $from, CarbonImmutable $until): array
{
$periods = $property->bookings()->occupying()->overlapping($from, $until)->get(['arrival', 'departure'])
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
->concat($property->blockedPeriods()->overlapping($from, $until)->get(['starts_on', 'ends_on'])
->map(fn (BlockedPeriod $period): array => [$period->starts_on, $period->ends_on]));
$nights = [];
foreach ($periods as [$start, $end]) {
for ($night = $start->max($from); $night->lessThan($end) && $night->lessThan($until); $night = $night->addDay()) {
$nights[$night->toDateString()] = true;
}
}
return $nights;
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Console\Commands;
use App\Actions\ExpireReservations;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('bookings:expire-holds')]
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord')]
class ExpireReservationHolds extends Command
{
/**
* Execute the console command.
*/
public function handle(ExpireReservations $expireReservations): int
{
$count = $expireReservations->handle();
$this->info("{$count} Vormerkung(en) abgelaufen.");
return self::SUCCESS;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum BookingStatus: string implements HasColor, HasLabel
{
/** Guest request; the dates are held until hold_expires_at. */
case Reserved = 'reserved';
case Confirmed = 'confirmed';
case DepositPaid = 'deposit_paid';
case Paid = 'paid';
case Completed = 'completed';
case Declined = 'declined';
case Expired = 'expired';
case Cancelled = 'cancelled';
public function getLabel(): string
{
return match ($this) {
self::Reserved => 'Vorreserviert',
self::Confirmed => 'Bestätigt',
self::DepositPaid => 'Anzahlung erhalten',
self::Paid => 'Bezahlt',
self::Completed => 'Abgeschlossen',
self::Declined => 'Abgelehnt',
self::Expired => 'Abgelaufen',
self::Cancelled => 'Storniert',
};
}
public function getColor(): string
{
return match ($this) {
self::Reserved => 'warning',
self::Confirmed, self::DepositPaid => 'info',
self::Paid, self::Completed => 'success',
self::Declined, self::Expired, self::Cancelled => 'gray',
};
}
/**
* Statuses that occupy the calendar regardless of any hold time.
*
* @return list<self>
*/
public static function occupying(): array
{
return [self::Confirmed, self::DepositPaid, self::Paid, self::Completed];
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum DiscountType: string implements HasLabel
{
/** discount_value = percent of the accommodation price */
case Percent = 'percent';
/** discount_value = euro cents off the stay */
case AmountPerStay = 'amount_per_stay';
/** discount_value = special price per night in euro cents */
case NightlyRate = 'nightly_rate';
/** discount_value = number of cheapest nights that are free */
case FreeNights = 'free_nights';
public function getLabel(): string
{
return match ($this) {
self::Percent => 'Rabatt in %',
self::AmountPerStay => 'Rabatt in € pro Aufenthalt',
self::NightlyRate => 'Sonderpreis pro Nacht',
self::FreeNights => 'Gratis-Nächte',
};
}
}
+2 -1
View File
@@ -8,12 +8,13 @@ enum QuoteLineType: string
case ExtraGuest = 'extra_guest';
case Cleaning = 'cleaning';
case Extra = 'extra';
case Discount = 'discount';
/**
* Whether the line counts towards the rent on which the deposit is calculated.
*/
public function isRent(): bool
{
return in_array($this, [self::Accommodation, self::ExtraGuest], true);
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount], true);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Exceptions;
use RuntimeException;
/**
* A reservation or status change that is not possible. Messages are shown to guests and administrators.
*/
class ReservationException extends RuntimeException
{
public static function notAvailable(): self
{
return new self('Der gewünschte Zeitraum ist leider nicht mehr frei.');
}
public static function invalidTransition(string $statusLabel, string $action): self
{
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Filament\Resources\Bookings;
use App\Enums\BookingStatus;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ListBookings;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
use App\Filament\Resources\Bookings\Tables\BookingsTable;
use App\Models\Booking;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
class BookingResource extends Resource
{
protected static ?string $model = Booking::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
protected static ?string $modelLabel = 'Buchung';
protected static ?string $pluralModelLabel = 'Anfragen & Buchungen';
protected static ?string $recordTitleAttribute = 'reference';
protected static ?int $navigationSort = 1;
public static function form(Schema $schema): Schema
{
return BookingForm::configure($schema);
}
public static function infolist(Schema $schema): Schema
{
return BookingInfolist::configure($schema);
}
public static function table(Table $table): Table
{
return BookingsTable::configure($table);
}
/**
* Number of open requests waiting for a decision.
*/
public static function getNavigationBadge(): ?string
{
$open = Booking::query()->where('status', BookingStatus::Reserved)->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function getPages(): array
{
return [
'index' => ListBookings::route('/'),
'create' => CreateBooking::route('/create'),
'view' => ViewBooking::route('/{record}'),
];
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\ConfirmBooking;
use App\Actions\CreateReservation;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Property;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
class CreateBooking extends CreateRecord
{
protected static string $resource = BookingResource::class;
protected static ?string $title = 'Buchung erfassen';
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
try {
$booking = app(CreateReservation::class)->handle(
Property::findOrFail($data['property_id']),
new StayRequest(
CarbonImmutable::parse($data['arrival']),
CarbonImmutable::parse($data['departure']),
(int) $data['guests'],
promoCode: $data['promo_code'] ?: null,
),
Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']),
source: 'manual',
sendMails: $data['send_mails'],
);
if ($data['confirm_immediately']) {
app(ConfirmBooking::class)->handle($booking, notifyGuest: $data['send_mails']);
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Buchung nicht möglich')->body($exception->getMessage())->danger()->send();
$this->halt();
}
$booking->update(['internal_notes' => $data['internal_notes'] ?: null]);
return $booking;
}
protected function getRedirectUrl(): string
{
return BookingResource::getUrl('view', ['record' => $this->getRecord()]);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Bookings\Pages;
use App\Filament\Resources\Bookings\BookingResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListBookings extends ListRecords
{
protected static string $resource = BookingResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,115 @@
<?php
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Icons\Heroicon;
/**
* @property Booking $record
*/
class ViewBooking extends ViewRecord
{
protected static string $resource = BookingResource::class;
public function getTitle(): string
{
return "{$this->record->reference} · {$this->record->guest->full_name}";
}
protected function getHeaderActions(): array
{
return [
Action::make('confirm')
->label('Bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->color('success')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Buchung bestätigen')
->modalDescription('Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
->schema([
Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(true),
])
->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(
fn () => $confirm->handle($this->record, $data['notify']),
'Buchung bestätigt',
)),
Action::make('decline')
->label('Ablehnen')
->icon(Heroicon::OutlinedXCircle)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Anfrage ablehnen')
->schema([
Toggle::make('notify')->label('Absage an den Gast senden')->default(true),
])
->action(fn (array $data, DeclineBooking $decline) => $this->runWorkflow(
fn () => $decline->handle($this->record, $data['notify']),
'Anfrage abgelehnt',
)),
Action::make('extendHold')
->label('Vormerkung verlängern')
->icon(Heroicon::OutlinedClock)
->color('gray')
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved)
->schema([
TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required(),
])
->action(function (array $data): void {
$from = $this->record->hold_expires_at?->isFuture() ? $this->record->hold_expires_at : now()->toImmutable();
$this->record->update(['hold_expires_at' => $from->addHours((int) $data['hours'])]);
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
}),
ActionGroup::make([
Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->fillForm(fn (): array => ['internal_notes' => $this->record->internal_notes])
->schema([
Textarea::make('internal_notes')->label('Interne Notizen')->rows(6),
])
->action(fn (array $data) => $this->record->update($data)),
Action::make('cancel')
->label('Stornieren')
->icon(Heroicon::OutlinedNoSymbol)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
->requiresConfirmation()
->modalDescription('Der Zeitraum wird wieder freigegeben. Der Gast wird nicht automatisch benachrichtigt.')
->action(function (): void {
$this->record->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
Notification::make()->title('Buchung storniert')->success()->send();
}),
]),
];
}
private function runWorkflow(callable $workflow, string $successTitle): void
{
try {
$workflow();
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
Notification::make()->title($successTitle)->success()->send();
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Resources\Bookings\Schemas;
use App\Models\Property;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
/**
* Manual entry of a booking received by phone or e-mail. The price is calculated automatically.
*/
class BookingForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make('Aufenthalt')
->columns(2)
->schema([
Select::make('property_id')
->label('Wohnung')
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
->default(fn (): ?int => Property::query()->value('id'))
->required(),
TextInput::make('guests')
->label('Personen')
->integer()
->minValue(1)
->default(2)
->required(),
DatePicker::make('arrival')
->label('Anreise')
->required(),
DatePicker::make('departure')
->label('Abreise')
->after('arrival')
->required(),
TextInput::make('promo_code')
->label('Aktionscode'),
]),
Section::make('Gast')
->columns(2)
->schema([
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required()->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->required()->maxLength(255),
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('street')->label('Straße')->maxLength(255),
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
TextInput::make('city')->label('Ort')->maxLength(255),
]),
Section::make('Abschluss')
->schema([
Textarea::make('internal_notes')->label('Interne Notiz'),
Toggle::make('confirm_immediately')->label('Sofort verbindlich bestätigen')->default(true),
Toggle::make('send_mails')->label('E-Mails an den Gast senden')->default(false),
]),
]);
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Filament\Resources\Bookings\Schemas;
use App\Models\Booking;
use App\Support\Money;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class BookingInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(3)
->components([
Grid::make(1)
->columnSpan(2)
->schema([
Section::make('Aufenthalt')
->columns(3)
->schema([
TextEntry::make('property.name')->label('Wohnung'),
TextEntry::make('arrival')->label('Anreise')->date('l, d.m.Y'),
TextEntry::make('departure')->label('Abreise')->date('l, d.m.Y'),
TextEntry::make('nights')->label('Nächte')->state(fn (Booking $record): int => $record->nights()),
TextEntry::make('guests')->label('Personen'),
TextEntry::make('promo_code')->label('Aktionscode')->placeholder('–'),
]),
Section::make('Preis')
->schema([
RepeatableEntry::make('quote.lines')
->hiddenLabel()
->table([
TableColumn::make('Leistung'),
TableColumn::make('Betrag')->alignEnd(),
])
->schema([
TextEntry::make('label'),
TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(),
]),
Grid::make(4)->schema([
TextEntry::make('total')->label('Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->weight('bold'),
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
]),
]),
Section::make('Nachricht des Gastes')
->visible(fn (Booking $record): bool => filled($record->message))
->schema([
TextEntry::make('message')->hiddenLabel(),
]),
]),
Grid::make(1)
->columnSpan(1)
->schema([
Section::make('Status')
->schema([
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('hold_expires_at')->label('Vorgemerkt bis')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->hold_expires_at !== null),
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
TextEntry::make('source')->label('Quelle'),
]),
Section::make('Gast')
->schema([
TextEntry::make('guest.full_name')->label('Name'),
TextEntry::make('guest.email')->label('E-Mail')->copyable(),
TextEntry::make('guest.phone')->label('Telefon')->placeholder('–'),
TextEntry::make('guest_address')
->label('Adresse')
->state(fn (Booking $record): ?string => collect([$record->guest->street, trim("{$record->guest->postal_code} {$record->guest->city}")])->filter()->implode(', ') ?: null)
->placeholder('–'),
]),
Section::make('Interne Notizen')
->schema([
TextEntry::make('internal_notes')->hiddenLabel()->placeholder('Keine Notizen'),
]),
]),
]);
}
}
@@ -0,0 +1,71 @@
<?php
namespace App\Filament\Resources\Bookings\Tables;
use App\Enums\BookingStatus;
use App\Models\Booking;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class BookingsTable
{
public static function configure(Table $table): Table
{
return $table
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property']))
->defaultSort('created_at', 'desc')
->columns([
TextColumn::make('reference')
->label('Nr.')
->searchable(),
TextColumn::make('status')
->label('Status')
->badge()
->description(fn (Booking $record): ?string => $record->isHoldActive() ? 'bis '.$record->hold_expires_at->format('d.m. H:i') : null),
TextColumn::make('guest.last_name')
->label('Gast')
->formatStateUsing(fn (Booking $record): string => $record->guest->full_name)
->description(fn (Booking $record): string => $record->guest->email)
->searchable(['first_name', 'last_name', 'email']),
TextColumn::make('property.name')
->label('Wohnung')
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('arrival')
->label('Anreise')
->date('D, d.m.Y')
->sortable(),
TextColumn::make('departure')
->label('Abreise')
->date('D, d.m.Y')
->description(fn (Booking $record): string => $record->nights().' Nächte'),
TextColumn::make('guests')
->label('Pers.'),
TextColumn::make('total')
->label('Gesamt')
->money('EUR', divideBy: 100, locale: 'de'),
TextColumn::make('source')
->label('Quelle')
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('created_at')
->label('Eingang')
->since()
->sortable(),
])
->filters([
SelectFilter::make('status')
->label('Status')
->options(BookingStatus::class)
->multiple(),
Filter::make('upcoming')
->label('Nur kommende Aufenthalte')
->query(fn (Builder $query): Builder => $query->whereDate('departure', '>=', today())),
])
->recordActions([
ViewAction::make(),
]);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Filament\Resources\Guests;
use App\Filament\Resources\Guests\Pages\CreateGuest;
use App\Filament\Resources\Guests\Pages\EditGuest;
use App\Filament\Resources\Guests\Pages\ListGuests;
use App\Filament\Resources\Guests\Schemas\GuestForm;
use App\Filament\Resources\Guests\Tables\GuestsTable;
use App\Models\Guest;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
class GuestResource extends Resource
{
protected static ?string $model = Guest::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;
protected static ?string $modelLabel = 'Gast';
protected static ?string $pluralModelLabel = 'Gäste';
protected static ?string $recordTitleAttribute = 'last_name';
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
return GuestForm::configure($schema);
}
public static function table(Table $table): Table
{
return GuestsTable::configure($table);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => ListGuests::route('/'),
'create' => CreateGuest::route('/create'),
'edit' => EditGuest::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Guests\Pages;
use App\Filament\Resources\Guests\GuestResource;
use Filament\Resources\Pages\CreateRecord;
class CreateGuest extends CreateRecord
{
protected static string $resource = GuestResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Guests\Pages;
use App\Filament\Resources\Guests\GuestResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditGuest extends EditRecord
{
protected static string $resource = GuestResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Guests\Pages;
use App\Filament\Resources\Guests\GuestResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListGuests extends ListRecords
{
protected static string $resource = GuestResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Filament\Resources\Guests\Schemas;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
class GuestForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required()->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->required()->maxLength(255),
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('street')->label('Straße')->maxLength(255),
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
TextInput::make('city')->label('Ort')->maxLength(255),
Select::make('country')
->label('Land')
->options(['DE' => 'Deutschland', 'AT' => 'Österreich', 'CH' => 'Schweiz', 'NL' => 'Niederlande', 'DK' => 'Dänemark', 'PL' => 'Polen'])
->default('DE')
->required(),
Textarea::make('notes')->label('Notizen')->columnSpanFull(),
]);
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Filament\Resources\Guests\Tables;
use App\Models\Guest;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class GuestsTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('last_name')
->columns([
TextColumn::make('last_name')
->label('Name')
->formatStateUsing(fn (Guest $record): string => "{$record->last_name}, {$record->first_name}")
->searchable(['first_name', 'last_name'])
->sortable(),
TextColumn::make('email')->label('E-Mail')->searchable(),
TextColumn::make('phone')->label('Telefon')->placeholder('–'),
TextColumn::make('city')->label('Ort')->placeholder('–'),
TextColumn::make('bookings_count')->label('Buchungen')->counts('bookings')->sortable(),
TextColumn::make('created_at')->label('Seit')->date('m/Y')->sortable(),
])
->recordActions([
EditAction::make(),
]);
}
}
@@ -5,8 +5,10 @@
use App\Filament\Resources\Properties\Pages\CreateProperty;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\Pages\ListProperties;
use App\Filament\Resources\Properties\RelationManagers\BlockedPeriodsRelationManager;
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
use App\Filament\Resources\Properties\Schemas\PropertyForm;
use App\Filament\Resources\Properties\Tables\PropertiesTable;
use App\Models\Property;
@@ -42,7 +44,9 @@ public static function getRelations(): array
{
return [
SeasonsRelationManager::class,
SpecialOffersRelationManager::class,
ExtrasRelationManager::class,
BlockedPeriodsRelationManager::class,
];
}
@@ -0,0 +1,74 @@
<?php
namespace App\Filament\Resources\Properties\RelationManagers;
use App\Models\BlockedPeriod;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\TextInput;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class BlockedPeriodsRelationManager extends RelationManager
{
protected static string $relationship = 'blockedPeriods';
protected static ?string $title = 'Sperrzeiten';
protected static ?string $modelLabel = 'Sperrzeit';
protected static ?string $pluralModelLabel = 'Sperrzeiten';
public function form(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
DatePicker::make('starts_on')
->label('Von (erste gesperrte Nacht)')
->required(),
DatePicker::make('ends_on')
->label('Bis (erster freier Tag)')
->after('starts_on')
->required(),
TextInput::make('reason')
->label('Grund')
->placeholder('z. B. Eigennutzung, Renovierung')
->maxLength(255)
->columnSpanFull(),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('reason')
->description('Manuelle Sperren (z. B. Eigennutzung). Belegungen aus Portalen erscheinen hier später automatisch.')
->defaultSort('starts_on')
->columns([
TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y'),
TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'),
TextColumn::make('reason')->label('Grund')->placeholder('–'),
TextColumn::make('source')->label('Quelle'),
])
->filters([
Filter::make('upcoming')
->label('Nur kommende')
->default()
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
])
->headerActions([
CreateAction::make(),
])
->recordActions([
EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
]);
}
}
@@ -9,6 +9,8 @@
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Closure;
use Filament\Actions\Action;
@@ -30,7 +32,6 @@
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;
class SeasonsRelationManager extends RelationManager
{
@@ -224,29 +225,30 @@ private function priceCalculatorAction(): Action
->integer()
->minValue(1)
->default(2),
TextInput::make('promo_code')
->label('Aktionscode (optional)'),
])
->action(function (array $data, PriceCalculator $calculator): void {
try {
$quote = $calculator->calculate(
$this->getOwnerRecord(),
$quote = $calculator->calculate($this->getOwnerRecord(), new StayRequest(
CarbonImmutable::parse($data['arrival']),
CarbonImmutable::parse($data['departure']),
(int) $data['guests'],
);
promoCode: $data['promo_code'] ?? null,
));
} catch (QuoteException $exception) {
Notification::make()->title('Nicht buchbar')->body($exception->getMessage())->danger()->send();
return;
}
$euro = fn (int $cents): string => Number::currency($cents / 100, 'EUR', 'de');
$lines = collect($quote->lines)
->map(fn (QuoteLine $line): string => e($line->label).': '.$euro($line->amount))
->push('Anzahlung: '.$euro($quote->deposit()).' · Rest: '.$euro($quote->balance()).' fällig am '.$quote->balanceDueOn->format('d.m.Y'))
->map(fn (QuoteLine $line): string => e($line->label).': '.Money::format($line->amount))
->push('Anzahlung: '.Money::format($quote->deposit()).' · Rest: '.Money::format($quote->balance()).' fällig am '.$quote->balanceDueOn->format('d.m.Y'))
->implode('<br>');
Notification::make()
->title('Gesamtpreis: '.$euro($quote->total()))
->title('Gesamtpreis: '.Money::format($quote->total()))
->body($lines)
->success()
->persistent()
@@ -0,0 +1,164 @@
<?php
namespace App\Filament\Resources\Properties\RelationManagers;
use App\Enums\DiscountType;
use App\Models\SpecialOffer;
use App\Support\Money;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Actions\ReplicateAction;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class SpecialOffersRelationManager extends RelationManager
{
protected static string $relationship = 'specialOffers';
protected static ?string $title = 'Sonderangebote';
protected static ?string $modelLabel = 'Sonderangebot';
protected static ?string $pluralModelLabel = 'Sonderangebote';
public function form(Schema $schema): Schema
{
return $schema
->components([
Section::make('Angebot')
->columns(2)
->schema([
TextInput::make('name')
->label('Bezeichnung')
->helperText('Erscheint so in Angebot und Rechnung, z. B. „Last Minute“ oder „Special Weekend“.')
->required()
->maxLength(255),
TextInput::make('public_description')
->label('Kurzbeschreibung für die Webseite')
->maxLength(255),
Select::make('discount_type')
->label('Art')
->options(DiscountType::class)
->default(DiscountType::Percent)
->live()
->required(),
TextInput::make('discount_value')
->label(fn (Get $get): string => match ($this->discountType($get)) {
DiscountType::Percent => 'Rabatt',
DiscountType::AmountPerStay => 'Rabatt pro Aufenthalt',
DiscountType::NightlyRate => 'Sonderpreis pro Nacht',
DiscountType::FreeNights => 'Anzahl Gratis-Nächte',
})
->suffix(fn (Get $get): string => match ($this->discountType($get)) {
DiscountType::Percent => '%',
DiscountType::FreeNights => 'Nächte',
default => '€',
})
->helperText(fn (Get $get): ?string => $this->discountType($get) === DiscountType::FreeNights ? 'Die günstigsten Nächte des Aufenthalts sind gratis.' : null)
->numeric()
->minValue(0)
->required()
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $this->isMoney($record?->discount_type) ? number_format($state / 100, 2, '.', '') : $state)
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->isMoney($this->discountType($get)) ? (int) round((float) $state * 100) : (int) $state),
Toggle::make('is_active')->label('Aktiv')->default(true),
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
Toggle::make('is_combinable')
->label('Mit anderen kombinierbaren Angeboten kombinierbar')
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.')
->columnSpanFull(),
]),
Section::make('Bedingungen')
->description('Leere Felder bedeuten: keine Einschränkung.')
->columns(2)
->schema([
TextInput::make('code')
->label('Aktionscode (Sonderkondition)')
->helperText('Nur mit diesem Code gültig, z. B. für Stammgäste. Leer = gilt automatisch.')
->maxLength(50)
->columnSpanFull(),
CheckboxList::make('season_names')
->label('Nur bei Anreise in Saison')
->options(fn (): array => $this->getOwnerRecord()->seasons()->reorder('name')->distinct()->pluck('name', 'name')->all())
->columns(3)
->columnSpanFull(),
TextInput::make('max_days_before_arrival')
->label('Buchung höchstens … Tage vor Anreise')
->helperText('Last Minute, z. B. 14')
->integer()
->minValue(0),
TextInput::make('min_days_before_arrival')
->label('Buchung mindestens … Tage vor Anreise')
->helperText('Frühbucher, z. B. 180')
->integer()
->minValue(0),
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1),
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1),
CheckboxList::make('arrival_weekdays')
->label('Anreise nur am')
->options([1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'])
->columns(7)
->columnSpanFull(),
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab'),
DatePicker::make('stay_until')->label('Abreise spätestens am'),
DateTimePicker::make('bookable_from')->label('Buchbar ab')->seconds(false),
DateTimePicker::make('bookable_until')->label('Buchbar bis')->seconds(false),
]),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->description('Sonderangebote werden bei jeder Preisberechnung automatisch geprüft und angewendet.')
->columns([
TextColumn::make('name')
->label('Angebot')
->description(fn (SpecialOffer $record): ?string => $record->public_description),
TextColumn::make('discount')
->label('Vorteil')
->state(fn (SpecialOffer $record): string => match ($record->discount_type) {
DiscountType::Percent => "−{$record->discount_value} %",
DiscountType::AmountPerStay => '−'.Money::format($record->discount_value),
DiscountType::NightlyRate => Money::format($record->discount_value).' / Nacht',
DiscountType::FreeNights => "{$record->discount_value} Nacht/Nächte gratis",
}),
TextColumn::make('code')->label('Code')->placeholder('automatisch')->badge(),
TextColumn::make('season_names')->label('Saisons')->badge()->placeholder('alle'),
IconColumn::make('is_combinable')->label('Kombinierbar')->boolean(),
IconColumn::make('is_active')->label('Aktiv')->boolean(),
])
->headerActions([
CreateAction::make(),
])
->recordActions([
EditAction::make(),
ReplicateAction::make()->label('Duplizieren')->schema(fn (Schema $schema): Schema => $this->form($schema)),
DeleteAction::make(),
]);
}
private function discountType(Get $get): DiscountType
{
$type = $get('discount_type');
return $type instanceof DiscountType ? $type : (DiscountType::tryFrom((string) $type) ?? DiscountType::Percent);
}
private function isMoney(?DiscountType $type): bool
{
return in_array($type, [DiscountType::AmountPerStay, DiscountType::NightlyRate], true);
}
}
@@ -93,6 +93,14 @@ public static function configure(Schema $schema): Schema
->minValue(0)
->suffix('Tage vor Anreise')
->default(28),
TextInput::make('hold_hours')
->label('Vorreservierung halten')
->helperText('So lange bleibt ein angefragter Zeitraum ohne Ihre Bestätigung blockiert.')
->required()
->integer()
->minValue(1)
->suffix('Stunden')
->default(48),
]),
]);
}
+325
View File
@@ -0,0 +1,325 @@
<?php
namespace App\Livewire;
use App\Actions\CreateReservation;
use App\Availability\AvailabilityChecker;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Extra;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Public availability calendar, live price and booking request form.
*/
class BookingRequest extends Component
{
private const MONTHS_SHOWN = 2;
#[Locked]
public int $propertyId;
/** First shown month as 'Y-m'. */
public string $month;
public ?string $arrival = null;
public ?string $departure = null;
public int $guests = 2;
/** @var array<int|string, int|string|null> quantity per extra id */
public array $extras = [];
public string $promoCode = '';
public string $firstName = '';
public string $lastName = '';
public string $email = '';
public string $phone = '';
public string $street = '';
public string $postalCode = '';
public string $city = '';
public string $message = '';
public bool $privacyAccepted = false;
/** Honeypot, must stay empty. */
public string $website = '';
#[Locked]
public ?int $bookingId = null;
public function mount(?Property $property = null): void
{
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
$this->month = CarbonImmutable::today()->format('Y-m');
}
#[Computed]
public function property(): Property
{
return Property::findOrFail($this->propertyId);
}
/**
* @return Collection<int, Extra>
*/
#[Computed]
public function availableExtras(): Collection
{
return $this->property->extras()->active()->get();
}
public function previousMonth(): void
{
$previous = $this->firstMonth()->subMonth();
if ($previous->greaterThanOrEqualTo(CarbonImmutable::today()->startOfMonth())) {
$this->month = $previous->format('Y-m');
}
}
public function nextMonth(): void
{
$this->month = $this->firstMonth()->addMonth()->format('Y-m');
}
/**
* Calendar click: the first click sets the arrival, the second the departure.
*/
public function selectDate(string $date): void
{
$day = CarbonImmutable::parse($date);
$occupied = $this->occupiedNights();
if ($this->arrival !== null && $this->departure === null && $day->greaterThan(CarbonImmutable::parse($this->arrival))) {
if ($this->allNightsFree(CarbonImmutable::parse($this->arrival), $day, $occupied)) {
$this->departure = $day->toDateString();
return;
}
}
if ($day->isBefore(CarbonImmutable::today()) || isset($occupied[$day->toDateString()])) {
return;
}
$this->arrival = $day->toDateString();
$this->departure = null;
}
public function clearDates(): void
{
$this->arrival = null;
$this->departure = null;
}
/**
* @return array{quote: ?PriceQuote, error: ?string}
*/
#[Computed]
public function pricing(): array
{
if ($this->arrival === null || $this->departure === null) {
return ['quote' => null, 'error' => null];
}
$stay = $this->stayRequest();
if ($stay->arrival->isBefore(CarbonImmutable::today())) {
return ['quote' => null, 'error' => 'Die Anreise darf nicht in der Vergangenheit liegen.'];
}
if ($stay->departure->greaterThan($stay->arrival) && ! app(AvailabilityChecker::class)->isAvailable($this->property, $stay->arrival, $stay->departure)) {
return ['quote' => null, 'error' => 'Der Zeitraum ist leider bereits belegt.'];
}
try {
return ['quote' => app(PriceCalculator::class)->calculate($this->property, $stay), 'error' => null];
} catch (QuoteException $exception) {
return ['quote' => null, 'error' => $exception->getMessage()];
}
}
/**
* Weeks of the shown months; every day knows whether its night is still free.
*
* @return list<array{label: string, weeks: list<list<?array{date: string, day: int, free: bool, past: bool, selected: bool, inRange: bool}>>}>
*/
#[Computed]
public function calendar(): array
{
$occupied = $this->occupiedNights();
$today = CarbonImmutable::today();
$arrival = $this->arrival ? CarbonImmutable::parse($this->arrival) : null;
$departure = $this->departure ? CarbonImmutable::parse($this->departure) : null;
$months = [];
for ($index = 0; $index < self::MONTHS_SHOWN; $index++) {
$first = $this->firstMonth()->addMonths($index);
$days = array_fill(0, $first->isoWeekday() - 1, null);
for ($day = $first; $day->month === $first->month; $day = $day->addDay()) {
$days[] = [
'date' => $day->toDateString(),
'day' => $day->day,
'free' => ! isset($occupied[$day->toDateString()]),
'past' => $day->isBefore($today),
'selected' => in_array($day->toDateString(), [$this->arrival, $this->departure], true),
'inRange' => $arrival && $departure && $day->greaterThan($arrival) && $day->lessThan($departure),
];
}
$months[] = ['label' => $first->translatedFormat('F Y'), 'weeks' => array_chunk($days, 7)];
}
return $months;
}
public function submit(CreateReservation $createReservation): void
{
$this->validate();
if ($this->website !== '') {
return;
}
$rateLimitKey = 'booking-request:'.request()->ip();
if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) {
$this->addError('email', 'Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an.');
return;
}
RateLimiter::hit($rateLimitKey, 3600);
try {
$booking = $createReservation->handle(
$this->property,
$this->stayRequest(),
[
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'email' => $this->email,
'phone' => $this->phone ?: null,
'street' => $this->street ?: null,
'postal_code' => $this->postalCode ?: null,
'city' => $this->city ?: null,
],
$this->message ?: null,
);
} catch (QuoteException|ReservationException $exception) {
$this->addError('arrival', $exception->getMessage());
unset($this->calendar, $this->pricing);
return;
}
$this->bookingId = $booking->id;
}
/**
* @return array<string, list<string>>
*/
protected function rules(): array
{
return [
'arrival' => ['required', 'date', 'after_or_equal:today'],
'departure' => ['required', 'date', 'after:arrival'],
'guests' => ['required', 'integer', 'min:1', 'max:'.$this->property->max_guests],
'extras.*' => ['nullable', 'integer', 'min:0', 'max:10'],
'promoCode' => ['nullable', 'string', 'max:50'],
'firstName' => ['required', 'string', 'max:255'],
'lastName' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:50'],
'street' => ['nullable', 'string', 'max:255'],
'postalCode' => ['nullable', 'string', 'max:20'],
'city' => ['nullable', 'string', 'max:255'],
'message' => ['nullable', 'string', 'max:5000'],
'privacyAccepted' => ['accepted'],
];
}
/**
* @return array<string, string>
*/
protected function validationAttributes(): array
{
return [
'arrival' => 'Anreise',
'departure' => 'Abreise',
'guests' => 'Personen',
'firstName' => 'Vorname',
'lastName' => 'Nachname',
'email' => 'E-Mail',
'privacyAccepted' => 'Datenschutzerklärung',
];
}
public function render(): View
{
return view('livewire.booking-request', [
'booking' => $this->bookingId ? Booking::with('guest')->find($this->bookingId) : null,
]);
}
private function stayRequest(): StayRequest
{
return new StayRequest(
CarbonImmutable::parse($this->arrival),
CarbonImmutable::parse($this->departure),
$this->guests,
array_map('intval', array_filter($this->extras, fn ($quantity): bool => (int) $quantity > 0)),
$this->promoCode !== '' ? trim($this->promoCode) : null,
);
}
private function firstMonth(): CarbonImmutable
{
return CarbonImmutable::createFromFormat('!Y-m', $this->month);
}
/**
* Occupied nights from the first shown month until a year ahead, so departures can be checked beyond the view.
*
* @return array<string, true>
*/
private function occupiedNights(): array
{
$from = $this->firstMonth()->min(CarbonImmutable::parse($this->arrival ?? $this->month.'-01'));
return app(AvailabilityChecker::class)->occupiedNights($this->property, $from, $from->addYear());
}
/**
* @param array<string, true> $occupied
*/
private function allNightsFree(CarbonImmutable $from, CarbonImmutable $until, array $occupied): bool
{
for ($night = $from; $night->lessThan($until); $night = $night->addDay()) {
if (isset($occupied[$night->toDateString()])) {
return false;
}
}
return true;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Sent to the guest when the landlord confirms a reservation.
*/
class BookingConfirmed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Buchungsbestätigung '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.booking-confirmed',
);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Sent to the guest when the landlord declines a reservation.
*/
class BookingDeclined extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Anfrage '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.booking-declined',
);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Notifies the landlord about a new request.
*/
class NewReservation extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Neue Anfrage '.$this->booking->reference.': '.$this->booking->guest->full_name.', '.$this->booking->arrival->format('d.m.').'–'.$this->booking->departure->format('d.m.Y'),
replyTo: [new Address($this->booking->guest->email, $this->booking->guest->full_name)],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.new-reservation',
);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Notifies the landlord that a hold expired without a decision.
*/
class ReservationExpired extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Vormerkung abgelaufen: '.$this->booking->reference.' ('.$this->booking->guest->full_name.')',
replyTo: [new Address($this->booking->guest->email, $this->booking->guest->full_name)],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.reservation-expired',
);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Sent to the guest right after a request: the quote and how long the dates are held.
*/
class ReservationReceived extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Anfrage '.$this->booking->reference.' – Termin vorgemerkt',
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.reservation-received',
);
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Models;
use Carbon\CarbonInterface;
use Database\Factories\BlockedPeriodFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Dates that are not bookable (own use, maintenance, bookings from portals).
* Like bookings, ends_on is the first free day again.
*/
#[Fillable(['property_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
class BlockedPeriod extends Model
{
/** @use HasFactory<BlockedPeriodFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'starts_on' => 'immutable_date',
'ends_on' => 'immutable_date',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @param Builder<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
*/
#[Scope]
protected function overlapping(Builder $query, CarbonInterface $from, CarbonInterface $until): Builder
{
return $query
->whereDate('starts_on', '<', $until)
->whereDate('ends_on', '>', $from);
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
namespace App\Models;
use App\Enums\BookingStatus;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A reservation or booking. arrival is the first night, departure the day the guest leaves,
* so a departure and the next arrival on the same day do not collide.
*/
#[Fillable([
'property_id',
'guest_id',
'status',
'source',
'arrival',
'departure',
'guests',
'extras',
'promo_code',
'quote',
'total',
'deposit',
'balance_due_on',
'hold_expires_at',
'message',
'internal_notes',
'confirmed_at',
'cancelled_at',
])]
class Booking extends Model
{
/** @use HasFactory<BookingFactory> */
use HasFactory;
protected static function booted(): void
{
static::created(function (Booking $booking): void {
$booking->forceFill(['reference' => $booking->created_at->format('Y').'-'.str_pad((string) $booking->id, 4, '0', STR_PAD_LEFT)])->saveQuietly();
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'status' => BookingStatus::class,
'arrival' => 'immutable_date',
'departure' => 'immutable_date',
'extras' => 'array',
'quote' => 'array',
'balance_due_on' => 'immutable_date',
'hold_expires_at' => 'immutable_datetime',
'confirmed_at' => 'immutable_datetime',
'cancelled_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @return BelongsTo<Guest, $this>
*/
public function guest(): BelongsTo
{
return $this->belongsTo(Guest::class);
}
/**
* Bookings that currently occupy their dates: confirmed ones and reservations whose hold has not expired.
*
* @param Builder<Booking> $query
* @return Builder<Booking>
*/
#[Scope]
protected function occupying(Builder $query): Builder
{
return $query->where(fn (Builder $query) => $query
->whereIn('status', BookingStatus::occupying())
->orWhere(fn (Builder $query) => $query
->where('status', BookingStatus::Reserved)
->where('hold_expires_at', '>', now())));
}
/**
* @param Builder<Booking> $query
* @return Builder<Booking>
*/
#[Scope]
protected function overlapping(Builder $query, CarbonInterface $from, CarbonInterface $until): Builder
{
return $query
->whereDate('arrival', '<', $until)
->whereDate('departure', '>', $from);
}
public function nights(): int
{
return (int) $this->arrival->diffInDays($this->departure);
}
public function isHoldActive(): bool
{
return $this->status === BookingStatus::Reserved && $this->hold_expires_at?->isFuture();
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Database\Factories\GuestFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\Notifiable;
#[Fillable(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country', 'locale', 'notes'])]
class Guest extends Model
{
/** @use HasFactory<GuestFactory> */
use HasFactory, Notifiable;
/**
* @return HasMany<Booking, $this>
*/
public function bookings(): HasMany
{
return $this->hasMany(Booking::class)->latest('arrival');
}
/**
* @return Attribute<string, never>
*/
protected function fullName(): Attribute
{
return Attribute::get(fn (): string => "{$this->first_name} {$this->last_name}");
}
}
+25
View File
@@ -23,6 +23,7 @@
'cleaning_fee',
'deposit_percent',
'balance_due_days_before_arrival',
'hold_hours',
'check_in_time',
'check_out_time',
'is_active',
@@ -52,6 +53,30 @@ public function seasons(): HasMany
return $this->hasMany(Season::class)->orderBy('starts_on');
}
/**
* @return HasMany<Booking, $this>
*/
public function bookings(): HasMany
{
return $this->hasMany(Booking::class);
}
/**
* @return HasMany<BlockedPeriod, $this>
*/
public function blockedPeriods(): HasMany
{
return $this->hasMany(BlockedPeriod::class)->orderBy('starts_on');
}
/**
* @return HasMany<SpecialOffer, $this>
*/
public function specialOffers(): HasMany
{
return $this->hasMany(SpecialOffer::class);
}
/**
* Periods within [$from, $until) for which no season defines a price.
*
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace App\Models;
use App\Enums\DiscountType;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Database\Factories\SpecialOfferFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A discount rule such as last minute, early bird, long stay, special weekends or a code for regular guests.
* Every condition left empty means "no restriction".
*/
#[Fillable([
'property_id',
'name',
'public_description',
'is_active',
'is_public',
'is_combinable',
'code',
'discount_type',
'discount_value',
'stay_from',
'stay_until',
'bookable_from',
'bookable_until',
'min_days_before_arrival',
'max_days_before_arrival',
'min_nights',
'max_nights',
'arrival_weekdays',
'season_names',
])]
class SpecialOffer extends Model
{
/** @use HasFactory<SpecialOfferFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_active' => 'boolean',
'is_public' => 'boolean',
'is_combinable' => 'boolean',
'discount_type' => DiscountType::class,
'stay_from' => 'immutable_date',
'stay_until' => 'immutable_date',
'bookable_from' => 'immutable_datetime',
'bookable_until' => 'immutable_datetime',
'arrival_weekdays' => 'array',
'season_names' => 'array',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @param Builder<SpecialOffer> $query
* @return Builder<SpecialOffer>
*/
#[Scope]
protected function active(Builder $query): Builder
{
return $query->where('is_active', true);
}
/**
* Whether all conditions are met. Offers with a code only apply when the guest entered that code.
*/
public function appliesTo(StayRequest $stay, string $arrivalSeasonName, CarbonImmutable $bookedAt): bool
{
$nights = $stay->nights();
$daysBeforeArrival = (int) $bookedAt->startOfDay()->diffInDays($stay->arrival, false);
return $this->is_active
&& ($this->code === null || strcasecmp($this->code, (string) $stay->promoCode) === 0)
&& ($this->stay_from === null || $stay->arrival->greaterThanOrEqualTo($this->stay_from))
&& ($this->stay_until === null || $stay->departure->lessThanOrEqualTo($this->stay_until))
&& ($this->bookable_from === null || $bookedAt->greaterThanOrEqualTo($this->bookable_from))
&& ($this->bookable_until === null || $bookedAt->lessThanOrEqualTo($this->bookable_until))
&& ($this->min_days_before_arrival === null || $daysBeforeArrival >= $this->min_days_before_arrival)
&& ($this->max_days_before_arrival === null || $daysBeforeArrival <= $this->max_days_before_arrival)
&& ($this->min_nights === null || $nights >= $this->min_nights)
&& ($this->max_nights === null || $nights <= $this->max_nights)
&& (empty($this->arrival_weekdays) || in_array($stay->arrival->isoWeekday(), array_map('intval', $this->arrival_weekdays), true))
&& (empty($this->season_names) || in_array($arrivalSeasonName, $this->season_names, true));
}
/**
* The discount in cents for the given nightly rates (one entry per night, in cents).
*
* @param list<int> $nightlyRates
*/
public function discountFor(array $nightlyRates): int
{
$accommodation = array_sum($nightlyRates);
$discount = match ($this->discount_type) {
DiscountType::Percent => intdiv($accommodation * min($this->discount_value, 100) + 50, 100),
DiscountType::AmountPerStay => $this->discount_value,
DiscountType::NightlyRate => array_sum(array_map(fn (int $rate): int => max(0, $rate - $this->discount_value), $nightlyRates)),
DiscountType::FreeNights => array_sum(array_slice($this->sortedAscending($nightlyRates), 0, $this->discount_value)),
};
return min($discount, $accommodation);
}
/**
* @param list<int> $rates
* @return list<int>
*/
private function sortedAscending(array $rates): array
{
sort($rates);
return $rates;
}
}
+88 -37
View File
@@ -7,40 +7,44 @@
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 from $arrival (first night) to $departure (day of departure, not a night).
*
* @param array<int, int> $extraQuantities quantity per extra id
* 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,
CarbonImmutable $arrival,
CarbonImmutable $departure,
int $guests,
array $extraQuantities = [],
): PriceQuote {
$arrival = $arrival->startOfDay();
$departure = $departure->startOfDay();
if ($departure->lessThanOrEqualTo($arrival)) {
public function calculate(Property $property, StayRequest $stay, ?CarbonImmutable $bookedAt = null): PriceQuote
{
if ($stay->departure->lessThanOrEqualTo($stay->arrival)) {
throw QuoteException::invalidPeriod();
}
if ($guests < 1 || $guests > $property->max_guests) {
if ($stay->guests < 1 || $stay->guests > $property->max_guests) {
throw QuoteException::invalidGuestCount($property->max_guests);
}
$nights = (int) $arrival->diffInDays($departure);
$lines = $this->accommodationLines($property, $arrival, $departure);
$nights = $stay->nights();
$nightSeasons = $this->seasonPerNight($property, $stay);
$extraGuests = max(0, $guests - $property->included_guests);
$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,
@@ -55,34 +59,47 @@ public function calculate(
$lines[] = new QuoteLine(QuoteLineType::Cleaning, 'Endreinigung & Service', 1, $property->cleaning_fee, $property->cleaning_fee);
}
array_push($lines, ...$this->extraLines($property, $extraQuantities, $nights));
array_push($lines, ...$this->extraLines($property, $stay->extras, $nights));
return new PriceQuote(
arrival: $arrival,
departure: $departure,
guests: $guests,
arrival: $stay->arrival,
departure: $stay->departure,
guests: $stay->guests,
lines: $lines,
depositPercent: $property->deposit_percent,
balanceDueOn: $arrival->subDays($property->balance_due_days_before_arrival),
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(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): array
private function accommodationLines(array $nightSeasons): array
{
/** @var Collection<int, Season> $seasons */
$seasons = $property->seasons()->overlapping($arrival, $departure)->get();
/** @var list<array{season: Season, nights: int}> $runs */
$runs = [];
for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) {
$season = $seasons->first(fn (Season $season): bool => $season->containsNight($night))
?? throw QuoteException::noRateForNight($night);
foreach ($nightSeasons as $season) {
$lastRun = array_key_last($runs);
if ($lastRun !== null && $runs[$lastRun]['season']->is($season)) {
$runs[$lastRun]['nights']++;
@@ -91,12 +108,6 @@ private function accommodationLines(Property $property, CarbonImmutable $arrival
}
}
$arrivalSeason = $runs[0]['season'];
$nights = (int) $arrival->diffInDays($departure);
if ($nights < $arrivalSeason->min_nights) {
throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name);
}
return array_map(fn (array $run): QuoteLine => new QuoteLine(
QuoteLineType::Accommodation,
"{$run['season']->name} ({$run['nights']} ".($run['nights'] === 1 ? 'Nacht' : 'Nächte').')',
@@ -106,6 +117,46 @@ private function accommodationLines(Property $property, CarbonImmutable $arrival
), $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>
+15 -1
View File
@@ -2,6 +2,7 @@
namespace App\Pricing;
use App\Enums\QuoteLineType;
use Carbon\CarbonImmutable;
/**
@@ -19,8 +20,20 @@ public function __construct(
public array $lines,
public int $depositPercent,
public CarbonImmutable $balanceDueOn,
public ?bool $promoCodeApplied = null,
) {}
/**
* Total of all special offer discounts as a positive amount.
*/
public function discount(): int
{
return -array_sum(array_map(
fn (QuoteLine $line): int => $line->type === QuoteLineType::Discount ? $line->amount : 0,
$this->lines,
));
}
public function nights(): int
{
return (int) $this->arrival->diffInDays($this->departure);
@@ -53,7 +66,7 @@ public function balance(): int
}
/**
* @return array{arrival: string, departure: string, nights: int, guests: int, lines: list<array<string, mixed>>, total: int, deposit: int, balance: int, balance_due_on: string}
* @return array{arrival: string, departure: string, nights: int, guests: int, lines: list<array<string, mixed>>, total: int, deposit: int, balance: int, balance_due_on: string, discount: int}
*/
public function toArray(): array
{
@@ -67,6 +80,7 @@ public function toArray(): array
'deposit' => $this->deposit(),
'balance' => $this->balance(),
'balance_due_on' => $this->balanceDueOn->toDateString(),
'discount' => $this->discount(),
];
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Pricing;
use Carbon\CarbonImmutable;
/**
* What a guest asks for: dates, number of guests, optional extras and a promo code.
*/
final readonly class StayRequest
{
public CarbonImmutable $arrival;
public CarbonImmutable $departure;
/**
* @param array<int, int> $extras quantity per extra id
*/
public function __construct(
CarbonImmutable $arrival,
CarbonImmutable $departure,
public int $guests,
public array $extras = [],
public ?string $promoCode = null,
) {
$this->arrival = $arrival->startOfDay();
$this->departure = $departure->startOfDay();
}
public function nights(): int
{
return (int) $this->arrival->diffInDays($this->departure);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Support;
use Illuminate\Support\Number;
class Money
{
/**
* Format euro cents for display, e.g. 12350 → "123,50 €".
*/
public static function format(int $cents): string
{
return (string) Number::currency($cents / 100, 'EUR', 'de');
}
}