Files
fewo-stommer/app/Actions/AssignOccupationGuest.php
T
2026-10-27 21:51:56 +01:00

46 lines
2.1 KiB
PHP

<?php
namespace App\Actions;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class AssignOccupationGuest
{
/** @param array{first_name?: string, last_name?: ?string, email?: ?string, phone?: ?string} $details */
public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $details = []): Guest
{
Gate::authorize('update', $occupation);
return DB::transaction(function () use ($occupation, $guestId, $details): Guest {
$record = $occupation->newQuery()->whereKey($occupation->id)->lockForUpdate()->firstOrFail();
if ($record instanceof BlockedPeriod && ($record->occupationKind() !== OccupationKind::Reservation || $record->is_representation)) {
throw ValidationException::withMessages(['guest_id' => 'Zuerst als eigenständige Portalreservierung einordnen. Darstellungen werden an der führenden Buchung gepflegt.']);
}
if ($guestId !== null) {
$guest = Guest::query()->where('tenant_id', $record->tenant_id)->whereNull('anonymized_at')->findOrFail($guestId);
Gate::authorize('view', $guest);
} else {
Gate::authorize('create', Guest::class);
$data = Validator::make($details, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['nullable', 'string', 'max:255'],
'email' => ['nullable', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:50'],
])->validate();
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null]);
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
}
$record->forceFill(['guest_id' => $guest->id])->save();
return $guest;
});
}
}