ldc-cocotte/tests/Feature/App/Jobs/SendReminderMailTest.php

182 lines
7.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature\App\Jobs;
use App\Cqs\Actions\Orders\ClaimTodayOrderReminder;
use App\Cqs\Actions\Orders\ReleaseTodayOrderReminder;
use App\Jobs\SendReminderMail;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\Shop;
use App\Notifications\OrderTodayReminderNotification;
use App\Services\ActionExecutorService;
use Domain\Enums\OrderStatus;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
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 Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository as CacheRepository;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Money\Currency;
use Money\Money;
use Money\MoneyFormatter;
use Psr\Log\NullLogger;
use Shared\Helpers\UuidHelper;
describe('SendReminderMail job', function (): void {
it('sends today reminder once and marks orders as reminded idempotently', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
Notification::fake();
Date::setTestNow('2026-11-20 10:00:00');
$shop = Shop::factory()->create();
$customer = Customer::query()->forceCreate([
'email' => new Email('today-reminder@example.com'),
'hashcode' => (string) Str::uuid(),
]);
$employee = Employee::query()->forceCreate([
'customer_id' => $customer->id,
'matricule' => new Matricule('5234567'),
'nom' => 'Bernard',
'prenom' => 'Alice',
'code' => new Code('MNQ2345'),
'etablissement' => new ShopperEstablishmentCode('01'),
'site' => new ShopperSiteCode('SITE'),
'service' => new ShopperServiceCode('01'),
]);
$order = Order::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'shop_id' => $shop->id,
'reference' => new OrderReference(UuidHelper::v7()),
'status' => OrderStatus::VALIDATED->value,
'total' => new Money(3000, new Currency('EUR')),
'employee' => new OrderEmployee(
new Matricule('5234567'),
'Alice',
'Bernard',
new ShopperEstablishmentCode('01'),
new ShopperSiteCode('SITE'),
new ShopperServiceCode('01'),
),
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'),
'pickup_day' => '2026-11-20',
]);
/** @var MoneyFormatter&\Mockery\MockInterface $formatter */
$formatter = \Mockery::mock(MoneyFormatter::class);
$formatter->shouldReceive('format')->once()->andReturn('30,00 €');
$executor = new ActionExecutorService(
new LaravelCacheLock(new CacheRepository(new ArrayStore())),
new NullLogger(),
new LaravelDomainEventDispatcher(),
);
$claimAction = new ClaimTodayOrderReminder();
$releaseAction = new ReleaseTodayOrderReminder();
$job = new SendReminderMail($formatter);
// WHEN
$job->handle($executor, $claimAction, $releaseAction);
// Re-running on same day (e.g. retry or duplicate run) must not notify twice.
$job->handle($executor, $claimAction, $releaseAction);
// THEN
Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1);
expect($order->fresh()?->reminded_at)->not->toBeNull()
->and($job->uniqueId())->toBe('2026-11-20')
->and(config('queue.connections.redis.after_commit'))->toBeTrue();
Date::setTestNow();
});
it('releases reminded_at when notification queue dispatch fails so retry can remind the order', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
Date::setTestNow('2026-11-20 10:00:00');
$shop = Shop::factory()->create();
$customer = Customer::query()->forceCreate([
'email' => new Email('retry-reminder@example.com'),
'hashcode' => (string) Str::uuid(),
]);
$employee = Employee::query()->forceCreate([
'customer_id' => $customer->id,
'matricule' => new Matricule('6234567'),
'nom' => 'Martin',
'prenom' => 'Luc',
'code' => new Code('PQR2345'),
'etablissement' => new ShopperEstablishmentCode('01'),
'site' => new ShopperSiteCode('SITE'),
'service' => new ShopperServiceCode('01'),
]);
$order = Order::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'shop_id' => $shop->id,
'reference' => new OrderReference(UuidHelper::v7()),
'status' => OrderStatus::VALIDATED->value,
'total' => new Money(3000, new Currency('EUR')),
'employee' => new OrderEmployee(
new Matricule('6234567'),
'Luc',
'Martin',
new ShopperEstablishmentCode('01'),
new ShopperSiteCode('SITE'),
new ShopperServiceCode('01'),
),
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '75000', 'Paris'),
'pickup_day' => '2026-11-20',
]);
/** @var MoneyFormatter&\Mockery\MockInterface $formatter */
$formatter = \Mockery::mock(MoneyFormatter::class);
$formatter->shouldReceive('format')->twice()->andReturn('30,00 €');
$executor = new ActionExecutorService(
new LaravelCacheLock(new CacheRepository(new ArrayStore())),
new NullLogger(),
new LaravelDomainEventDispatcher(),
);
$claimAction = new ClaimTodayOrderReminder();
$releaseAction = new ReleaseTodayOrderReminder();
$job = new SendReminderMail($formatter);
Notification::shouldReceive('send')
->once()
->andThrow(new \RuntimeException('Redis queue unavailable'));
// WHEN (first attempt fails during queue dispatch)
expect(fn () => $job->handle($executor, $claimAction, $releaseAction))
->toThrow(\RuntimeException::class, 'Redis queue unavailable');
// THEN (reminded_at was released back to null)
expect($order->fresh()?->reminded_at)->toBeNull();
// WHEN (retry succeeds after queue recovers)
Notification::clearResolvedInstances();
Notification::fake();
$job->handle($executor, $claimAction, $releaseAction);
// THEN
Notification::assertSentToTimes($employee, OrderTodayReminderNotification::class, 1);
expect($order->fresh()?->reminded_at)->not->toBeNull();
Date::setTestNow();
});
});