63 lines
2.3 KiB
PHP
63 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Requests;
|
|
|
|
use App\Domain\Administration\Services\ReservationPolicy;
|
|
use Carbon\CarbonImmutable;
|
|
use Illuminate\Foundation\Http\FormRequest;
|
|
use Illuminate\Validation\Validator;
|
|
|
|
class StoreReservationRequest extends FormRequest
|
|
{
|
|
public function authorize(): bool
|
|
{
|
|
return $this->user()?->active === true;
|
|
}
|
|
|
|
/** @return array<string, list<string>> */
|
|
public function rules(): array
|
|
{
|
|
$maxAssets = app(ReservationPolicy::class)->integer('reservation.max_assets');
|
|
|
|
return [
|
|
'purpose' => ['required', 'string', 'min:10', 'max:2000'],
|
|
'usage_location' => ['required', 'string', 'max:255'],
|
|
'starts_at' => ['required', 'date', 'after:now'],
|
|
'ends_at' => ['required', 'date', 'after:starts_at'],
|
|
'asset_ids' => ['required', 'array', 'min:1', "max:{$maxAssets}"],
|
|
'asset_ids.*' => ['required', 'integer', 'distinct', 'exists:snipe_assets,id'],
|
|
'terms_accepted' => ['accepted'],
|
|
];
|
|
}
|
|
|
|
/** @return list<callable(Validator): void> */
|
|
public function after(): array
|
|
{
|
|
return [function (Validator $validator): void {
|
|
$now = now();
|
|
$nowFormatted = $now->format('d/m/Y \à\s H:i');
|
|
|
|
if ($validator->errors()->has('starts_at')) {
|
|
$validator->errors()->add('starts_at', "A data de início deve ser posterior às {$nowFormatted}.");
|
|
}
|
|
|
|
if ($validator->errors()->hasAny(['starts_at', 'ends_at'])) {
|
|
return;
|
|
}
|
|
|
|
$policy = app(ReservationPolicy::class);
|
|
$startsAt = CarbonImmutable::parse((string) $this->input('starts_at'));
|
|
$endsAt = CarbonImmutable::parse((string) $this->input('ends_at'));
|
|
$minNotice = $policy->integer('reservation.min_notice_hours');
|
|
$maxDuration = $policy->integer('reservation.max_duration_hours');
|
|
|
|
if ($startsAt->lessThan(now()->addHours($minNotice))) {
|
|
$validator->errors()->add('starts_at', "A requisição exige pelo menos {$minNotice} horas de antecedência.");
|
|
}
|
|
if ($startsAt->diffInMinutes($endsAt) > $maxDuration * 60) {
|
|
$validator->errors()->add('ends_at', "A duração máxima permitida é de {$maxDuration} horas.");
|
|
}
|
|
}];
|
|
}
|
|
}
|