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 $windowsByShopId */ $windowsByShopId = []; /** @var array $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 $employees */ $this->processChunk( $employees, $schedulingService, $shopperService, $icsGenerator, $cache, $targetFriday, $weekKey, $windowsByShopId, $icsByCutoffKey, ); }, 'id' ); } /** * @param \Illuminate\Database\Eloquent\Collection $employees * @param array $windowsByShopId * @param array $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 $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); $employee->notify(new MissingOrderReminderNotification($pickupDay, $cutoffDate, $icsContent)); } } private function reminderCacheKey(string $weekKey, int $employeeId): string { return 'missing-order-reminder:' . $weekKey . ':' . $employeeId; } /** * @param list $matricules * @param list $pickupDates * @return array */ 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); 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, ); } private function canNotifyEmployee(Employee $employee): bool { $customer = $employee->customer; return $customer instanceof Customer && Gate::forUser($customer)->check('customerPassOrders'); } }