ldc-cocotte/app/Jobs/SendMissingOrderReminderJob.php

61 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Employee;
use App\Models\Order;
use App\Notifications\MissingOrderReminderNotification;
use Carbon\CarbonInterface;
use Domain\Enums\OrderStatus;
use Domain\Models\ValueObjects\Matricule;
use Domain\Services\PickupSchedulingService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
class SendMissingOrderReminderJob implements ShouldQueue
{
use Queueable;
public const int DAYS_BEFORE_CUTOFF = 0;
public const int HOURS_BEFORE_CUTOFF = 6;
public function handle(PickupSchedulingService $schedulingService): void
{
$pickupDay = Carbon::now()->next($schedulingService->getPickupDay()->value);
$employees = $this->getEmployeesToNotify($pickupDay);
foreach ($employees as $employee) {
$employee->notify(new MissingOrderReminderNotification($pickupDay));
}
}
/** @return Collection<int,\App\Models\Employee> */
private function getEmployeesToNotify(CarbonInterface $pickupDay): Collection
{
$excludedMatricules = Order::query()
->whereDate('pickup_day', $pickupDay->format('Y-m-d'))
->where('status', OrderStatus::VALIDATED)
->get()
->map(fn (Order $order): Matricule => $order->employee->matricule)
->unique();
return Employee::query()
->with('customer')
->whereNotIn('matricule', $excludedMatricules)
->get()
->filter(fn (Employee $employee): bool => $this->canNotifyEmployee($employee));
}
private function canNotifyEmployee(Employee $employee): bool
{
$customer = $employee->customer;
return $customer && Gate::forUser($customer)->check('customerPassOrders');
}
}