ldc-qrcollector-back/app/Http/Requests/Bo/StatsRequest.php
2026-07-17 16:46:22 +02:00

78 lines
2.3 KiB
PHP

<?php
namespace App\Http\Requests\Bo;
use App\Models\Brand;
use App\Models\Url;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
class StatsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth('backend')->check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation(): void
{
$now = Carbon::now();
$urlId = $this->input('url');
$brandId = $this->input('brand');
$startDate = Carbon::parse($this->input('start'));
$endDate = Carbon::parse($this->input('end'));
$adjustedEndDate = $endDate->greaterThan($now) ? $now : $endDate;
// Get start & end dates by period.
switch ($this->input('period')) {
case 'week':
$adjustedStart = $startDate->copy()->startOfWeek();
$adjustedEnd = $endDate->copy()->endOfWeek();
break;
case 'month':
$adjustedStart = $startDate->copy()->startOfMonth();
$adjustedEnd = $endDate->copy()->endOfMonth();
break;
default:
$adjustedStart = $startDate;
$adjustedEnd = $adjustedEndDate;
break;
}
$this->merge([
'url' => Url::find($urlId) ? $urlId : null,
'brand' => Brand::find($brandId) ? $brandId : null,
'start' => $adjustedStart->toDateString(),
'end' => $adjustedEnd->toDateString(),
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return (request()->post()) ? [
'period' => 'required|string|in:day,week,month',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:today|after_or_equal:'
. Carbon::parse($this->input('end'))->modify('-1 year'),
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
'brand' => 'nullable|integer|exists:App\Models\Brand,id',
'url' => 'nullable|integer|exists:App\Models\Url,id'
] : [];
}
}