feat(jobs): handle shop pickup exceptions, chunking, and cache deduplication in SendMissingOrderReminderJob

This commit is contained in:
Jérémy Munsch 2026-11-15 21:39:33 +01:00
parent 3d4c4f74de
commit c427b60210
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
5 changed files with 497 additions and 53 deletions

View file

@ -5,24 +5,27 @@ declare(strict_types=1);
namespace App\Jobs;
use App\Dto\IcsContentDto;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Notifications\MissingOrderReminderNotification;
use App\Services\IcsGeneratorService;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Domain\Enums\OrderStatus;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\IcsContent;
use Domain\Models\ValueObjects\Matricule;
use Domain\Services\PickupSchedulingService;
use Domain\Services\ShopperService;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Gate;
use Webmozart\Assert\Assert;
class SendMissingOrderReminderJob implements ShouldBeUnique, ShouldQueue
{
@ -34,31 +37,182 @@ class SendMissingOrderReminderJob implements ShouldBeUnique, ShouldQueue
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, IcsGeneratorService $icsGenerator): void
{
$pickupDay = Carbon::now()->next($schedulingService->getPickupDay()->value);
$employees = $this->getEmployeesToNotify($pickupDay);
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');
if ($employees->isEmpty()) {
/** @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;
}
$cutoffDate = CarbonImmutable::instance(
$schedulingService->getPeriodForPickupDate($pickupDay)->getStartDate()
)->setTimezone('Europe/Paris');
$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,
))),
);
$icsContent = $this->generateIcsContent($icsGenerator, $cutoffDate);
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);
foreach ($employees as $employee) {
$employee->notify(new MissingOrderReminderNotification($pickupDay, $cutoffDate, $icsContent));
}
}
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');
@ -88,27 +242,34 @@ class SendMissingOrderReminderJob implements ShouldBeUnique, ShouldQueue
));
}
/** @return Collection<int,\App\Models\Employee> */
private function getEmployeesToNotify(CarbonInterface $pickupDay): Collection
private function mapEmployeeToShopper(Employee $employee): Shopper
{
$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();
$customer = $employee->customer;
Assert::isInstanceOf($customer, Customer::class);
return Employee::query()
->with('customer')
->whereNotIn('matricule', $excludedMatricules)
->get()
->filter(fn (Employee $employee): bool => $this->canNotifyEmployee($employee));
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 && Gate::forUser($customer)->check('customerPassOrders');
return $customer instanceof Customer
&& Gate::forUser($customer)->check('customerPassOrders');
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Domain\Models\ValueObjects;
use Carbon\CarbonImmutable;
final readonly class PickupWindow
{
public function __construct(
public PickupTimeSlot $timeSlot,
public CarbonImmutable $deadline,
) {
}
}

View file

@ -12,6 +12,7 @@ use Domain\Models\Entities\PickupExceptionOnDate;
use Domain\Models\Entities\Shop;
use Domain\Models\ValueObjects\EditablePickupExceptionForShop;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\PickupWindow;
use Domain\Models\ValueObjects\ShopPickupOverride;
use Domain\Ports\Repositories\PickupExceptionRepository;
@ -111,6 +112,23 @@ class PickupSchedulingService
}, $allExceptions);
}
public function getPickupWindowFor(Shop $shop, CarbonInterface $targetPickupDay): ?PickupWindow
{
$todayDate = $this->getNow()->startOfDay();
$targetDate = CarbonImmutable::createFromInterface($targetPickupDay)
->setTimezone(self::CUTOFF_TIME_ZONE)
->startOfDay();
if ($targetDate->lessThanOrEqualTo($todayDate)) {
return null;
}
$coveredPeriod = CarbonPeriod::create($todayDate, $targetDate);
$pickupExceptionList = $this->pickupExceptionRepository->getExceptionsForShop($shop->id(), $coveredPeriod);
return $this->resolveWindowForDate($targetDate, $pickupExceptionList);
}
/** @return \Domain\Models\ValueObjects\PickupTimeSlot[] */
public function getTimeSlotsFor(Shop $shop, \DateTimeInterface $until): array
{
@ -129,21 +147,10 @@ class PickupSchedulingService
fn (CarbonInterface $date) => $date->isDayOfWeek(self::PICKUP_DAY->value)
);
$mappedSlots = array_map(function (CarbonInterface $date) use ($pickupExceptionList) {
$pickupDayDate = CarbonImmutable::createFromInterface($date);
$shopPickupExceptionForTheDate = null;
foreach ($pickupExceptionList as $ex) {
if ($pickupDayDate->isSameDay($ex->exception->date)) {
$shopPickupExceptionForTheDate = $ex;
break;
}
}
return $shopPickupExceptionForTheDate !== null
? $this->getTimeSlotForException($shopPickupExceptionForTheDate)
: $this->getTimeSlotForPickupDay($pickupDayDate);
}, $filteredDates);
$mappedSlots = array_map(
fn (CarbonInterface $date): ?PickupTimeSlot => $this->resolveWindowForDate($date, $pickupExceptionList)?->timeSlot,
$filteredDates,
);
$validSlots = array_filter($mappedSlots);
usort($validSlots, fn (PickupTimeSlot $a, PickupTimeSlot $b) => $a->getAt() <=> $b->getAt());
@ -151,18 +158,38 @@ class PickupSchedulingService
return $validSlots;
}
protected function getTimeSlotForPickupDay(CarbonInterface $pickupDayDate): ?PickupTimeSlot
/**
* @param \Domain\Models\ValueObjects\ShopPickupOverride[] $pickupExceptionList
*/
protected function resolveWindowForDate(CarbonInterface $pickupDayDate, array $pickupExceptionList): ?PickupWindow
{
$date = CarbonImmutable::createFromInterface($pickupDayDate);
$shopPickupExceptionForTheDate = null;
foreach ($pickupExceptionList as $ex) {
if ($date->isSameDay($ex->exception->date)) {
$shopPickupExceptionForTheDate = $ex;
break;
}
}
return $shopPickupExceptionForTheDate !== null
? $this->resolveWindowForException($shopPickupExceptionForTheDate)
: $this->resolveWindowForPickupDay($date);
}
protected function resolveWindowForPickupDay(CarbonInterface $pickupDayDate): ?PickupWindow
{
$defaultDeadline = $this->getDefaultDeadline($pickupDayDate);
// ? Have we reached the default standard deadline ?
return $this->isBefore($defaultDeadline)
// * Nominal pipeline: timeslot matches standard pickup day
? $this->createTimeSlot($pickupDayDate)
? new PickupWindow($this->createTimeSlot($pickupDayDate), $defaultDeadline)
: null;
}
protected function getTimeSlotForException(ShopPickupOverride $shopPickupException): ?PickupTimeSlot
protected function resolveWindowForException(ShopPickupOverride $shopPickupException): ?PickupWindow
{
if (! $shopPickupException->hasReplacement() || $shopPickupException->replacementDate === null) {
return null;
@ -172,10 +199,20 @@ class PickupSchedulingService
$deadline = $shopPickupException->effectiveDeadline($defaultDeadline);
return $this->isBefore($deadline)
? $this->createTimeSlot($shopPickupException->replacementDate->toImmutable())
? new PickupWindow($this->createTimeSlot($shopPickupException->replacementDate->toImmutable()), $deadline)
: null;
}
protected function getTimeSlotForPickupDay(CarbonInterface $pickupDayDate): ?PickupTimeSlot
{
return $this->resolveWindowForPickupDay($pickupDayDate)?->timeSlot;
}
protected function getTimeSlotForException(ShopPickupOverride $shopPickupException): ?PickupTimeSlot
{
return $this->resolveWindowForException($shopPickupException)?->timeSlot;
}
protected function createTimeSlot(CarbonInterface $forDate): PickupTimeSlot
{
return new PickupTimeSlot(
@ -211,6 +248,6 @@ class PickupSchedulingService
protected function getNow(): CarbonImmutable
{
return CarbonImmutable::createFromInterface(new \DateTimeImmutable());
return CarbonImmutable::now();
}
}

View file

@ -5,29 +5,48 @@ declare(strict_types=1);
use App\Jobs\SendMissingOrderReminderJob;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\Shop;
use App\Notifications\MissingOrderReminderNotification;
use App\Services\IcsGeneratorService;
use Carbon\CarbonImmutable;
use Domain\Enums\OrderStatus;
use Domain\Enums\RepeatFrequency;
use Domain\Models\Entities\PickupExceptionOnDate;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\PickupExceptionId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Models\ValueObjects\ShopPickupOverride;
use Domain\Ports\Repositories\PickupExceptionRepository;
use Domain\Services\PickupSchedulingService;
use Domain\Services\ShopperService;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository as CacheRepository;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Money\Currency;
use Money\Money;
use Ramsey\Uuid\Uuid;
describe('SendMissingOrderReminderJob', function (): void {
it('dispatches MissingOrderReminderNotification with precomputed cutoff and ICS content', function (): void {
it('dispatches MissingOrderReminderNotification once per week with precomputed cutoff and ICS content', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
Notification::fake();
Config::set('app.url', 'https://cocotte.example.com');
Config::set('app.name', 'Cocotte Test');
Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am
Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am -> Friday 2026-11-20
Shop::factory()->create(['default' => true]);
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
@ -50,13 +69,21 @@ describe('SendMissingOrderReminderJob', function (): void {
]);
$pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class);
$schedulingService = new PickupSchedulingService($pickupExceptionRepo);
$icsGenerator = new IcsGeneratorService('Cocotte Test');
$pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([]);
$schedulingService = new PickupSchedulingService($pickupExceptionRepo);
$shopperService = $this->app->make(ShopperService::class);
$icsGenerator = new IcsGeneratorService('Cocotte Test');
$cache = new CacheRepository(new ArrayStore());
// WHEN
new SendMissingOrderReminderJob()->handle($schedulingService, $icsGenerator);
$job = new SendMissingOrderReminderJob();
$job->handle($schedulingService, $shopperService, $icsGenerator, $cache);
// Second invocation within the same week must be idempotent.
$job->handle($schedulingService, $shopperService, $icsGenerator, $cache);
// THEN
Notification::assertSentToTimes($employee, MissingOrderReminderNotification::class, 1);
Notification::assertSentTo(
$employee,
MissingOrderReminderNotification::class,
@ -69,6 +96,179 @@ describe('SendMissingOrderReminderJob', function (): void {
}
);
expect($cache->has('missing-order-reminder:2026-W47:' . $employee->id))->toBeTrue();
Date::setTestNow();
});
it('skips employees when their shop is closed on pickup day without replacement', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
Notification::fake();
Config::set('app.url', 'https://cocotte.example.com');
Config::set('app.name', 'Cocotte Test');
Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am -> Friday 2026-11-20
Shop::factory()->create(['default' => true]);
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'email' => new Email('closed-shop@example.com'),
'hashcode' => (string) Str::uuid(),
]);
/** @var Employee $employee */
$employee = Employee::query()->forceCreate([
'customer_id' => $customer->id,
'matricule' => new Matricule('2234567'),
'nom' => 'Martin',
'prenom' => 'Paul',
'code' => new Code('DEF1234'),
'etablissement' => new ShopperEstablishmentCode('01'),
'site' => new ShopperSiteCode('SITE'),
'service' => new ShopperServiceCode('01'),
'start_date' => CarbonImmutable::now()->subMonth(),
'end_date' => CarbonImmutable::now()->addMonth(),
]);
$exception = new PickupExceptionOnDate(
id: new PickupExceptionId(Uuid::uuid7()),
date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'),
label: 'Fermeture exceptionnelle',
repeatable: false,
repeatFrequency: RepeatFrequency::YEARLY,
autoUpdated: false,
);
$override = new ShopPickupOverride($exception, replacementDate: null, orderDeadlineAt: null);
$pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class);
$pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([$override]);
$schedulingService = new PickupSchedulingService($pickupExceptionRepo);
$shopperService = $this->app->make(ShopperService::class);
$icsGenerator = new IcsGeneratorService('Cocotte Test');
$cache = new CacheRepository(new ArrayStore());
// WHEN
new SendMissingOrderReminderJob()->handle(
$schedulingService,
$shopperService,
$icsGenerator,
$cache,
);
// THEN
Notification::assertNothingSent();
expect($cache->has('missing-order-reminder:2026-W47:' . $employee->id))->toBeFalse();
Date::setTestNow();
});
it('uses replacement pickup day and excludes employees who already ordered for replacement date', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
Notification::fake();
Config::set('app.url', 'https://cocotte.example.com');
Config::set('app.name', 'Cocotte Test');
Date::setTestNow('2026-11-16 08:00:00'); // Monday 8am -> Friday 2026-11-20 replaced by Thursday 2026-11-19
$shop = Shop::factory()->create(['default' => true]);
$orderedCustomer = Customer::query()->forceCreate([
'email' => new Email('ordered-repl@example.com'),
'hashcode' => (string) Str::uuid(),
]);
$orderedEmployee = Employee::query()->forceCreate([
'customer_id' => $orderedCustomer->id,
'matricule' => new Matricule('3234567'),
'nom' => 'Ordered',
'prenom' => 'Claire',
'code' => new Code('GHJ2345'),
'etablissement' => new ShopperEstablishmentCode('01'),
'site' => new ShopperSiteCode('SITE'),
'service' => new ShopperServiceCode('01'),
'start_date' => CarbonImmutable::now()->subMonth(),
'end_date' => CarbonImmutable::now()->addMonth(),
]);
Order::forceCreate([
'id' => Uuid::uuid7()->toString(),
'shop_id' => $shop->id,
'reference' => new OrderReference(Uuid::uuid7()),
'status' => OrderStatus::VALIDATED->value,
'total' => new Money(2500, new Currency('EUR')),
'employee' => new OrderEmployee(
new Matricule('3234567'),
'Claire',
'Ordered',
new ShopperEstablishmentCode('01'),
new ShopperSiteCode('SITE'),
new ShopperServiceCode('01'),
),
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'),
'pickup_day' => '2026-11-19',
]);
$missingCustomer = Customer::query()->forceCreate([
'email' => new Email('missing-repl@example.com'),
'hashcode' => (string) Str::uuid(),
]);
$missingEmployee = Employee::query()->forceCreate([
'customer_id' => $missingCustomer->id,
'matricule' => new Matricule('4234567'),
'nom' => 'Missing',
'prenom' => 'Luc',
'code' => new Code('KMN2345'),
'etablissement' => new ShopperEstablishmentCode('01'),
'site' => new ShopperSiteCode('SITE'),
'service' => new ShopperServiceCode('01'),
'start_date' => CarbonImmutable::now()->subMonth(),
'end_date' => CarbonImmutable::now()->addMonth(),
]);
$exception = new PickupExceptionOnDate(
id: new PickupExceptionId(Uuid::uuid7()),
date: CarbonImmutable::parse('2026-11-20', 'Europe/Paris'),
label: 'Décalage jeudi',
repeatable: false,
repeatFrequency: RepeatFrequency::YEARLY,
autoUpdated: false,
);
$override = new ShopPickupOverride(
$exception,
replacementDate: CarbonImmutable::parse('2026-11-19', 'Europe/Paris'),
orderDeadlineAt: CarbonImmutable::parse('2026-11-16 16:00:00', 'Europe/Paris'),
);
$pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class);
$pickupExceptionRepo->shouldReceive('getExceptionsForShop')->once()->andReturn([$override]);
$schedulingService = new PickupSchedulingService($pickupExceptionRepo);
$shopperService = $this->app->make(ShopperService::class);
$icsGenerator = new IcsGeneratorService('Cocotte Test');
$cache = new CacheRepository(new ArrayStore());
// WHEN
new SendMissingOrderReminderJob()->handle(
$schedulingService,
$shopperService,
$icsGenerator,
$cache,
);
// THEN
Notification::assertNotSentTo($orderedEmployee, MissingOrderReminderNotification::class);
Notification::assertSentTo(
$missingEmployee,
MissingOrderReminderNotification::class,
function (MissingOrderReminderNotification $notification) use ($missingEmployee): bool {
$rendered = $notification->toMail($missingEmployee)->render();
return str_contains((string) $rendered, '19/11/2026')
&& str_contains((string) $rendered, '16h');
}
);
Date::setTestNow();
});
});

View file

@ -10,6 +10,7 @@ use Domain\Models\Entities\Shop;
use Domain\Models\ValueObjects\Entities\PickupExceptionId;
use Domain\Models\ValueObjects\Entities\ShopId;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\PickupWindow;
use Domain\Models\ValueObjects\ShopPickupOverride;
use Domain\Ports\Repositories\PickupExceptionRepository;
use Domain\Services\PickupSchedulingService;
@ -397,6 +398,35 @@ describe('Pickup Scheduling Service', function (): void {
expect($hasFridayAtCutoff)->toBeTrue()
->and($hasFridayPastCutoff)->toBeFalse();
});
it('resolves nominal, replacement, and closed pickup windows for a target pickup day', function (): void {
// GIVEN
$now = CarbonImmutable::parse('2026-05-04 08:00:00');
$targetFriday = CarbonImmutable::parse('2026-05-08');
$shop = createTestShop(1);
$nominalService = createServiceWithExceptions($now);
$closedService = createServiceWithExceptions($now, [
createExceptionPivot(date: '2026-05-08', replacementDate: null, orderDeadlineAt: null),
]);
$replacedService = createServiceWithExceptions($now, [
createExceptionPivot(date: '2026-05-08', replacementDate: '2026-05-07', orderDeadlineAt: '2026-05-04 16:00:00'),
]);
// WHEN
$nominalWindow = $nominalService->getPickupWindowFor($shop, $targetFriday);
$closedWindow = $closedService->getPickupWindowFor($shop, $targetFriday);
$replacedWindow = $replacedService->getPickupWindowFor($shop, $targetFriday);
// THEN
expect($nominalWindow)->toBeInstanceOf(PickupWindow::class)
->and($nominalWindow?->timeSlot->getAt()->format('Y-m-d'))->toBe('2026-05-08')
->and($nominalWindow?->deadline->format('Y-m-d H:i'))->toBe('2026-05-04 14:00')
->and($closedWindow)->toBeNull()
->and($replacedWindow)->toBeInstanceOf(PickupWindow::class)
->and($replacedWindow?->timeSlot->getAt()->format('Y-m-d'))->toBe('2026-05-07')
->and($replacedWindow?->deadline->format('Y-m-d H:i'))->toBe('2026-05-04 16:00');
});
});
/**