format('Y-m-d'); } public function handle( Executor $executor, ClaimTodayOrderReminder $claimAction, ReleaseTodayOrderReminder $releaseAction, ): void { $today = Date::now()->format('Y-m-d'); Order::query() ->with(['lines', 'shop']) ->whereDate('pickup_day', $today) ->where('status', OrderStatus::VALIDATED) ->whereNull('reminded_at') ->chunkById( self::CHUNK_SIZE, function (Collection $orders) use ($executor, $claimAction, $releaseAction): void { /** @var \Illuminate\Database\Eloquent\Collection $orders */ $this->processChunk($orders, $executor, $claimAction, $releaseAction); }, 'id' ); } /** * @param \Illuminate\Database\Eloquent\Collection $orders */ private function processChunk( Collection $orders, Executor $executor, ClaimTodayOrderReminder $claimAction, ReleaseTodayOrderReminder $releaseAction, ): void { $matricules = $orders ->map(fn (Order $order): string => $order->employee->matricule->value) ->unique() ->values(); $employees = Employee::query() ->with('customer') ->whereIn('matricule', $matricules) ->get() ->keyBy(fn (Employee $employee): string => $employee->matricule->value); foreach ($orders as $order) { $employee = $employees->get($order->employee->matricule->value); if (! $employee instanceof Employee) { continue; } $dto = $this->toDto($order, $employee); $remindedAt = CarbonImmutable::now()->utc()->startOfSecond(); $claimed = $executor->execute( $claimAction, new ClaimTodayOrderReminderInput($order->getId(), $remindedAt), ); if (! $claimed) { continue; } try { $this->notifyEmployee($employee, $dto); } catch (\Throwable $e) { try { $executor->execute( $releaseAction, new ReleaseTodayOrderReminderInput($order->getId(), $remindedAt), ); } catch (\Throwable $releaseException) { report($releaseException); } throw $e; } } } private function notifyEmployee(Employee $employee, OrderReminderDto $dto): void { $employee->notify(new OrderTodayReminderNotification($dto)); } private function toDto(Order $order, Employee $employee): OrderReminderDto { $linesDto = []; foreach ($order->lines as $line) { $linesDto[] = new OrderReminderLineDto( name: $line->product->name ?? '', quantity: $line->quantity, priceKgTtc: $this->moneyFormatter->format($line->product->priceKgTtc), totalTtc: $this->moneyFormatter->format($line->total_ttc), ); } return new OrderReminderDto( firstname: $employee->prenom, lastname: $employee->nom, reference: (string) $order->reference, total: $this->moneyFormatter->format($order->total), pickupDayFormatted: $order->pickup_day ? $order->pickup_day->translatedFormat('l j F Y') : '', lines: $linesDto, shopName: $order->shop ? $order->shop->name : '', shopAddress: $order->shop ? $order->shop->address : '', shopPostcode: $order->shop ? $order->shop->postcode : '', shopCity: $order->shop ? $order->shop->city : '' ); } }