ldc-cocotte/app/Jobs/SendReminderMail.php
Jérémy Munsch efbd507ac9
feat(jobs): implement unique job handling for reminders
Added ShouldBeUnique interface to SendMissingOrderReminderJob and SendReminderMail for unique job processing.
2026-11-15 20:39:57 +01:00

98 lines
3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Dto\OrderReminderDto;
use App\Dto\OrderReminderLineDto;
use App\Models\Employee;
use App\Models\Order;
use App\Notifications\OrderTodayReminderNotification;
use Domain\Enums\OrderStatus;
use Domain\Models\ValueObjects\Matricule;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Date;
use Money\MoneyFormatter;
class SendReminderMail implements ShouldBeUnique, ShouldQueue
{
use Queueable;
public int $uniqueFor = 3600;
public function __construct(
private readonly MoneyFormatter $moneyFormatter
) {
}
public function uniqueId(): string
{
return Date::now()->format('Y-m-d');
}
public function handle(): void
{
$orders = Order::query()
->with(['lines', 'shop'])
->whereDate('pickup_day', now()->format('Y-m-d'))
->where('status', OrderStatus::VALIDATED)
->get();
$matricules = $orders
->map(fn (Order $order): Matricule => $order->employee->matricule)
->unique();
$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;
}
$this->notifyEmployee(
$employee,
$this->toDto($order, $employee)
);
}
}
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 : ''
);
}
}