feat(cqs): buffer domain events until commit and add action lifecycle hooks

This commit is contained in:
Jérémy Munsch 2026-11-14 22:00:11 +01:00
parent 79ae763e88
commit 6dfef2c7a1
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
21 changed files with 1141 additions and 319 deletions

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
*/
interface HandlesFailure
{
/**
* @param TInput $input
*/
public function onFailure(ActionInput $input, \Throwable $exception): void;
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Contracts;
/**
* @template TInput of \App\Contracts\ActionInput
* @template TResult
*/
interface HandlesSuccess
{
/**
* @param TInput $input
* @param TResult $result
*/
public function onSuccess(ActionInput $input, mixed $result): void;
}

View file

@ -8,7 +8,9 @@ use App\Attributes\Locked;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Enums\FinalizeOrderStatus;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
@ -26,9 +28,13 @@ use Webmozart\Assert\Assert;
* \App\Cqs\Actions\Orders\FinalizeOrderInput,
* \App\Cqs\Actions\Orders\FinalizeOrderOutput
* >
* @implements \App\Contracts\HandlesSuccess<
* \App\Cqs\Actions\Orders\FinalizeOrderInput,
* \App\Cqs\Actions\Orders\FinalizeOrderOutput
* >
*/
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
final class FinalizeOrder implements Action, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey
{
public function __construct(
private readonly OrderTunnelService $orderTunnelService,
@ -71,8 +77,6 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
try {
$order = $this->orderTunnelService->finalizeOrder($builder);
return FinalizeOrderOutput::success($order->reference);
} catch (ExpiredPickupTimeSlotException | UnorderableProductException | OrderLimitExceededException | WeeklyLimitExceededException $e) {
return match (true) {
$e instanceof ExpiredPickupTimeSlotException => FinalizeOrderOutput::expiredTimeSlot($e->getMessage()),
@ -81,5 +85,21 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
$e instanceof WeeklyLimitExceededException => FinalizeOrderOutput::weeklyLimitExceeded($e->getMessage()),
};
}
return FinalizeOrderOutput::success($order->reference);
}
/**
* @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input
* @param \App\Cqs\Actions\Orders\FinalizeOrderOutput $result
*/
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
Assert::isInstanceOf($input, FinalizeOrderInput::class);
if ($result instanceof FinalizeOrderOutput && $result->status === FinalizeOrderStatus::SUCCESS) {
$this->orderTunnelService->clearTunnelState();
}
}
}

View file

@ -1,28 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Listeners\Orders;
use Carbon\CarbonImmutable;
use Domain\Events\AnOrderHasBeenPlaced;
use Domain\Services\RegateService;
// NOTE: This has to be run in SYNC
class ProcessRegateOrderExport
{
public function __construct(
private readonly RegateService $regateService,
) {
}
public function handle(AnOrderHasBeenPlaced $event): void
{
$this->regateService->processOrder(
$event->reference,
$event->byMatricule,
CarbonImmutable::instance($event->pickupDay),
$event->lines
);
}
}

View file

@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Listeners;
use App\Mail\RegateOrderMail;
use Domain\Events\Dto\RegateOrderCsvGenerated;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
// NOTE: This has to be run in SYNC
class SendRegateOrderMail
{
private readonly Address $regateEmail;
public function __construct()
{
if (! Config::has('mail.to.regate')) {
throw new \UnexpectedValueException('Regate email address is not configured.');
}
$this->regateEmail = new Address(Config::string('mail.to.regate'));
}
public function handle(RegateOrderCsvGenerated $event): void
{
Mail::to($this->regateEmail)
->send(new RegateOrderMail(
$event->csvContent,
$event->fileName
));
}
}

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Providers;
use App\Services\MailRegateService;
use Domain\Ports\Directories\CodeDirectory;
use Domain\Ports\Directories\ShopDirectory;
use Domain\Ports\Repositories\BasketRepository;
@ -17,6 +18,7 @@ use Domain\Ports\Services\CsvGenerator;
use Domain\Ports\Services\CustomerAuthenticationService;
use Domain\Ports\Services\EmployeeImportStorageService;
use Domain\Ports\Services\EmployeeStatisticsService;
use Domain\Ports\Services\RegateService;
use Domain\Ports\Services\TransactionManager;
use Illuminate\Support\ServiceProvider;
use Infrastructure\Adapters\Directories\EloquentCodeDirectory;
@ -46,7 +48,9 @@ class DomainServiceProvider extends ServiceProvider
#[\Override]
public function register(): void
{
$this->app->singleton(
$this->app->scoped(LaravelDomainEventDispatcher::class);
$this->app->bind(
DomainEventDispatcher::class,
LaravelDomainEventDispatcher::class
);
@ -125,6 +129,11 @@ class DomainServiceProvider extends ServiceProvider
Lock::class,
LaravelCacheLock::class
);
$this->app->bind(
RegateService::class,
MailRegateService::class
);
}
/**

View file

@ -8,11 +8,14 @@ use App\Attributes\Locked;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\Executor;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Contracts\Query;
use App\Contracts\QueryInput;
use Illuminate\Support\Facades\DB;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Psr\Log\LoggerInterface;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
@ -22,6 +25,7 @@ final class ActionExecutorService implements Executor
public function __construct(
private readonly Lock $lock,
private readonly LoggerInterface $logger,
private readonly LaravelDomainEventDispatcher $eventDispatcher,
) {
}
@ -47,11 +51,7 @@ final class ActionExecutorService implements Executor
return $this->executeWithLock($executable, $input, $actionName, $lockedAttribute);
}
return $this->executeWithinTransaction(
$executable,
$input,
$actionName
);
return $this->executeWithoutLock($executable, $input, $actionName);
}
$this->assertInputIsQuery($input);
@ -120,7 +120,7 @@ final class ActionExecutorService implements Executor
: ($locked->key ?? $executable::class);
try {
return $this->lock->synchronize(
$result = $this->lock->synchronize(
key: $lockKey,
callback: fn (): mixed => $this->executeWithinTransaction($executable, $input, $actionName),
ttlSeconds: $locked->ttlSeconds,
@ -138,7 +138,59 @@ final class ActionExecutorService implements Executor
return $executable->onLockTimeout($input);
}
$this->runFailureHook($executable, $input, $e);
throw $e;
} catch (\Throwable $e) {
$this->runFailureHook($executable, $input, $e);
throw $e;
}
$this->runPostCommitHooks($executable, $input, $result);
return $result;
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function executeWithoutLock(
Action $executable,
ActionInput $input,
string $actionName,
): mixed {
try {
$result = $this->executeWithinTransaction($executable, $input, $actionName);
} catch (\Throwable $e) {
$this->runFailureHook($executable, $input, $e);
throw $e;
}
$this->runPostCommitHooks($executable, $input, $result);
return $result;
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function runFailureHook(
Action $executable,
ActionInput $input,
\Throwable $exception,
): void {
if ($executable instanceof HandlesFailure) {
$executable->onFailure($input, $exception);
}
}
@ -151,13 +203,37 @@ final class ActionExecutorService implements Executor
*/
private function executeWithinTransaction(Action $executable, ActionInput $input, string $actionName): mixed
{
return DB::transaction(function () use ($executable, $input, $actionName): mixed {
$result = $executable($input);
$this->eventDispatcher->beginBuffering();
$this->logger->info("[Action] Succeeded {$actionName}");
try {
return DB::transaction(function () use ($executable, $input, $actionName): mixed {
$result = $executable($input);
return $result;
});
$this->logger->info("[Action] Succeeded {$actionName}");
return $result;
});
} catch (\Throwable $e) {
$this->eventDispatcher->discard();
throw $e;
}
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
*
* @param TAction $executable
* @param TActionInput $input
*/
private function runPostCommitHooks(Action $executable, ActionInput $input, mixed $result): void
{
$this->eventDispatcher->flush();
if ($executable instanceof HandlesSuccess) {
$executable->onSuccess($input, $result);
}
}
/**

View file

@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Mail\RegateOrderMail;
use Carbon\CarbonImmutable;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Ports\Services\CsvGenerator;
use Domain\Ports\Services\RegateService;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\Config;
final class MailRegateService implements RegateService
{
private readonly Address $regateEmail;
/** @var string[] */
private array $header = [
'CodeArt',
'Client livré code',
'ean13',
'Type de commande',
'Unité Elem. Appro',
'mode de commande',
'Pcb Art',
'Date livraison',
'Qté commandée',
'Num Cde Client',
];
public function __construct(
private readonly CsvGenerator $csvGenerator,
private readonly Mailer $mailer,
) {
if (! Config::has('mail.to.regate')) {
throw new \UnexpectedValueException('Regate email address is not configured.');
}
$this->regateEmail = new Address(Config::string('mail.to.regate'));
}
/**
* @param \Domain\Events\Dto\OrderPlacedLine[] $lines
*
* @throws \Domain\Exceptions\OrderTunnel\RegateExportFailedException
*/
#[\Override]
public function processOrder(
OrderReference $reference,
Matricule $employeeMatricule,
CarbonImmutable $pickupDay,
array $lines,
): void {
$rows = [];
foreach ($lines as $line) {
$rows[] = [
(string) $line->productIncoId->value,
$employeeMatricule->value,
(string) $line->productIncoId->value,
'commande ferme',
(string) $line->productOrderUnit->value,
$line->productOrderUnit->toRegateCode(),
'',
$pickupDay->format('d/m/Y'),
(string) $line->quantity,
(string) $reference,
];
}
$csvContent = $this->csvGenerator->generate($this->header, $rows);
$now = CarbonImmutable::now();
$fileName = sprintf(
'BTQ-%s-%s%s.csv',
$reference,
$now->format('Ymd_His'),
\microtime(true)
);
try {
$this->mailer->to($this->regateEmail)
->send(new RegateOrderMail($csvContent, $fileName));
} catch (\Throwable $e) {
throw new RegateExportFailedException($e->getMessage(), $e);
}
}
}

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
namespace Domain\Events\Dto;
use Shared\DDD\Event;
class RegateOrderCsvGenerated implements Event
{
public function __construct(
public readonly string $csvContent,
public readonly string $fileName
) {
}
}

View file

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Domain\Exceptions\OrderTunnel;
final class RegateExportFailedException extends \DomainException
{
public function __construct(string $message = 'Failed to export order to Regate.', ?\Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
}

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Domain\Ports\Services;
use Carbon\CarbonImmutable;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
interface RegateService
{
/**
* @param \Domain\Events\Dto\OrderPlacedLine[] $lines
*
* @throws \Domain\Exceptions\OrderTunnel\RegateExportFailedException
*/
public function processOrder(
OrderReference $reference,
Matricule $employeeMatricule,
CarbonImmutable $pickupDay,
array $lines,
): void;
}

View file

@ -13,6 +13,7 @@ use Domain\Enums\OrderTunnelStep;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Models\Entities\Basket;
@ -27,6 +28,7 @@ use Domain\Ports\Repositories\ShopperRepository;
use Domain\Ports\Repositories\ShopRepository;
use Domain\Ports\Services\EmployeeStatisticsService;
use Domain\Ports\Services\OrderBuilderSessionManager;
use Domain\Ports\Services\RegateService;
use Shared\DDD\DomainEventDispatcher;
class OrderTunnelService
@ -45,6 +47,7 @@ class OrderTunnelService
private readonly ShopperRepository $shopperRepository,
private readonly OrderService $orderService,
private readonly EmployeeStatisticsService $employeeStatisticsService,
private readonly RegateService $regateService,
) {
}
@ -186,6 +189,7 @@ class OrderTunnelService
* @throws OrderLimitExceededException
* @throws ExpiredPickupTimeSlotException
* @throws UnorderableProductException
* @throws RegateExportFailedException
*/
public function finalizeOrder(OrderBuilderCompleted $builder): Order
{
@ -218,14 +222,26 @@ class OrderTunnelService
$this->orderRepository->persist($order);
$this->eventDispatcher->dispatch($order->toPlacedEvent());
$placedEvent = $order->toPlacedEvent();
$this->basketService->empty();
$this->orderBuilderSessionManager->clear();
$this->regateService->processOrder(
$order->reference,
$order->employee->matricule,
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
$placedEvent->lines,
);
$this->eventDispatcher->dispatch($placedEvent);
return $order;
}
public function clearTunnelState(): void
{
$this->basketService->empty();
$this->orderBuilderSessionManager->clear();
}
/**
* @throws \Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException
*/

View file

@ -1,79 +0,0 @@
<?php
declare(strict_types=1);
namespace Domain\Services;
use Carbon\CarbonImmutable;
use Domain\Events\Dto\RegateOrderCsvGenerated;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Ports\Services\CsvGenerator;
use Shared\DDD\DomainEventDispatcher;
class RegateService
{
/** @var string[] */
private array $header = [
'CodeArt',
'Client livré code',
'ean13',
'Type de commande',
'Unité Elem. Appro',
'mode de commande',
'Pcb Art',
'Date livraison',
'Qté commandée',
'Num Cde Client',
];
public function __construct(
private readonly CsvGenerator $csvGenerator,
private readonly DomainEventDispatcher $dispatcher
) {
}
/**
* @param \Domain\Events\Dto\OrderPlacedLine[] $lines
*/
public function processOrder(
OrderReference $reference,
Matricule $employeeMatricule,
CarbonImmutable $pickupDay,
array $lines
): void {
$rows = [];
foreach ($lines as $line) {
array_push(
$rows,
[
(string) $line->productIncoId->value,
$employeeMatricule->value,
(string) $line->productIncoId->value,
'commande ferme',
(string) $line->productOrderUnit->value,
$line->productOrderUnit->toRegateCode(),
'',
$pickupDay->format('d/m/Y'),
(string) $line->quantity,
(string) $reference,
]
);
}
$csvContent = $this->csvGenerator->generate($this->header, $rows);
$now = CarbonImmutable::now();
$fileName = sprintf(
'BTQ-%s-%s%s.csv',
$reference,
$now->format('Ymd_His'),
\microtime(true)
);
$this->dispatcher->dispatch(
new RegateOrderCsvGenerated($csvContent, $fileName)
);
}
}

View file

@ -10,8 +10,58 @@ use Shared\DDD\Event as LibEvent;
class LaravelDomainEventDispatcher implements DomainEventDispatcher
{
private int $bufferDepth = 0;
/** @var list<\Shared\DDD\Event> */
private array $bufferedEvents = [];
public function beginBuffering(): void
{
$this->bufferDepth++;
}
#[\Override]
public function dispatch(LibEvent $event): void
{
if ($this->bufferDepth > 0) {
$this->bufferedEvents[] = $event;
return;
}
Event::dispatch($event);
}
public function flush(): void
{
if ($this->bufferDepth === 0) {
return;
}
$this->bufferDepth--;
if ($this->bufferDepth > 0) {
return;
}
$events = $this->bufferedEvents;
$this->bufferedEvents = [];
foreach ($events as $event) {
Event::dispatch($event);
}
}
public function discard(): void
{
if ($this->bufferDepth === 0) {
return;
}
$this->bufferDepth--;
if ($this->bufferDepth === 0) {
$this->bufferedEvents = [];
}
}
}

View file

@ -5,17 +5,22 @@ declare(strict_types=1);
use App\Attributes\Locked;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Models\Tag;
use App\Services\ActionExecutorService;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Support\Facades\DB;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
use Shared\DDD\Event;
describe('ActionExecutorService', function (): void {
it('executes action in transaction and logs success', function (): void {
@ -44,8 +49,9 @@ describe('ActionExecutorService', function (): void {
$input = new class () implements ActionInput
{
};
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$executor = new ActionExecutorService($lock, $logger);
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
@ -83,8 +89,9 @@ describe('ActionExecutorService', function (): void {
$input = new class () implements ActionInput
{
};
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$executor = new ActionExecutorService($lock, $logger);
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
@ -179,10 +186,11 @@ describe('ActionExecutorService', function (): void {
}
};
$input = new class () implements ActionInput
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($recordingLock, $logger);
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
@ -219,10 +227,11 @@ describe('ActionExecutorService', function (): void {
}
};
$input = new class () implements ActionInput
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger);
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
@ -250,10 +259,11 @@ describe('ActionExecutorService', function (): void {
->with($action::class, \Mockery::type(\Closure::class), 30, 10)
->andReturnUsing(static fn (string $key, callable $callback): mixed => $callback());
$input = new class () implements ActionInput
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger);
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
@ -314,10 +324,11 @@ describe('ActionExecutorService', function (): void {
}
};
$input = new class () implements ActionInput
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger);
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
@ -363,10 +374,11 @@ describe('ActionExecutorService', function (): void {
}
};
$input = new class () implements ActionInput
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger);
$eventDispatcher = new LaravelDomainEventDispatcher();
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
@ -379,4 +391,409 @@ describe('ActionExecutorService', function (): void {
->and($logger->entries[1]['level'])->toBe('error')
->and($logger->entries[1]['message'])->toContain('Failed');
});
it('flushes buffered events and calls onSucceeded only after transaction commit and lock release', function (): void {
// GIVEN
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$store = new ArrayStore();
$innerLock = new LaravelCacheLock(new Repository($store));
$sequence = [];
$recordingLock = new class ($innerLock, $sequence) implements Lock
{
/** @param list<string> $sequence */
public function __construct(
private readonly Lock $inner,
private array &$sequence,
) {
}
#[\Override]
public function synchronize(
string $key,
callable $callback,
int $ttlSeconds = 30,
int $waitSeconds = 10,
): mixed {
$this->sequence[] = 'lock:acquire';
$result = $this->inner->synchronize($key, $callback, $ttlSeconds, $waitSeconds);
$this->sequence[] = 'lock:release';
return $result;
}
};
$eventDispatcher = new class ($sequence) extends LaravelDomainEventDispatcher
{
/** @param list<string> $sequence */
public function __construct(
private array &$sequence,
) {
}
#[\Override]
public function beginBuffering(): void
{
$this->sequence[] = 'events:begin';
}
#[\Override]
public function dispatch(Event $event): void
{
$this->sequence[] = 'events:dispatch';
}
#[\Override]
public function flush(): void
{
$this->sequence[] = 'events:flush';
}
#[\Override]
public function discard(): void
{
$this->sequence[] = 'events:discard';
}
};
$action = new #[Locked(key: 'test:post-commit')] class ($sequence, $eventDispatcher) implements Action, HandlesSuccess
{
/** @param list<string> $sequence */
public function __construct(
private array &$sequence,
private readonly LaravelDomainEventDispatcher $eventDispatcher,
) {
}
#[\Override]
public function __invoke(ActionInput $input): string
{
$this->sequence[] = 'action:invoke';
$this->eventDispatcher->dispatch(new class () implements Event
{
});
return 'ok';
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->sequence[] = "action:onSuccess:{$result}";
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($recordingLock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
// THEN
expect($result)->toBe('ok')
->and($sequence)->toBe([
'lock:acquire',
'events:begin',
'action:invoke',
'events:dispatch',
'lock:release',
'events:flush',
'action:onSuccess:ok',
]);
});
it('discards buffered events and skips onSuccess when action throws', function (): void {
// GIVEN
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldReceive('beginBuffering')->once();
$eventDispatcher->shouldReceive('discard')->once();
$eventDispatcher->shouldNotReceive('flush');
$onSuccessCalled = false;
$action = new class ($onSuccessCalled) implements Action, HandlesSuccess
{
public function __construct(
private bool &$onSuccessCalled,
) {
}
#[\Override]
public function __invoke(ActionInput $input): never
{
throw new \RuntimeException('Boom');
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->onSuccessCalled = true;
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
// THEN
->toThrow(\RuntimeException::class, 'Boom');
expect($onSuccessCalled)->toBeFalse();
});
it('skips flush and onSuccess when lock timeout occurs and HandlesLockTimeout handles it', function (): void {
// GIVEN
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$lock = \Mockery::mock(Lock::class);
$lock->shouldReceive('synchronize')
->once()
->andThrow(new LockTimeoutException('Busy'));
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('beginBuffering');
$eventDispatcher->shouldNotReceive('flush');
$eventDispatcher->shouldNotReceive('discard');
$onSuccessCalled = false;
$action = new #[Locked(key: 'test:timeout')] class ($onSuccessCalled) implements Action, HandlesLockTimeout, HandlesSuccess
{
public function __construct(
private bool &$onSuccessCalled,
) {
}
#[\Override]
public function onLockTimeout(ActionInput $input): string
{
return 'timeout-result';
}
#[\Override]
public function __invoke(ActionInput $input): string
{
return 'never';
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->onSuccessCalled = true;
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
$result = $executor->execute($action, $input);
// THEN
expect($result)->toBe('timeout-result')
->and($onSuccessCalled)->toBeFalse();
});
it('rolls back DB writes, discards events, runs onFailure, skips onSuccess, and rethrows when action fails', function (): void {
// GIVEN
$logger = new class () extends AbstractLogger
{
/** @var array<int, array{level: mixed, message: string}> */
public array $entries = [];
#[\Override]
public function log($level, string | \Stringable $message, array $context = []): void
{
$this->entries[] = [
'level' => $level,
'message' => (string) $message,
];
}
};
$lock = new LaravelCacheLock(new Repository(new ArrayStore()));
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldReceive('beginBuffering')->once();
$eventDispatcher->shouldReceive('discard')->once();
$eventDispatcher->shouldNotReceive('flush');
$onSuccessCalled = false;
$capturedException = null;
$action = new class ($onSuccessCalled, $capturedException) implements Action, HandlesFailure, HandlesSuccess
{
public function __construct(
private bool &$onSuccessCalled,
private ?\Throwable &$capturedException,
) {
}
#[\Override]
public function __invoke(ActionInput $input): string
{
Tag::query()->create([
'label' => 'Should be rolled back',
'status' => true,
]);
throw new \DomainException('Domain failure after DB write');
}
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
$this->capturedException = $exception;
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->onSuccessCalled = true;
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
// THEN
->toThrow(\DomainException::class, 'Domain failure after DB write');
expect(Tag::query()->where('label', 'Should be rolled back')->exists())->toBeFalse()
->and($onSuccessCalled)->toBeFalse()
->and($capturedException)->toBeInstanceOf(\DomainException::class)
->and($logger->entries)->toHaveCount(2)
->and($logger->entries[1]['level'])->toBe('error');
});
it('rolls back DB writes and calls onFailure after releasing lock when Locked action implements HandlesFailure', function (): void {
// GIVEN
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$store = new ArrayStore();
$lock = new LaravelCacheLock(new Repository($store));
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldReceive('beginBuffering')->once();
$eventDispatcher->shouldReceive('discard')->once();
$eventDispatcher->shouldNotReceive('flush');
$onSuccessCalled = false;
$lockReleasedInHook = false;
$action = new #[Locked(key: 'test:locked:failure')] class ($onSuccessCalled, $lockReleasedInHook, $store) implements Action, HandlesFailure, HandlesSuccess
{
public function __construct(
private bool &$onSuccessCalled,
private bool &$lockReleasedInHook,
private readonly ArrayStore $store,
) {
}
#[\Override]
public function __invoke(ActionInput $input): string
{
Tag::query()->create([
'label' => 'Locked rollback test',
'status' => true,
]);
throw new \DomainException('Locked domain failure');
}
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
$lock = $this->store->lock('test:locked:failure', 30);
$this->lockReleasedInHook = $lock->get();
if ($this->lockReleasedInHook) {
$lock->release();
}
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->onSuccessCalled = true;
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
// THEN
->toThrow(\DomainException::class, 'Locked domain failure');
expect(Tag::query()->where('label', 'Locked rollback test')->exists())->toBeFalse()
->and($onSuccessCalled)->toBeFalse()
->and($lockReleasedInHook)->toBeTrue()
->and($store->lock('test:locked:failure', 30)->get())->toBeTrue();
});
it('calls onFailure and rethrows LockTimeoutException when Locked action does not implement HandlesLockTimeout', function (): void {
// GIVEN
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$lock = \Mockery::mock(Lock::class);
$lock->shouldReceive('synchronize')
->once()
->andThrow(new LockTimeoutException('Busy'));
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('beginBuffering');
$eventDispatcher->shouldNotReceive('flush');
$eventDispatcher->shouldNotReceive('discard');
$capturedException = null;
$action = new #[Locked(key: 'test:timeout:failure')] class ($capturedException) implements Action, HandlesFailure
{
public function __construct(
private ?\Throwable &$capturedException,
) {
}
#[\Override]
public function __invoke(ActionInput $input): string
{
return 'never';
}
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
$this->capturedException = $exception;
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
// WHEN
expect(fn () => $executor->execute($action, $input))
// THEN
->toThrow(LockTimeoutException::class, 'Busy');
expect($capturedException)->toBeInstanceOf(LockTimeoutException::class);
});
});

View file

@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
use App\Mail\RegateOrderMail;
use App\Services\MailRegateService;
use Carbon\CarbonImmutable;
use Domain\Enums\Units\OrderUnit;
use Domain\Events\Dto\OrderPlacedLine;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Models\ValueObjects\IncoId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Ports\Services\CsvGenerator;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\PendingMail;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Money\Money;
use Ramsey\Uuid\Uuid;
describe('MailRegateService', function (): void {
it('generates expected CSV rows and sends RegateOrderMail to configured regate address', function (): void {
// GIVEN
Mail::fake();
Config::set('mail.to.regate', 'regate@example.com');
$uuid = Uuid::uuid7();
$reference = new OrderReference($uuid);
$orderReferenceValue = (string) $reference;
$employeeMatricule = new Matricule('1234567');
$pickupDay = CarbonImmutable::create(2025, 1, 1);
$line1 = new OrderPlacedLine(
productName: 'Product 1',
productIncoId: new IncoId(45),
productWeightIsVariable: false,
productPriceKgTtc: null,
productOrderUnit: OrderUnit::PCE,
quantity: 2,
totalTtc: Money::EUR(1000),
);
$line2 = new OrderPlacedLine(
productName: 'Product 2',
productIncoId: new IncoId(46),
productWeightIsVariable: false,
productPriceKgTtc: null,
productOrderUnit: OrderUnit::COLIS,
quantity: 1,
totalTtc: Money::EUR(2000),
);
$line3 = new OrderPlacedLine(
productName: 'Product 3',
productIncoId: new IncoId(47),
productWeightIsVariable: true,
productPriceKgTtc: Money::EUR(1000),
productOrderUnit: OrderUnit::KGM,
quantity: 3,
totalTtc: Money::EUR(3000),
);
$csvGenerator = \Mockery::mock(CsvGenerator::class);
$csvGenerator->shouldReceive('generate')
->once()
->with(
\Mockery::type('array'),
\Mockery::on(function (array $rows) use ($orderReferenceValue): bool {
return count($rows) === 3
&& $rows[0][5] === 'UB'
&& $rows[1][5] === 'UEA'
&& $rows[2][5] === 'KGM'
&& $rows[0][0] === '45'
&& $rows[0][7] === '01/01/2025'
&& $rows[0][9] === $orderReferenceValue;
})
)
->andReturn('csv_content');
/** @var Mailer $mailer */
$mailer = Mail::getFacadeRoot();
$service = new MailRegateService($csvGenerator, $mailer);
// WHEN
$service->processOrder($reference, $employeeMatricule, $pickupDay, [$line1, $line2, $line3]);
// THEN
Mail::assertSent(RegateOrderMail::class, function (RegateOrderMail $mail) use ($orderReferenceValue): bool {
$attachments = $mail->attachments();
return $mail->hasTo('regate@example.com')
&& count($attachments) === 1
&& str_contains((string) $attachments[0]->as, sprintf('BTQ-%s-', $orderReferenceValue));
});
});
it('throws RegateExportFailedException when mailer throws', function (): void {
// GIVEN
Config::set('mail.to.regate', 'regate@example.com');
$reference = new OrderReference(Uuid::uuid7());
$employeeMatricule = new Matricule('1234567');
$pickupDay = CarbonImmutable::create(2025, 1, 1);
$csvGenerator = \Mockery::mock(CsvGenerator::class);
$csvGenerator->shouldReceive('generate')->once()->andReturn('csv_content');
$pendingMail = \Mockery::mock(PendingMail::class);
$pendingMail->shouldReceive('send')
->once()
->with(\Mockery::type(RegateOrderMail::class))
->andThrow(new \RuntimeException('SMTP connection refused'));
$mailer = \Mockery::mock(Mailer::class);
$mailer->shouldReceive('to')
->once()
->andReturn($pendingMail);
$service = new MailRegateService($csvGenerator, $mailer);
// WHEN
$action = fn () => $service->processOrder($reference, $employeeMatricule, $pickupDay, []);
// THEN
expect($action)->toThrow(RegateExportFailedException::class, 'SMTP connection refused');
});
});

View file

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
use Illuminate\Support\Facades\Event;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Shared\DDD\Event as DomainEvent;
describe('LaravelDomainEventDispatcher', function (): void {
it('dispatches immediately when not buffering', function (): void {
// GIVEN
Event::fake();
$dispatcher = new LaravelDomainEventDispatcher();
$event = new class () implements DomainEvent
{
};
// WHEN
$dispatcher->dispatch($event);
// THEN
Event::assertDispatched($event::class, 1);
});
it('buffers events and dispatches them only on outermost flush', function (): void {
// GIVEN
Event::fake();
$dispatcher = new LaravelDomainEventDispatcher();
$event = new class () implements DomainEvent
{
};
// WHEN
$dispatcher->beginBuffering();
$dispatcher->beginBuffering();
$dispatcher->dispatch($event);
Event::assertNothingDispatched();
$dispatcher->flush();
Event::assertNothingDispatched();
$dispatcher->flush();
// THEN
Event::assertDispatched($event::class, 1);
});
it('discards buffered events without dispatching them', function (): void {
// GIVEN
Event::fake();
$dispatcher = new LaravelDomainEventDispatcher();
$event = new class () implements DomainEvent
{
};
// WHEN
$dispatcher->beginBuffering();
$dispatcher->dispatch($event);
$dispatcher->discard();
$dispatcher->flush();
// THEN
Event::assertNothingDispatched();
});
});

View file

@ -3,7 +3,9 @@
declare(strict_types=1);
use App\Attributes\Locked;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Cqs\Actions\Orders\FinalizeOrder;
use App\Cqs\Actions\Orders\FinalizeOrderInput;
@ -13,6 +15,7 @@ use Domain\Builders\OrderBuilderCompleted;
use Domain\Enums\OrderStatus;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Models\Entities\Order;
@ -83,14 +86,12 @@ describe('FinalizeOrder', function (): void {
->and($result->orderReference?->value)->toBe($orderReference->value);
});
it('returns expiredTimeSlot output when ExpiredPickupTimeSlotException is thrown', function (): void {
it('returns expiredTimeSlot output when finalizeOrder throws ExpiredPickupTimeSlotException', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
@ -102,20 +103,19 @@ describe('FinalizeOrder', function (): void {
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
expect($action)->not->toBeInstanceOf(HandlesFailure::class)
->and($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('Invalid or unavailable time slot');
});
it('returns unorderableProduct output when UnorderableProductException is thrown', function (): void {
it('returns unorderableProduct output when finalizeOrder throws UnorderableProductException', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
@ -133,14 +133,12 @@ describe('FinalizeOrder', function (): void {
->and($result->errorMessage)->toBe('One or more products in your basket are no longer available for order.');
});
it('returns orderLimitExceeded output when OrderLimitExceededException is thrown', function (): void {
it('returns orderLimitExceeded output when finalizeOrder throws OrderLimitExceededException', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
@ -158,14 +156,12 @@ describe('FinalizeOrder', function (): void {
->and($result->errorMessage)->toBe('The total amount of this order has been exceeded. Please modify it to validate.');
});
it('returns weeklyLimitExceeded output when WeeklyLimitExceededException is thrown', function (): void {
it('returns weeklyLimitExceeded output when finalizeOrder throws WeeklyLimitExceededException', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
@ -183,6 +179,25 @@ describe('FinalizeOrder', function (): void {
->and($result->errorMessage)->toBe('The total amount for this delivery date has been exceeded. Please modify it to validate.');
});
it('propagates RegateExportFailedException so ActionExecutorService rolls back the transaction', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
->andThrow(new RegateExportFailedException('SMTP transport error'));
$action = new FinalizeOrder($orderTunnelService);
// WHEN
expect(fn () => $action($input))
// THEN
->toThrow(RegateExportFailedException::class, 'SMTP transport error');
});
it('has Locked attribute with expected TTL and wait seconds and implements lock contracts', function (): void {
// GIVEN
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
@ -258,4 +273,41 @@ describe('FinalizeOrder', function (): void {
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBeNull();
});
it('implements HandlesSuccess and clears tunnel state when status is SUCCESS', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$output = FinalizeOrderOutput::success(new OrderReference(Uuid::uuid7()));
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('clearTunnelState')->once();
$action = new FinalizeOrder($orderTunnelService);
// WHEN
$action->onSuccess($input, $output);
// THEN
expect($action)->toBeInstanceOf(HandlesSuccess::class);
});
it('does not clear tunnel state in onSuccess when status is not SUCCESS', function (FinalizeOrderOutput $output): void {
// GIVEN
$input = new FinalizeOrderInput();
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldNotReceive('clearTunnelState');
$action = new FinalizeOrder($orderTunnelService);
// WHEN
$action->onSuccess($input, $output);
// THEN
expect(true)->toBeTrue();
})->with([
'lock timeout' => [FinalizeOrderOutput::lockTimeout()],
'order limit exceeded' => [FinalizeOrderOutput::orderLimitExceeded('Limit exceeded')],
'weekly limit exceeded' => [FinalizeOrderOutput::weeklyLimitExceeded('Weekly limit exceeded')],
'expired time slot' => [FinalizeOrderOutput::expiredTimeSlot('Expired')],
'unorderable product' => [FinalizeOrderOutput::unorderableProduct('Unorderable')],
]);
});

View file

@ -9,7 +9,6 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Events\Dto\OrderPlacedLine;
use Domain\Events\Dto\OrderPlacedShop;
use Domain\Events\Dto\RegateOrderCsvGenerated;
use Domain\Events\Dto\SalariesHaveBeenSynced;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Entities\ProductId;
@ -178,21 +177,6 @@ describe('OrderPlacedShop', function () {
});
});
describe('RegateOrderCsvGenerated', function () {
it('creates RegateOrderCsvGenerated correctly', function () {
// GIVEN
$csvContent = 'csv';
$fileName = 'file.csv';
// WHEN
$dto = new RegateOrderCsvGenerated($csvContent, $fileName);
// THEN
expect($dto->csvContent)->toBe('csv')
->and($dto->fileName)->toBe('file.csv');
});
});
describe('SalariesHaveBeenSynced', function () {
it('creates SalariesHaveBeenSynced correctly', function () {
// GIVEN

View file

@ -13,6 +13,7 @@ use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Models\Entities\Basket;
use Domain\Models\Entities\Order;
@ -41,6 +42,7 @@ use Domain\Ports\Repositories\ShopperRepository;
use Domain\Ports\Repositories\ShopRepository;
use Domain\Ports\Services\EmployeeStatisticsService;
use Domain\Ports\Services\OrderBuilderSessionManager;
use Domain\Ports\Services\RegateService;
use Domain\Ports\Services\SessionService;
use Domain\Services\BasketService;
use Domain\Services\OrderService;
@ -109,6 +111,7 @@ function createOrderTunnelService(
?OrderBuilderSessionManager $orderBuilderSessionManager = null,
?OrderRepository $orderRepository = null,
?DomainEventDispatcher $eventDispatcher = null,
?RegateService $regateService = null,
): OrderTunnelService {
if ($basketRepository === null) {
$basketRepository = mock(BasketRepository::class);
@ -159,6 +162,11 @@ function createOrderTunnelService(
$pickupService = new PickupSchedulingService($pickupExceptionRepository);
$orderService = new OrderService($orderRepository);
if ($regateService === null) {
$regateService = \Mockery::mock(RegateService::class);
$regateService->shouldReceive('processOrder')->byDefault();
}
$orderLimitPolicy = new CustomerOrderLimitPolicy(500000, 500000);
return new OrderTunnelService(
@ -173,6 +181,7 @@ function createOrderTunnelService(
$shopperRepository,
$orderService,
$employeeStatisticsService,
$regateService,
);
}
@ -540,9 +549,9 @@ describe('OrderTunnelService', function (): void {
it('finalizes order', function (): void {
// GIVEN
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldReceive('find')->once()->andReturn(createTestBasket(1));
$basketRepo->shouldNotReceive('find');
$basketRepo->shouldReceive('persist')->once();
$basketRepo->shouldReceive('delete')->once();
$basketRepo->shouldNotReceive('delete');
$builder = createTestBuilder(completed: true);
$shopperId = $builder->getShopperId();
@ -574,7 +583,7 @@ describe('OrderTunnelService', function (): void {
$eventDispatcher->shouldReceive('dispatch')->once();
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldReceive('clear')->once();
$builderRepo->shouldNotReceive('clear');
$service = createOrderTunnelService(
basketRepository: $basketRepo,
@ -663,12 +672,12 @@ describe('OrderTunnelService', function (): void {
$eventDispatcher->shouldReceive('dispatch')->once();
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldReceive('clear')->once();
$builderRepo->shouldNotReceive('clear');
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldReceive('find')->once()->andReturn(createTestBasket(1));
$basketRepo->shouldNotReceive('find');
$basketRepo->shouldReceive('persist')->once();
$basketRepo->shouldReceive('delete')->once();
$basketRepo->shouldNotReceive('delete');
$productRepo = mock(ProductRepository::class);
$productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function ($id, $qty) {
@ -803,4 +812,83 @@ describe('OrderTunnelService', function (): void {
// THEN
expect($action)->toThrow(UnorderableProductException::class);
});
it('propagates RegateExportFailedException without dispatching AnOrderHasBeenPlaced', function (): void {
// GIVEN
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldNotReceive('find');
$basketRepo->shouldReceive('persist')->once();
$basketRepo->shouldNotReceive('delete');
$builder = createTestBuilder(completed: true);
$shopperId = $builder->getShopperId();
$shopper = new Shopper(
id: $shopperId,
email: new Email('test@test.com'),
matricule: new Matricule('1234567'),
nom: 'Doe',
prenom: 'John',
startDate: CarbonImmutable::now()->subYear(),
endDate: null,
etablissement: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101')
);
$shopperRepo = mock(ShopperRepository::class);
$shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper);
$shopId = clone $builder->getShopId();
$shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris');
$shopRepo = mock(ShopRepository::class);
$shopRepo->shouldReceive('find')->andReturn($shop);
$orderRepo = mock(OrderRepository::class);
$orderRepo->shouldReceive('persist')->once();
$eventDispatcher = mock(DomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('dispatch');
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldNotReceive('clear');
$regateService = mock(RegateService::class);
$regateService->shouldReceive('processOrder')->once()->andThrow(new RegateExportFailedException('SMTP failed'));
$service = createOrderTunnelService(
basketRepository: $basketRepo,
shopRepository: $shopRepo,
shopperRepository: $shopperRepo,
orderBuilderSessionManager: $builderRepo,
orderRepository: $orderRepo,
eventDispatcher: $eventDispatcher,
regateService: $regateService,
);
// WHEN
$action = fn () => $service->finalizeOrder($builder);
// THEN
expect($action)->toThrow(RegateExportFailedException::class, 'SMTP failed');
});
it('clears basket and order builder session when clearTunnelState is called', function (): void {
// GIVEN
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldReceive('find')->once()->andReturn(createTestBasket(1));
$basketRepo->shouldReceive('delete')->once();
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldReceive('clear')->once();
$service = createOrderTunnelService(
basketRepository: $basketRepo,
orderBuilderSessionManager: $builderRepo,
);
// WHEN
$service->clearTunnelState();
// THEN
expect(true)->toBeTrue();
});
});

View file

@ -1,90 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Domain\Services;
use Carbon\CarbonImmutable;
use Domain\Enums\Units\OrderUnit as UnitsOrderUnit;
use Domain\Events\Dto\OrderPlacedLine;
use Domain\Events\Dto\RegateOrderCsvGenerated;
use Domain\Models\ValueObjects\IncoId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Ports\Services\CsvGenerator;
use Domain\Services\RegateService;
use Mockery;
use Money\Money;
use Ramsey\Uuid\Uuid;
use Shared\DDD\DomainEventDispatcher;
describe('RegateService', function (): void {
it('processes order and generates csv', function (): void {
// GIVEN
$csvGenerator = Mockery::mock(CsvGenerator::class);
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$service = new RegateService($csvGenerator, $dispatcher);
$uuid = Uuid::uuid7();
$reference = new OrderReference($uuid);
$orderReferenceValue = (string) $reference;
$employeeMatricule = new Matricule('1234567');
$pickupDay = CarbonImmutable::create(2025, 1, 1);
$line1 = new OrderPlacedLine(
productName: 'Product 1',
productIncoId: new IncoId(45),
productWeightIsVariable: false,
productPriceKgTtc: null,
productOrderUnit: UnitsOrderUnit::PCE,
quantity: 2,
totalTtc: Money::EUR(1000)
);
$line2 = new OrderPlacedLine(
productName: 'Product 2',
productIncoId: new IncoId(46),
productWeightIsVariable: false,
productPriceKgTtc: null,
productOrderUnit: UnitsOrderUnit::COLIS,
quantity: 1,
totalTtc: Money::EUR(2000)
);
$line3 = new OrderPlacedLine(
productName: 'Product 3',
productIncoId: new IncoId(47),
productWeightIsVariable: true,
productPriceKgTtc: Money::EUR(1000),
productOrderUnit: UnitsOrderUnit::KGM,
quantity: 3,
totalTtc: Money::EUR(3000)
);
$csvGenerator->shouldReceive('generate')->once()->with(
Mockery::type('array'),
Mockery::on(function (array $rows) use ($orderReferenceValue): bool {
return count($rows) === 3
&& $rows[0][5] === 'UB'
&& $rows[1][5] === 'UEA'
&& $rows[2][5] === 'KGM'
&& $rows[0][0] === '45'
&& $rows[0][7] === '01/01/2025'
&& $rows[0][9] === $orderReferenceValue;
})
)->andReturn('csv_content');
$dispatcher->shouldReceive('dispatch')->once()->with(Mockery::on(function (object $event) use ($orderReferenceValue): bool {
return $event instanceof RegateOrderCsvGenerated
&& $event->csvContent === 'csv_content'
&& str_contains($event->fileName, sprintf('BTQ-%s-', $orderReferenceValue));
}));
// WHEN
$service->processOrder($reference, $employeeMatricule, $pickupDay, [$line1, $line2, $line3]);
// THEN
expect(true)->toBeTrue();
});
});