ldc-cocotte/app/Jobs/SendMissingOrderReminderJob.php

276 lines
9.6 KiB
PHP
Raw Permalink Normal View History

2026-06-14 21:32:07 +02:00
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Dto\IcsContentDto;
use App\Models\Customer;
2026-06-14 21:32:07 +02:00
use App\Models\Employee;
use App\Models\Order;
2026-06-14 21:32:07 +02:00
use App\Notifications\MissingOrderReminderNotification;
use App\Services\IcsGeneratorService;
use Carbon\CarbonImmutable;
use Domain\Enums\OrderStatus;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\IcsContent;
2026-06-14 21:32:07 +02:00
use Domain\Services\PickupSchedulingService;
use Domain\Services\ShopperService;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Contracts\Queue\ShouldBeUnique;
2026-06-14 21:32:07 +02:00
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
2026-06-14 21:32:07 +02:00
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
2026-06-14 21:32:07 +02:00
use Illuminate\Support\Facades\Gate;
use Webmozart\Assert\Assert;
2026-06-14 21:32:07 +02:00
class SendMissingOrderReminderJob implements ShouldBeUnique, ShouldQueue
2026-06-14 21:32:07 +02:00
{
use Queueable;
public const int DAYS_BEFORE_CUTOFF = 0;
public const int HOURS_BEFORE_CUTOFF = 6;
public int $uniqueFor = 3600;
private const int CHUNK_SIZE = 100;
public function uniqueId(): string
{
return Date::now()->format('o-\WW');
}
public function handle(
PickupSchedulingService $schedulingService,
ShopperService $shopperService,
IcsGeneratorService $icsGenerator,
CacheRepository $cache,
): void {
$timezone = $schedulingService->getCutoffTimezone();
$targetFriday = CarbonImmutable::instance($schedulingService->nextPickup())
->setTimezone($timezone)
->startOfDay();
$weekKey = $targetFriday->format('o-\WW');
/** @var array<string, ?\Domain\Models\ValueObjects\PickupWindow> $windowsByShopId */
$windowsByShopId = [];
/** @var array<string, \Domain\Models\ValueObjects\IcsContent> $icsByCutoffKey */
$icsByCutoffKey = [];
Employee::query()
->whereNotNull('customer_id')
->with('customer')
->active()
->chunkById(
self::CHUNK_SIZE,
function (Collection $employees) use (
$schedulingService,
$shopperService,
$icsGenerator,
$cache,
$targetFriday,
$weekKey,
&$windowsByShopId,
&$icsByCutoffKey,
): void {
/** @var \Illuminate\Database\Eloquent\Collection<int, \App\Models\Employee> $employees */
$this->processChunk(
$employees,
$schedulingService,
$shopperService,
$icsGenerator,
$cache,
$targetFriday,
$weekKey,
$windowsByShopId,
$icsByCutoffKey,
);
},
'id'
);
}
/**
* @param \Illuminate\Database\Eloquent\Collection<int, \App\Models\Employee> $employees
* @param array<string, ?\Domain\Models\ValueObjects\PickupWindow> $windowsByShopId
* @param array<string, \Domain\Models\ValueObjects\IcsContent> $icsByCutoffKey
*/
private function processChunk(
Collection $employees,
PickupSchedulingService $schedulingService,
ShopperService $shopperService,
IcsGeneratorService $icsGenerator,
CacheRepository $cache,
CarbonImmutable $targetFriday,
string $weekKey,
array &$windowsByShopId,
array &$icsByCutoffKey,
): void {
$timezone = $schedulingService->getCutoffTimezone();
/** @var list<array{employee: \App\Models\Employee, window: \Domain\Models\ValueObjects\PickupWindow, pickupDateKey: string}> $candidates */
$candidates = [];
foreach ($employees as $employee) {
if (! $this->canNotifyEmployee($employee) || $cache->has($this->reminderCacheKey($weekKey, $employee->id))) {
continue;
}
$shop = $shopperService->resolveShopForEmployee($this->mapEmployeeToShopper($employee));
$shopId = $shop->id()->value->toString();
if (! array_key_exists($shopId, $windowsByShopId)) {
$windowsByShopId[$shopId] = $schedulingService->getPickupWindowFor($shop, $targetFriday);
}
$window = $windowsByShopId[$shopId];
if ($window === null) {
continue;
}
$pickupDateKey = CarbonImmutable::instance($window->timeSlot->getAt())
->setTimezone($timezone)
->format('Y-m-d');
$candidates[] = [
'employee' => $employee,
'window' => $window,
'pickupDateKey' => $pickupDateKey,
];
}
if ($candidates === []) {
return;
}
$orderedPairs = $this->findValidatedOrderPairs(
matricules: array_values(array_unique(array_map(
fn (array $candidate): string => $candidate['employee']->matricule->value,
$candidates,
))),
pickupDates: array_values(array_unique(array_map(
fn (array $candidate): string => $candidate['pickupDateKey'],
$candidates,
))),
);
foreach ($candidates as $candidate) {
$employee = $candidate['employee'];
$pairKey = $employee->matricule->value . '|' . $candidate['pickupDateKey'];
if (isset($orderedPairs[$pairKey])) {
continue;
}
if (! $cache->add($this->reminderCacheKey($weekKey, $employee->id), true, Date::now()->addWeek())) {
continue;
}
$cutoffDate = $candidate['window']->deadline->setTimezone($timezone);
$cutoffKey = $cutoffDate->format(\DateTimeInterface::ATOM);
$icsContent = $icsByCutoffKey[$cutoffKey] ??= $this->generateIcsContent($icsGenerator, $cutoffDate);
$pickupDay = CarbonImmutable::instance($candidate['window']->timeSlot->getAt())->setTimezone($timezone);
2026-06-14 21:32:07 +02:00
$employee->notify(new MissingOrderReminderNotification($pickupDay, $cutoffDate, $icsContent));
2026-06-14 21:32:07 +02:00
}
}
private function reminderCacheKey(string $weekKey, int $employeeId): string
{
return 'missing-order-reminder:' . $weekKey . ':' . $employeeId;
}
/**
* @param list<string> $matricules
* @param list<string> $pickupDates
* @return array<string, true>
*/
private function findValidatedOrderPairs(array $matricules, array $pickupDates): array
{
$orders = Order::query()
->whereIn('employee_matricule', $matricules)
->where('status', OrderStatus::VALIDATED)
->where(function (Builder $query) use ($pickupDates): void {
foreach ($pickupDates as $date) {
$query->orWhereDate('pickup_day', $date);
}
})
->get(['employee', 'pickup_day']);
$pairs = [];
foreach ($orders as $order) {
$date = $order->pickup_day?->format('Y-m-d');
if ($date !== null) {
$pairs[$order->employee->matricule->value . '|' . $date] = true;
}
}
return $pairs;
}
private function generateIcsContent(IcsGeneratorService $icsGenerator, CarbonImmutable $cutoffDate): IcsContent
{
$appUrl = Config::string('app.url');
$appHost = parse_url($appUrl, \PHP_URL_HOST);
if (empty($appHost)) {
throw new \UnexpectedValueException('Invalid app URL configuration');
}
$appName = Config::string('app.name', 'La Boutique de Cocotte');
$closureTime = $cutoffDate->format('G') . 'h';
$eventStart = $cutoffDate->subHours(2);
$eventEnd = $eventStart->addMinutes(15);
return $icsGenerator->generate(new IcsContentDto(
uid: 'reminder-' . $eventStart->format('Y-m-d') . '@' . $appHost,
summary: trans('Place my order :appname', [
'appname' => $appName,
]),
description: trans('Remember to validate your order before :closureTime on :url', [
'closureTime' => $closureTime,
'url' => $appHost,
]),
startsAt: $eventStart,
endsAt: $eventEnd,
url: $appUrl,
));
}
private function mapEmployeeToShopper(Employee $employee): Shopper
{
$customer = $employee->customer;
Assert::isInstanceOf($customer, Customer::class);
2026-06-14 21:32:07 +02:00
return new Shopper(
id: $customer->getId(),
email: $customer->email,
matricule: clone $employee->matricule,
nom: $employee->nom,
prenom: $employee->prenom,
startDate: $employee->start_date !== null
? CarbonImmutable::instance($employee->start_date)
: CarbonImmutable::now(),
endDate: $employee->end_date !== null
? CarbonImmutable::instance($employee->end_date)
: null,
etablissement: $employee->etablissement,
site: $employee->site,
service: $employee->service,
);
2026-06-14 21:32:07 +02:00
}
private function canNotifyEmployee(Employee $employee): bool
{
$customer = $employee->customer;
return $customer instanceof Customer
&& Gate::forUser($customer)->check('customerPassOrders');
2026-06-14 21:32:07 +02:00
}
}