53 lines
2.7 KiB
PHP
53 lines
2.7 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, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string, notes?: ?string, tags?: ?array} $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'],
|
|
'street' => ['nullable', 'string', 'max:255'],
|
|
'postal_code' => ['nullable', 'string', 'max:20'],
|
|
'city' => ['nullable', 'string', 'max:255'],
|
|
'country' => ['nullable', 'string', 'size:2', 'regex:/^[A-Z]{2}$/'],
|
|
'notes' => ['nullable', 'string'],
|
|
'tags' => ['nullable', 'array'],
|
|
'tags.*' => ['string', 'max:255'],
|
|
])->validate();
|
|
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? 'DE']);
|
|
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
|
|
}
|
|
$record->forceFill(['guest_id' => $guest->id])->save();
|
|
|
|
return $guest;
|
|
});
|
|
}
|
|
}
|