diff --git a/app/Jobs/SendMissingOrderReminderJob.php b/app/Jobs/SendMissingOrderReminderJob.php index 80b903b0..4eaab14e 100644 --- a/app/Jobs/SendMissingOrderReminderJob.php +++ b/app/Jobs/SendMissingOrderReminderJob.php @@ -4,17 +4,22 @@ declare(strict_types=1); namespace App\Jobs; +use App\Dto\IcsContentDto; 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\ValueObjects\IcsContent; use Domain\Models\ValueObjects\Matricule; use Domain\Services\PickupSchedulingService; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Gate; class SendMissingOrderReminderJob implements ShouldQueue @@ -25,16 +30,55 @@ class SendMissingOrderReminderJob implements ShouldQueue public const int HOURS_BEFORE_CUTOFF = 6; - public function handle(PickupSchedulingService $schedulingService): void + public function handle(PickupSchedulingService $schedulingService, IcsGeneratorService $icsGenerator): void { - $pickupDay = Carbon::now()->next($schedulingService->getPickupDay()->value); - $employees = $this->getEmployeesToNotify($pickupDay); + $pickupDay = Carbon::now()->next($schedulingService->getPickupDay()->value); + $employees = $this->getEmployeesToNotify($pickupDay); + + if ($employees->isEmpty()) { + return; + } + + $cutoffDate = CarbonImmutable::instance( + $schedulingService->getPeriodForPickupDate($pickupDay)->getStartDate() + )->setTimezone('Europe/Paris'); + + $icsContent = $this->generateIcsContent($icsGenerator, $cutoffDate); foreach ($employees as $employee) { - $employee->notify(new MissingOrderReminderNotification($pickupDay)); + $employee->notify(new MissingOrderReminderNotification($pickupDay, $cutoffDate, $icsContent)); } } + 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, + )); + } + /** @return Collection */ private function getEmployeesToNotify(CarbonInterface $pickupDay): Collection { diff --git a/app/Notifications/MissingOrderReminderNotification.php b/app/Notifications/MissingOrderReminderNotification.php index 41344349..1291110b 100644 --- a/app/Notifications/MissingOrderReminderNotification.php +++ b/app/Notifications/MissingOrderReminderNotification.php @@ -4,15 +4,13 @@ declare(strict_types=1); namespace App\Notifications; -use App\Dto\IcsContentDto; use App\Jobs\SendMissingOrderReminderJob; use App\Models\Employee; use App\Models\Order; -use App\Services\IcsGeneratorService; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Domain\Enums\OrderStatus; -use Domain\Services\PickupSchedulingService; +use Domain\Models\ValueObjects\IcsContent; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; @@ -30,7 +28,9 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue private readonly string $appHost; public function __construct( - private readonly CarbonInterface $pickupDay + private readonly CarbonInterface $pickupDay, + private readonly CarbonInterface $cutoffDate, + private readonly IcsContent $icsContent, ) { $appUrl = Config::string('app.url'); $appHost = parse_url($appUrl, \PHP_URL_HOST); @@ -67,27 +67,10 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue public function toMail(mixed $notifiable): MailMessage { /** @var Employee $notifiable */ - $icsGenerator = app(IcsGeneratorService::class); - $schedulingService = app(PickupSchedulingService::class); - - $cutoffDate = $schedulingService->getPeriodForPickupDate($this->pickupDay) - ->getStartDate() - ->setTimezone('Europe/Paris'); - + $cutoffDate = CarbonImmutable::instance($this->cutoffDate)->setTimezone('Europe/Paris'); $closureTime = $cutoffDate->format('G') . 'h'; $reminderDay = $cutoffDate->translatedFormat('l'); - $reminderTime = $cutoffDate->copy()->subHours(2)->format('G') . 'h'; - - // The reminder event starts 2 hours before the cutoff on the cutoff day - $eventStart = CarbonImmutable::instance($cutoffDate)->subHours(2); - $eventEnd = $eventStart->addMinutes(15); - - $icsContent = $this->generateIcsContent( - $icsGenerator, - $eventStart, - $eventEnd, - $closureTime - ); + $reminderTime = $cutoffDate->subHours(2)->format('G') . 'h'; return (new MailMessage()) ->subject(trans(':time before order taking closes - :appname', [ @@ -103,32 +86,8 @@ class MissingOrderReminderNotification extends Notification implements ShouldQue 'appHost' => $this->appHost, 'appUrl' => $this->appUrl, ]) - ->attachData($icsContent, 'rappel-commande.ics', [ + ->attachData($this->icsContent->value, 'rappel-commande.ics', [ 'mime' => 'text/calendar', ]); } - - private function generateIcsContent( - IcsGeneratorService $icsGenerator, - CarbonInterface $eventStart, - CarbonInterface $eventEnd, - string $closureTime - ): string { - - $eventDto = new IcsContentDto( - uid: 'reminder-' . $eventStart->format('Y-m-d') . '@' . $this->appHost, - summary: trans('Place my order :appname', [ - 'appname' => $this->appName, - ]), - description: trans('Remember to validate your order before :closureTime on :url', [ - 'closureTime' => $closureTime, - 'url' => $this->appHost, - ]), - startsAt: $eventStart, - endsAt: $eventEnd, - url: $this->appUrl - ); - - return $icsGenerator->generate($eventDto); - } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 3cfc2d55..ef5a68ff 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -8,6 +8,7 @@ use App\Contracts\Executor; use App\Lib\PrivateS3Disk; use App\Lib\PublicS3Disk; use App\Services\ActionExecutorService; +use App\Services\IcsGeneratorService; use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; @@ -56,6 +57,13 @@ class AppServiceProvider extends ServiceProvider ); $this->app->bind(Executor::class, ActionExecutorService::class); + + $this->app->singleton( + IcsGeneratorService::class, + fn (): IcsGeneratorService => new IcsGeneratorService( + Config::string('app.name', 'La Boutique de Cocotte'), + ) + ); } /** diff --git a/app/Services/IcsGeneratorService.php b/app/Services/IcsGeneratorService.php index 28925cbc..a9f781a7 100644 --- a/app/Services/IcsGeneratorService.php +++ b/app/Services/IcsGeneratorService.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Services; use App\Dto\IcsContentDto; +use Domain\Models\ValueObjects\IcsContent; class IcsGeneratorService { @@ -16,7 +17,7 @@ class IcsGeneratorService } } - public function generate(IcsContentDto $event): string + public function generate(IcsContentDto $event): IcsContent { $dateFormat = 'Ymd\THis\Z'; $lines = [ @@ -40,7 +41,7 @@ class IcsGeneratorService $lines[] = 'END:VCALENDAR'; // NOTE: ICS files must have CRLF line endings - return implode("\r\n", $lines) . "\r\n"; + return new IcsContent(implode("\r\n", $lines) . "\r\n"); } private function escape(string $text): string diff --git a/domain/Models/ValueObjects/IcsContent.php b/domain/Models/ValueObjects/IcsContent.php new file mode 100644 index 00000000..942b94db --- /dev/null +++ b/domain/Models/ValueObjects/IcsContent.php @@ -0,0 +1,26 @@ +value; + } +} diff --git a/tests/Feature/Jobs/SendMissingOrderReminderJobTest.php b/tests/Feature/Jobs/SendMissingOrderReminderJobTest.php new file mode 100644 index 00000000..165b84eb --- /dev/null +++ b/tests/Feature/Jobs/SendMissingOrderReminderJobTest.php @@ -0,0 +1,74 @@ +forceCreate([ + 'email' => new Email('reminder@example.com'), + 'hashcode' => (string) Str::uuid(), + ]); + + /** @var Employee $employee */ + $employee = Employee::query()->forceCreate([ + 'customer_id' => $customer->id, + 'matricule' => new Matricule('1234567'), + 'nom' => 'Dupont', + 'prenom' => 'Jean', + 'code' => new Code('ABC1234'), + 'etablissement' => new ShopperEstablishmentCode('01'), + 'site' => new ShopperSiteCode('SITE'), + 'service' => new ShopperServiceCode('01'), + 'start_date' => CarbonImmutable::now()->subMonth(), + 'end_date' => CarbonImmutable::now()->addMonth(), + ]); + + $pickupExceptionRepo = \Mockery::mock(PickupExceptionRepository::class); + $schedulingService = new PickupSchedulingService($pickupExceptionRepo); + $icsGenerator = new IcsGeneratorService('Cocotte Test'); + + // WHEN + new SendMissingOrderReminderJob()->handle($schedulingService, $icsGenerator); + + // THEN + Notification::assertSentTo( + $employee, + MissingOrderReminderNotification::class, + function (MissingOrderReminderNotification $notification) use ($employee): bool { + $mail = $notification->toMail($employee); + + return count($mail->rawAttachments) === 1 + && $mail->rawAttachments[0]['name'] === 'rappel-commande.ics' + && str_contains((string) $mail->rawAttachments[0]['data'], 'BEGIN:VCALENDAR'); + } + ); + + Date::setTestNow(); + }); +}); diff --git a/tests/Unit/App/Services/IcsGeneratorServiceTest.php b/tests/Unit/App/Services/IcsGeneratorServiceTest.php index 064e92d3..8e542884 100644 --- a/tests/Unit/App/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/App/Services/IcsGeneratorServiceTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; +use Domain\Models\ValueObjects\IcsContent; use Illuminate\Support\Carbon; covers(IcsGeneratorService::class); @@ -38,7 +39,8 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics) + expect($ics)->toBeInstanceOf(IcsContent::class) + ->and($ics->value) ->toContain('BEGIN:VCALENDAR') ->toContain('PRODID:-//MyApp//NONSGML v1.0//EN') ->toContain('UID:uid-123') @@ -68,6 +70,7 @@ describe('IcsGeneratorService', function (): void { $ics = $service->generate($dto); // THEN - expect($ics)->toContain('URL:http://example.com'); + expect($ics)->toBeInstanceOf(IcsContent::class) + ->and($ics->value)->toContain('URL:http://example.com'); }); }); diff --git a/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php new file mode 100644 index 00000000..48111fa5 --- /dev/null +++ b/tests/Unit/Domain/Models/ValueObjects/IcsContentTest.php @@ -0,0 +1,37 @@ +value)->toBe($raw) + ->and((string) $ics)->toBe($raw); + }); + + it('rejects empty ICS content', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent(' ')) + ->toThrow(\InvalidArgumentException::class); + }); + + it('rejects ICS content missing BEGIN:VCALENDAR header', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent("BEGIN:VEVENT\r\nEND:VCALENDAR")) + ->toThrow(\InvalidArgumentException::class); + }); + + it('rejects ICS content missing END:VCALENDAR footer', function (): void { + // WHEN / THEN + expect(fn (): IcsContent => new IcsContent("BEGIN:VCALENDAR\r\nBEGIN:VEVENT")) + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index bbb41fee..b6375faa 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -46,6 +46,7 @@ use Domain\Services\OrderService; use Domain\Services\OrderTunnelService; use Domain\Services\PickupSchedulingService; use Domain\Services\ShopperService; +use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; use Shared\DDD\DomainEventDispatcher; @@ -158,7 +159,7 @@ function createOrderTunnelService( $regateService->shouldReceive('processOrder')->byDefault(); } - $orderLimitPolicy = new CustomerOrderLimitPolicy(500000, 500000); + $orderLimitPolicy = new CustomerOrderLimitPolicy(500000, 500000, new Currency('EUR')); return new OrderTunnelService( $eventDispatcher, diff --git a/tests/Unit/Services/IcsGeneratorServiceTest.php b/tests/Unit/Services/IcsGeneratorServiceTest.php index 9cfcf290..f9eecca0 100644 --- a/tests/Unit/Services/IcsGeneratorServiceTest.php +++ b/tests/Unit/Services/IcsGeneratorServiceTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); use App\Dto\IcsContentDto; use App\Services\IcsGeneratorService; use Carbon\CarbonImmutable; +use Domain\Models\ValueObjects\IcsContent; it('generates a valid ICS string', function () { // GIVEN @@ -26,7 +27,8 @@ it('generates a valid ICS string', function () { $ics = $service->generate($event); // THEN - expect($ics)->toContain('BEGIN:VCALENDAR') + expect($ics)->toBeInstanceOf(IcsContent::class) + ->and($ics->value)->toContain('BEGIN:VCALENDAR') ->toContain('VERSION:2.0') ->toContain('PRODID:-//La Boutique de Cocotte//NONSGML v1.0//EN') ->toContain('BEGIN:VEVENT')