CaseActivities/CaseAutomation sind Fassaden über ProcessRunner. Verhaltensvergleich v0.11: 11 Abläufe und 198 Konstellationen gleich, beabsichtigte Abweichungen I-004/I-005 (F-001/F-002). Volle Suite vor U-B: 785/785. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
9.9 KiB
PHP
210 lines
9.9 KiB
PHP
<?php
|
||
|
||
namespace App\Actions;
|
||
|
||
use App\Availability\AvailabilityChecker;
|
||
use App\Enums\BookingStatus;
|
||
use App\Enums\FactSource;
|
||
use App\Enums\IntakeKind;
|
||
use App\Enums\ProcessingMode;
|
||
use App\Exceptions\ReservationException;
|
||
use App\Mail\NewReservation;
|
||
use App\Mail\ReservationReceived;
|
||
use App\Models\Booking;
|
||
use App\Models\Channel;
|
||
use App\Models\Guest;
|
||
use App\Models\Property;
|
||
use App\Pricing\PriceCalculator;
|
||
use App\Pricing\QuoteException;
|
||
use App\Pricing\StayRequest;
|
||
use App\Process\ProcessRunner;
|
||
use App\Process\ProcessSettings;
|
||
use App\Process\RequestHold;
|
||
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\Log;
|
||
use Illuminate\Support\Facades\Mail;
|
||
use Throwable;
|
||
|
||
/**
|
||
* Turns a guest request into a case (intake "request") that holds the dates for the hold time of the process settings,
|
||
* 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 = [], ?Channel $originChannel = null): 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, $originChannel),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @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, ?Channel $originChannel): Booking
|
||
{
|
||
if ($originChannel !== null && $originChannel->property_id !== $property->id) {
|
||
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
|
||
}
|
||
|
||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution, $originChannel): 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);
|
||
$profile = $originChannel === null && $source === 'website'
|
||
? app(ProcessSettings::class)->forWebsite($property)
|
||
: app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
|
||
$draft = new Booking(['property_id' => $property->id, 'arrival' => $stay->arrival->toDateString(), 'departure' => $stay->departure->toDateString(), 'guests' => $stay->guests]);
|
||
$draft->setRelation('guest', $guest);
|
||
$hold = RequestHold::for($draft, $profile);
|
||
|
||
return $property->bookings()->create([
|
||
...$hold,
|
||
'guest_id' => $guest->id,
|
||
'status' => BookingStatus::Reserved,
|
||
'source' => $source,
|
||
'intake' => IntakeKind::Inquiry,
|
||
'origin_channel_id' => $originChannel?->id,
|
||
...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(),
|
||
'message' => $message,
|
||
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
||
]);
|
||
});
|
||
|
||
if ($source === 'website') {
|
||
// Evidence of what the guest typed (v0.11, S5): completed fields are confirmed, differing ones go to the
|
||
// landlord as a conflict instead of only a note. The guest record itself was already handled above.
|
||
$facts = collect(Arr::only($guestData, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']))
|
||
->filter(fn (?string $value): bool => filled($value))
|
||
->mapWithKeys(fn (string $value, string $field): array => ['guest.'.$field => $value])->all();
|
||
app(ContributeCaseFacts::class)->handle($booking, $facts, FactSource::WebsiteForm, ['advance' => false, 'reference' => 'request']);
|
||
$booking->refresh();
|
||
}
|
||
|
||
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(trim((string) ($guestData['email'] ?? '')));
|
||
$guest = $email === '' ? null : 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];
|
||
}
|
||
|
||
/**
|
||
* Automatic mode first tries to send the offer; the guest then gets the offer instead of the receipt, the
|
||
* landlord a note either way (with the reasons when the automatic offer was not possible). A failing mail
|
||
* server or any other error must not lose the reservation; failures are logged without personal data.
|
||
*/
|
||
private function sendMails(Booking $booking): void
|
||
{
|
||
$blockers = [];
|
||
$offerSent = false;
|
||
$asked = false;
|
||
|
||
// The process core answers the request as far as its data allows (Architektur V2, trigger request.created):
|
||
// automatic mode sends the offer or information; if details are missing, the data request asks for them
|
||
// (and then replaces the receipt) – independently of the offer, which waits for the details.
|
||
try {
|
||
$result = app(ProcessRunner::class)->advance($booking, 'request.created');
|
||
$offerSent = $result->ran('offer.binding') || $result->ran('offer.information');
|
||
$booking->refresh();
|
||
if (! $offerSent && $booking->processingMode() === ProcessingMode::Automatic) {
|
||
$blockers = [...$result->reasons('offer.binding'), ...$result->reasons('offer.information')];
|
||
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
|
||
}
|
||
$asked = $result->ran('guest.data_request') && $booking->openDataRequest()?->last_sent_at !== null;
|
||
$booking->refresh();
|
||
} catch (Throwable $exception) {
|
||
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
|
||
$offerSent = false;
|
||
}
|
||
|
||
try {
|
||
if (! $offerSent && ! $asked && filled($booking->guest?->email)) {
|
||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||
}
|
||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
|
||
} catch (Throwable $exception) {
|
||
Log::warning('Eingangsmail nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||
}
|
||
}
|
||
}
|