Files
fewo-stommer/app/Actions/CreateReservation.php
LarsandCursor 8ebc1a3878 Assign the existing site to one landlord so stommer.info can run tenancy.
Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:00:11 +02:00

153 lines
6.1 KiB
PHP

<?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 App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
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
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
{
$tenant = $property->tenant;
if ($tenant === null) {
throw new TenantContextMissing(Property::class);
}
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
);
}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): 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, $differences] = $this->guestFor($guestData);
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'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,
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
]);
});
if ($sendMails) {
$this->sendMails($booking);
}
return $booking;
}
/**
* The guest record for the request. A known e-mail address never overwrites existing master data
* (anybody can type somebody else's address); empty fields are completed, differing values are
* returned so the landlord sees them with the request and can take them over in the offer.
*
* @param array<string, ?string> $guestData
* @return array{0: Guest, 1: list<string>}
*/
private function guestFor(array $guestData): array
{
$email = mb_strtolower($guestData['email']);
$guest = Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([
...$guestData,
'email' => $email,
'tenant_id' => app(TenantContext::class)->id(),
]), []];
}
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
$differences = [];
foreach ($labels as $field => $label) {
$value = trim((string) ($guestData[$field] ?? ''));
if ($value === '') {
continue;
}
if (blank($guest->{$field})) {
$guest->{$field} = $value;
} elseif (mb_strtolower((string) $guest->{$field}) !== mb_strtolower($value)) {
$differences[] = "{$label}: {$value} (Kartei: {$guest->{$field}})";
}
}
$guest->save();
return [$guest, $differences];
}
/**
* 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(Settings::notificationRecipients())->send(new NewReservation($booking));
} catch (Throwable $exception) {
report($exception);
}
}
}