73 lines
2.8 KiB
PHP
73 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Reservations\Services;
|
|
|
|
use App\Domain\Administration\Services\ReservationPolicy;
|
|
use App\Domain\Inventory\Models\SnipeAsset;
|
|
use App\Domain\Reservations\Enums\ReservationItemStatus;
|
|
use Carbon\CarbonImmutable;
|
|
use DateTimeInterface;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
class AvailabilityService
|
|
{
|
|
public function __construct(private readonly ReservationPolicy $policy) {}
|
|
|
|
/** @return Builder<SnipeAsset> */
|
|
public function availableAssets(DateTimeInterface $startsAt, DateTimeInterface $endsAt): Builder
|
|
{
|
|
[$bufferStartsAt, $bufferEndsAt] = $this->bufferedPeriod($startsAt, $endsAt);
|
|
|
|
return SnipeAsset::query()
|
|
->where('active', true)
|
|
->where('requestable', true)
|
|
->whereNull('assigned_id')
|
|
->whereDoesntHave('reservationItems', fn (Builder $query): Builder => $query
|
|
->whereIn('status', ReservationItemStatus::blockingValues())
|
|
->whereRaw('COALESCE(buffer_starts_at, starts_at) < ?', [$bufferEndsAt])
|
|
->whereRaw('COALESCE(buffer_ends_at, ends_at) > ?', [$bufferStartsAt]))
|
|
->whereDoesntHave('blocks', fn (Builder $query): Builder => $query
|
|
->where('starts_at', '<', $endsAt)
|
|
->where('ends_at', '>', $startsAt));
|
|
}
|
|
|
|
public function isAvailable(
|
|
SnipeAsset $asset,
|
|
DateTimeInterface $startsAt,
|
|
DateTimeInterface $endsAt,
|
|
?int $exceptReservationId = null,
|
|
): bool {
|
|
if (! $asset->active || ! $asset->requestable || $asset->assigned_id !== null) {
|
|
return false;
|
|
}
|
|
|
|
[$bufferStartsAt, $bufferEndsAt] = $this->bufferedPeriod($startsAt, $endsAt);
|
|
$hasReservationConflict = $asset->reservationItems()
|
|
->whereIn('status', ReservationItemStatus::blockingValues())
|
|
->when($exceptReservationId, fn (Builder $query): Builder => $query->where('reservation_id', '!=', $exceptReservationId))
|
|
->whereRaw('COALESCE(buffer_starts_at, starts_at) < ?', [$bufferEndsAt])
|
|
->whereRaw('COALESCE(buffer_ends_at, ends_at) > ?', [$bufferStartsAt])
|
|
->exists();
|
|
|
|
if ($hasReservationConflict) {
|
|
return false;
|
|
}
|
|
|
|
return ! $asset->blocks()
|
|
->where('starts_at', '<', $endsAt)
|
|
->where('ends_at', '>', $startsAt)
|
|
->exists();
|
|
}
|
|
|
|
/** @return array{DateTimeInterface, DateTimeInterface} */
|
|
public function bufferedPeriod(DateTimeInterface $startsAt, DateTimeInterface $endsAt): array
|
|
{
|
|
$margin = $this->policy->integer('reservation.turnaround_minutes');
|
|
|
|
return [
|
|
CarbonImmutable::instance($startsAt)->subMinutes($margin),
|
|
CarbonImmutable::instance($endsAt)->addMinutes($margin),
|
|
];
|
|
}
|
|
}
|