refactor(orders): split pending placement, non-transactional Regate SMTP export and final confirmation

This commit is contained in:
Jérémy Munsch 2026-11-16 03:32:57 +01:00
parent 3e4dfdad4e
commit 3d1c798c08
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
32 changed files with 1754 additions and 876 deletions

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace App\Attributes;
#[\Attribute(\Attribute::TARGET_CLASS)]
final readonly class WithoutTransaction
{
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\CancelPendingOrderInput,
* \App\Cqs\Actions\Orders\CancelPendingOrderOutput
* >
*/
final class CancelPendingOrder implements Action
{
public function __construct(
private readonly OrderTunnelService $orderTunnelService,
) {
}
/**
* @param \App\Cqs\Actions\Orders\CancelPendingOrderInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): CancelPendingOrderOutput
{
Assert::isInstanceOf($input, CancelPendingOrderInput::class);
try {
$this->orderTunnelService->cancelPendingOrder($input->orderId);
} catch (\DomainException) {
return CancelPendingOrderOutput::NOT_FOUND;
}
return CancelPendingOrderOutput::CANCELLED;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class CancelPendingOrderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum CancelPendingOrderOutput
{
case CANCELLED;
case NOT_FOUND;
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\ConfirmPlacedOrderInput,
* \App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput
* >
*/
final class ConfirmPlacedOrder implements Action
{
public function __construct(
private readonly OrderTunnelService $orderTunnelService,
) {
}
/**
* @param \App\Cqs\Actions\Orders\ConfirmPlacedOrderInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): ConfirmPlacedOrderOutput
{
Assert::isInstanceOf($input, ConfirmPlacedOrderInput::class);
try {
$this->orderTunnelService->confirmPlacedOrder($input->orderId);
} catch (\Throwable $e) {
report($e);
return ConfirmPlacedOrderOutput::FAILED;
}
return ConfirmPlacedOrderOutput::CONFIRMED;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ConfirmPlacedOrderInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum ConfirmPlacedOrderOutput
{
case CONFIRMED;
case FAILED;
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\ProvidesLockKey;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\ExportOrderToRegateInput,
* \App\Cqs\Actions\Orders\ExportOrderToRegateOutput
* >
* @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\ExportOrderToRegateInput>
* @implements \App\Contracts\HandlesLockTimeout<
* \App\Cqs\Actions\Orders\ExportOrderToRegateInput,
* \App\Cqs\Actions\Orders\ExportOrderToRegateOutput
* >
*/
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
#[WithoutTransaction]
final class ExportOrderToRegate implements Action, HandlesLockTimeout, ProvidesLockKey
{
public function __construct(
private readonly OrderTunnelService $orderTunnelService,
) {
}
/**
* @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input
*/
#[\Override]
public function lockKey(ActionInput $input): string
{
Assert::isInstanceOf($input, ExportOrderToRegateInput::class);
return "order:export:{$input->orderId->value}";
}
/**
* @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input
*/
#[\Override]
public function onLockTimeout(ActionInput $input): ExportOrderToRegateOutput
{
Assert::isInstanceOf($input, ExportOrderToRegateInput::class);
return ExportOrderToRegateOutput::LOCK_TIMEOUT;
}
/**
* @param \App\Cqs\Actions\Orders\ExportOrderToRegateInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): ExportOrderToRegateOutput
{
Assert::isInstanceOf($input, ExportOrderToRegateInput::class);
try {
$this->orderTunnelService->exportOrderToRegate($input->orderId);
} catch (RegateExportFailedException $e) {
report($e);
return ExportOrderToRegateOutput::FAILED;
}
return ExportOrderToRegateOutput::SENT;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\OrderId;
final readonly class ExportOrderToRegateInput implements ActionInput
{
public function __construct(
public OrderId $orderId,
) {
}
}

View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
enum ExportOrderToRegateOutput
{
case SENT;
case FAILED;
case LOCK_TIMEOUT;
}

View file

@ -21,17 +21,17 @@ use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Orders\FinalizeOrderInput,
* \App\Cqs\Actions\Orders\FinalizeOrderOutput
* \App\Cqs\Actions\Orders\PlacePendingOrderInput,
* \App\Cqs\Actions\Orders\PlacePendingOrderOutput
* >
* @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\FinalizeOrderInput>
* @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Orders\PlacePendingOrderInput>
* @implements \App\Contracts\HandlesLockTimeout<
* \App\Cqs\Actions\Orders\FinalizeOrderInput,
* \App\Cqs\Actions\Orders\FinalizeOrderOutput
* \App\Cqs\Actions\Orders\PlacePendingOrderInput,
* \App\Cqs\Actions\Orders\PlacePendingOrderOutput
* >
*/
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
final class PlacePendingOrder implements Action, HandlesLockTimeout, ProvidesLockKey
{
public function __construct(
private readonly OrderTunnelService $orderTunnelService,
@ -40,12 +40,12 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
}
/**
* @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input
* @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input
*/
#[\Override]
public function lockKey(ActionInput $input): string
{
Assert::isInstanceOf($input, FinalizeOrderInput::class);
Assert::isInstanceOf($input, PlacePendingOrderInput::class);
$shopperId = $input->shopperId ?? $this->orderTunnelService->getBuilderCompletedOrFail()->getShopperId();
@ -53,32 +53,32 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
}
/**
* @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input
* @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input
*/
#[\Override]
public function onLockTimeout(ActionInput $input): FinalizeOrderOutput
public function onLockTimeout(ActionInput $input): PlacePendingOrderOutput
{
Assert::isInstanceOf($input, FinalizeOrderInput::class);
Assert::isInstanceOf($input, PlacePendingOrderInput::class);
return FinalizeOrderOutput::lockTimeout();
return PlacePendingOrderOutput::lockTimeout();
}
/**
* @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input
* @param \App\Cqs\Actions\Orders\PlacePendingOrderInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): FinalizeOrderOutput
public function __invoke(ActionInput $input): PlacePendingOrderOutput
{
Assert::isInstanceOf($input, FinalizeOrderInput::class);
Assert::isInstanceOf($input, PlacePendingOrderInput::class);
$builder = $this->orderTunnelService->getBuilderCompletedOrFail();
try {
$order = $this->orderTunnelService->finalizeOrder($builder);
$order = $this->orderTunnelService->placePendingOrder($builder);
} catch (BasketPriceChangedException $e) {
$this->basketRepository->persist($e->refreshedBasket);
return FinalizeOrderOutput::basketPriceChanged($e->getMessage());
return PlacePendingOrderOutput::basketPriceChanged($e->getMessage());
} catch (
ExpiredPickupTimeSlotException
| InactiveShopperException
@ -87,14 +87,14 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey
| WeeklyLimitExceededException $e
) {
return match (true) {
$e instanceof ExpiredPickupTimeSlotException => FinalizeOrderOutput::expiredTimeSlot($e->getMessage()),
$e instanceof InactiveShopperException => FinalizeOrderOutput::inactiveShopper($e->getMessage()),
$e instanceof UnorderableProductException => FinalizeOrderOutput::unorderableProduct($e->getMessage()),
$e instanceof OrderLimitExceededException => FinalizeOrderOutput::orderLimitExceeded($e->getMessage()),
$e instanceof WeeklyLimitExceededException => FinalizeOrderOutput::weeklyLimitExceeded($e->getMessage()),
$e instanceof ExpiredPickupTimeSlotException => PlacePendingOrderOutput::expiredTimeSlot($e->getMessage()),
$e instanceof InactiveShopperException => PlacePendingOrderOutput::inactiveShopper($e->getMessage()),
$e instanceof UnorderableProductException => PlacePendingOrderOutput::unorderableProduct($e->getMessage()),
$e instanceof OrderLimitExceededException => PlacePendingOrderOutput::orderLimitExceeded($e->getMessage()),
$e instanceof WeeklyLimitExceededException => PlacePendingOrderOutput::weeklyLimitExceeded($e->getMessage()),
};
}
return FinalizeOrderOutput::success($order->reference);
return PlacePendingOrderOutput::pendingCreated($order->id(), $order->reference);
}
}

View file

@ -7,7 +7,7 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\Entities\ShopperId;
final readonly class FinalizeOrderInput implements ActionInput
final readonly class PlacePendingOrderInput implements ActionInput
{
public function __construct(
public ?ShopperId $shopperId = null,

View file

@ -4,22 +4,25 @@ declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Enums\FinalizeOrderStatus;
use App\Enums\PlacePendingOrderStatus;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\OrderReference;
final readonly class FinalizeOrderOutput
final readonly class PlacePendingOrderOutput
{
private function __construct(
public FinalizeOrderStatus $status,
public PlacePendingOrderStatus $status,
public ?OrderId $orderId = null,
public ?OrderReference $orderReference = null,
public ?string $errorMessage = null,
) {
}
public static function success(OrderReference $orderReference): self
public static function pendingCreated(OrderId $orderId, OrderReference $orderReference): self
{
return new self(
status: FinalizeOrderStatus::SUCCESS,
status: PlacePendingOrderStatus::PENDING_CREATED,
orderId: $orderId,
orderReference: $orderReference,
);
}
@ -27,7 +30,7 @@ final readonly class FinalizeOrderOutput
public static function expiredTimeSlot(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::EXPIRED_TIME_SLOT,
status: PlacePendingOrderStatus::EXPIRED_TIME_SLOT,
errorMessage: $errorMessage,
);
}
@ -35,7 +38,7 @@ final readonly class FinalizeOrderOutput
public static function inactiveShopper(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::INACTIVE_SHOPPER,
status: PlacePendingOrderStatus::INACTIVE_SHOPPER,
errorMessage: $errorMessage,
);
}
@ -43,7 +46,7 @@ final readonly class FinalizeOrderOutput
public static function unorderableProduct(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::UNORDERABLE_PRODUCT,
status: PlacePendingOrderStatus::UNORDERABLE_PRODUCT,
errorMessage: $errorMessage,
);
}
@ -51,7 +54,7 @@ final readonly class FinalizeOrderOutput
public static function basketPriceChanged(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::BASKET_PRICE_CHANGED,
status: PlacePendingOrderStatus::BASKET_PRICE_CHANGED,
errorMessage: $errorMessage,
);
}
@ -59,7 +62,7 @@ final readonly class FinalizeOrderOutput
public static function orderLimitExceeded(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED,
status: PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
@ -67,7 +70,7 @@ final readonly class FinalizeOrderOutput
public static function weeklyLimitExceeded(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED,
status: PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
@ -75,7 +78,7 @@ final readonly class FinalizeOrderOutput
public static function lockTimeout(): self
{
return new self(
status: FinalizeOrderStatus::LOCK_TIMEOUT,
status: PlacePendingOrderStatus::LOCK_TIMEOUT,
);
}
}

View file

@ -4,9 +4,9 @@ declare(strict_types=1);
namespace App\Enums;
enum FinalizeOrderStatus
enum PlacePendingOrderStatus
{
case SUCCESS;
case PENDING_CREATED;
case EXPIRED_TIME_SLOT;
case INACTIVE_SHOPPER;
case BASKET_PRICE_CHANGED;

View file

@ -6,9 +6,17 @@ namespace App\Http\Controllers\Fo;
use App\Contracts\Executor;
use App\Cqs\Actions\Orders\ApplyPickTimeSlot;
use App\Cqs\Actions\Orders\FinalizeOrder;
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
use App\Cqs\Actions\Orders\CancelPendingOrder;
use App\Cqs\Actions\Orders\CancelPendingOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrder;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput;
use App\Cqs\Actions\Orders\ExportOrderToRegate;
use App\Cqs\Actions\Orders\ExportOrderToRegateInput;
use App\Cqs\Actions\Orders\ExportOrderToRegateOutput;
use App\Cqs\Actions\Orders\InitializeOrderTunnel;
use App\Cqs\Actions\Orders\PlacePendingOrder;
use App\Cqs\Actions\Orders\PlacePendingOrderOutput;
use App\Cqs\Queries\Orders\GetBasketSummaryQuery;
use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput;
use App\Cqs\Queries\Orders\GetOrderConfirmationQuery;
@ -18,7 +26,7 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput;
use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQuery;
use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQueryInput;
use App\Enums\ApplyPickTimeSlotStatus;
use App\Enums\FinalizeOrderStatus;
use App\Enums\PlacePendingOrderStatus;
use App\Exceptions\CustomerNotEmployedException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Fo\Orders\ConfirmOrderRequest;
@ -130,33 +138,78 @@ class TunnelController extends Controller
public function confirmationSubmit(
ConfirmOrderRequest $request,
FinalizeOrder $action
PlacePendingOrder $placePendingOrder,
ExportOrderToRegate $exportOrderToRegate,
ConfirmPlacedOrder $confirmPlacedOrder,
CancelPendingOrder $cancelPendingOrder,
): RedirectResponse {
$this->authorize('canFinalizeOrder', OrderTunnelStep::class);
/** @var FinalizeOrderOutput $output */
$output = $this->executor->execute(
$action,
$request->toFinalizeOrderInput()
/** @var PlacePendingOrderOutput $placeOutput */
$placeOutput = $this->executor->execute(
$placePendingOrder,
$request->toPlacePendingOrderInput()
);
return match ($output->status) {
FinalizeOrderStatus::SUCCESS => to_route(
if ($placeOutput->status !== PlacePendingOrderStatus::PENDING_CREATED) {
return $this->redirectOnPendingFailure($placeOutput);
}
$orderId = $placeOutput->orderId
?? throw new \LogicException('Order ID is missing on pending created output.');
$orderReference = $placeOutput->orderReference
?? throw new \LogicException('Order reference is missing on pending created output.');
/** @var ExportOrderToRegateOutput $exportOutput */
$exportOutput = $this->executor->execute(
$exportOrderToRegate,
new ExportOrderToRegateInput($orderId)
);
if ($exportOutput !== ExportOrderToRegateOutput::SENT) {
$this->executor->execute($cancelPendingOrder, new CancelPendingOrderInput($orderId));
return to_route('fo.sales.confirmation')->with(
'message',
__('An error occurred while validating your order. Please try again later.')
);
}
/** @var ConfirmPlacedOrderOutput $confirmOutput */
$confirmOutput = $this->executor->execute(
$confirmPlacedOrder,
new ConfirmPlacedOrderInput($orderId)
);
return match ($confirmOutput) {
ConfirmPlacedOrderOutput::CONFIRMED => to_route(
'fo.sales.confirmation.show-confirmed',
(string) ($output->orderReference
?? throw new \LogicException('Order reference is missing on success output.'))
(string) $orderReference
),
FinalizeOrderStatus::EXPIRED_TIME_SLOT => to_route('fo.sales.pick-time-slot')->withErrors([
ConfirmPlacedOrderOutput::FAILED => to_route('fo.sales.confirmation')->with(
'message',
__('An error occurred while validating your order. Please try again later.')
),
};
}
private function redirectOnPendingFailure(PlacePendingOrderOutput $output): RedirectResponse
{
return match ($output->status) {
PlacePendingOrderStatus::PENDING_CREATED => throw new \LogicException(
'Unexpected PENDING_CREATED status in failure handler.'
),
PlacePendingOrderStatus::EXPIRED_TIME_SLOT => to_route('fo.sales.pick-time-slot')->withErrors([
'timeslot' => trans($output->errorMessage ?? ''),
]),
FinalizeOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(),
FinalizeOrderStatus::BASKET_PRICE_CHANGED,
FinalizeOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([
PlacePendingOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(),
PlacePendingOrderStatus::BASKET_PRICE_CHANGED,
PlacePendingOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([
'basket' => trans($output->errorMessage ?? ''),
]),
FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED,
FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED => back()->with('message', $output->errorMessage),
FinalizeOrderStatus::LOCK_TIMEOUT => back()->with(
PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED,
PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED => back()->with('message', $output->errorMessage),
PlacePendingOrderStatus::LOCK_TIMEOUT => back()->with(
'message',
__('Your order is already being processed. Please wait a moment and try again.')
),

View file

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace App\Http\Requests\Fo\Orders;
use App\Cqs\Actions\Orders\FinalizeOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use Illuminate\Foundation\Http\FormRequest;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
@ -20,11 +20,11 @@ class ConfirmOrderRequest extends FormRequest
return $this->authService->check();
}
public function toFinalizeOrderInput(): FinalizeOrderInput
public function toPlacePendingOrderInput(): PlacePendingOrderInput
{
$customer = $this->authService->getCustomerAsMandatory();
return new FinalizeOrderInput(
return new PlacePendingOrderInput(
shopperId: $customer->getId(),
);
}

View file

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Services;
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\Executor;
@ -102,6 +103,18 @@ final class ActionExecutorService implements Executor
return ($attributes[0] ?? null)?->newInstance();
}
/**
* @template TAction of Action
*
* @param TAction $executable
*/
private function hasWithoutTransactionAttribute(Action $executable): bool
{
$reflection = new \ReflectionClass($executable);
return $reflection->getAttributes(WithoutTransaction::class) !== [];
}
/**
* @template TAction of Action
* @template TActionInput of ActionInput
@ -205,14 +218,18 @@ final class ActionExecutorService implements Executor
{
$this->eventDispatcher->beginBuffering();
$run = function () use ($executable, $input, $actionName): mixed {
$result = $executable($input);
$this->logger->info("[Action] Succeeded {$actionName}");
return $result;
};
try {
return DB::transaction(function () use ($executable, $input, $actionName): mixed {
$result = $executable($input);
$this->logger->info("[Action] Succeeded {$actionName}");
return $result;
});
return $this->hasWithoutTransactionAttribute($executable)
? $run()
: DB::transaction($run);
} catch (\Throwable $e) {
$this->eventDispatcher->discard();

View file

@ -71,6 +71,34 @@ final class Order implements Entity
$this->status = OrderStatus::CANCELED;
}
public function validate(): void
{
if ($this->status === OrderStatus::CANCELED) {
throw new \DomainException('Cannot validate a canceled order.');
}
$this->status = OrderStatus::VALIDATED;
}
public static function pendingFromBasket(
OrderId $id,
OrderReference $reference,
Basket $basket,
PickupTimeSlot $pickupTimeSlot,
Shopper $shopper,
Shop $shop
): self {
return self::buildFromBasket(
id: $id,
reference: $reference,
basket: $basket,
pickupTimeSlot: $pickupTimeSlot,
shopper: $shopper,
shop: $shop,
status: OrderStatus::WAITING,
);
}
public static function fromBasket(
OrderId $id,
OrderReference $reference,
@ -78,6 +106,26 @@ final class Order implements Entity
PickupTimeSlot $pickupTimeSlot,
Shopper $shopper,
Shop $shop
): self {
return self::buildFromBasket(
id: $id,
reference: $reference,
basket: $basket,
pickupTimeSlot: $pickupTimeSlot,
shopper: $shopper,
shop: $shop,
status: OrderStatus::VALIDATED,
);
}
private static function buildFromBasket(
OrderId $id,
OrderReference $reference,
Basket $basket,
PickupTimeSlot $pickupTimeSlot,
Shopper $shopper,
Shop $shop,
OrderStatus $status
): self {
$lines = array_map(
fn (BasketProduct $item) => OrderLine::fromBasketProduct($item),
@ -91,7 +139,7 @@ final class Order implements Entity
employee: OrderEmployee::fromShopper($shopper),
deliveryAddress: DeliveryAddress::fromShop($shop),
pickupTimeSlot: clone $pickupTimeSlot,
status: OrderStatus::VALIDATED,
status: $status,
total: clone $basket->totalTaxIncluded(),
lines: $lines
);

View file

@ -21,6 +21,22 @@ class OrderService
) {
}
public function createPendingOrderFromBasket(
Basket $basket,
PickupTimeSlot $pickupTimeSlot,
Shopper $shopper,
Shop $shop
): Order {
return Order::pendingFromBasket(
id: $this->newOrderId(),
reference: $this->newReference(),
basket: $basket,
pickupTimeSlot: $pickupTimeSlot,
shopper: $shopper,
shop: $shop
);
}
public function createOrderFromBasket(
Basket $basket,
PickupTimeSlot $pickupTimeSlot,
@ -47,6 +63,21 @@ class OrderService
return new OrderReference(Uuid::uuid7());
}
public function validateOrder(OrderId $id): Order
{
$order = $this->orderRepository->find($id);
if (! $order) {
throw new \DomainException('Order not found');
}
$order->validate();
$this->orderRepository->persist($order);
return $order;
}
public function cancelOrder(OrderId $id): void
{
$order = $this->orderRepository->find($id);

View file

@ -22,6 +22,7 @@ use Domain\Models\Entities\Order;
use Domain\Models\Entities\Shop;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Entities\ShopperId;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Policies\CustomerOrderLimitPolicy;
@ -157,6 +158,69 @@ class OrderTunnelService
return $matchedSlot;
}
/**
* Step 1 of order confirmation: validates basket, limits, shopper and slot,
* then persists the order in WAITING state without dispatching external notifications.
*
* @throws WeeklyLimitExceededException
* @throws OrderLimitExceededException
* @throws ExpiredPickupTimeSlotException
* @throws BasketPriceChangedException
* @throws UnorderableProductException
* @throws InactiveShopperException
*/
public function placePendingOrder(OrderBuilderCompleted $builder): Order
{
$order = $this->validateAndCreateOrder($builder, pending: true);
$this->orderRepository->persist($order);
return $order;
}
/**
* Step 2a (outside DB transaction): exports the pending order to Regate via SMTP.
*
* @throws RegateExportFailedException
*/
public function exportOrderToRegate(OrderId $orderId): void
{
$order = $this->orderRepository->find($orderId);
if (! $order) {
throw new \DomainException("Order with id '{$orderId->value}' not found.");
}
$placedEvent = $order->toPlacedEvent();
$this->regateService->processOrder(
$order->reference,
$order->employee->matricule,
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
$placedEvent->lines,
);
}
/**
* Step 2b (on Regate success): validates the order and dispatches AnOrderHasBeenPlaced.
*/
public function confirmPlacedOrder(OrderId $orderId): Order
{
$order = $this->orderService->validateOrder($orderId);
$this->eventDispatcher->dispatch($order->toPlacedEvent());
return $order;
}
/**
* Step 2c (on Regate failure): cancels the WAITING order without emptying the basket.
*/
public function cancelPendingOrder(OrderId $orderId): void
{
$this->orderService->cancelOrder($orderId);
}
/**
* @throws WeeklyLimitExceededException
* @throws OrderLimitExceededException
@ -167,6 +231,26 @@ class OrderTunnelService
* @throws RegateExportFailedException
*/
public function finalizeOrder(OrderBuilderCompleted $builder): Order
{
$order = $this->validateAndCreateOrder($builder, pending: false);
$this->orderRepository->persist($order);
$placedEvent = $order->toPlacedEvent();
$this->regateService->processOrder(
$order->reference,
$order->employee->matricule,
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
$placedEvent->lines,
);
$this->eventDispatcher->dispatch($placedEvent);
return $order;
}
private function validateAndCreateOrder(OrderBuilderCompleted $builder, bool $pending): Order
{
$shopperId = $builder->getShopperId();
$basket = $this->revalidateBasket($builder->getBasket());
@ -192,27 +276,9 @@ class OrderTunnelService
$this->assertPickupTimeSlotIsAvailable($shop, $pickupTimeSlot);
$order = $this->orderService->createOrderFromBasket(
$basket,
$pickupTimeSlot,
$shopper,
$shop
);
$this->orderRepository->persist($order);
$placedEvent = $order->toPlacedEvent();
$this->regateService->processOrder(
$order->reference,
$order->employee->matricule,
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
$placedEvent->lines,
);
$this->eventDispatcher->dispatch($placedEvent);
return $order;
return $pending
? $this->orderService->createPendingOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop)
: $this->orderService->createOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop);
}
/** @throws \Domain\Exceptions\OrderTunnel\OrderLimitExceededException */

View file

@ -30,7 +30,7 @@ class EloquentEmployeeStatisticsService implements EmployeeStatisticsService
{
$weekTotal = Order::query()
->where('employee_matricule', $matricule->value)
->where('status', OrderStatus::VALIDATED)
->whereIn('status', [OrderStatus::VALIDATED, OrderStatus::WAITING])
->whereBetween('pickup_day', [$start, $end])
->sum('total');

View file

@ -4,7 +4,18 @@ declare(strict_types=1);
use App\Contracts\Executor;
use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput;
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
use App\Cqs\Actions\Orders\CancelPendingOrder;
use App\Cqs\Actions\Orders\CancelPendingOrderInput;
use App\Cqs\Actions\Orders\CancelPendingOrderOutput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrder;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput;
use App\Cqs\Actions\Orders\ExportOrderToRegate;
use App\Cqs\Actions\Orders\ExportOrderToRegateInput;
use App\Cqs\Actions\Orders\ExportOrderToRegateOutput;
use App\Cqs\Actions\Orders\PlacePendingOrder;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderOutput;
use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput;
use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput;
use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput;
@ -26,6 +37,7 @@ use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
@ -500,11 +512,21 @@ describe('TunnelController', function (): void {
]);
Gate::before(fn () => true);
$orderId = new OrderId(Uuid::uuid7());
$orderReference = new OrderReference(Uuid::uuid7());
$this->mock(Executor::class, function ($mock) use ($orderReference): void {
$this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::success($orderReference));
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::SENT);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class))
->andReturn(ConfirmPlacedOrderOutput::CONFIRMED);
});
// WHEN
@ -516,6 +538,104 @@ describe('TunnelController', function (): void {
$response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', (string) $orderReference);
});
it('cancels pending order and redirects back cleanly when Regate export fails on confirmation submit', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$customer = new Customer();
$customer->email = new Email('regate-export-fail@example.com');
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$orderId = new OrderId(Uuid::uuid7());
$orderReference = new OrderReference(Uuid::uuid7());
$this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::FAILED);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(CancelPendingOrder::class), \Mockery::type(CancelPendingOrderInput::class))
->andReturn(CancelPendingOrderOutput::CANCELLED);
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
});
it('redirects to confirmation with error when ConfirmPlacedOrder fails after Regate export', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$customer = new Customer();
$customer->email = new Email('confirm-sql-fail@example.com');
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$orderId = new OrderId(Uuid::uuid7());
$orderReference = new OrderReference(Uuid::uuid7());
$this->mock(Executor::class, function ($mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::SENT);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class))
->andReturn(ConfirmPlacedOrderOutput::FAILED);
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
});
it('redirects back with message when limit exception occurs on confirmation submit', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
@ -541,7 +661,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::weeklyLimitExceeded(
->andReturn(PlacePendingOrderOutput::weeklyLimitExceeded(
'The total amount for this delivery date has been exceeded. Please modify it to validate.'
));
});
@ -581,7 +701,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::expiredTimeSlot('Invalid or unavailable time slot'));
->andReturn(PlacePendingOrderOutput::expiredTimeSlot('Invalid or unavailable time slot'));
});
// WHEN
@ -621,7 +741,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::unorderableProduct(
->andReturn(PlacePendingOrderOutput::unorderableProduct(
'One or more products in your basket are no longer available for order.'
));
});
@ -663,7 +783,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::basketPriceChanged(
->andReturn(PlacePendingOrderOutput::basketPriceChanged(
'The price of one or more products in your basket has changed.'
));
});
@ -705,7 +825,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::lockTimeout());
->andReturn(PlacePendingOrderOutput::lockTimeout());
});
// WHEN
@ -743,7 +863,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::inactiveShopper('Employee account is no longer active.'));
->andReturn(PlacePendingOrderOutput::inactiveShopper('Employee account is no longer active.'));
});
// WHEN

View file

@ -2,7 +2,7 @@
declare(strict_types=1);
use App\Cqs\Actions\Orders\FinalizeOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use App\Http\Requests\Fo\Orders\ConfirmOrderRequest;
use App\Models\Customer;
use Domain\Models\ValueObjects\Entities\ShopperId;
@ -51,7 +51,7 @@ describe('ConfirmOrderRequest', function () {
->and($rules['ok_cgv'])->toContain('accepted');
});
it('maps to FinalizeOrderInput', function () {
it('maps to PlacePendingOrderInput', function () {
// GIVEN
$shopperId = new ShopperId(Uuid::uuid7());
$customer = \Mockery::mock(Customer::class);
@ -64,10 +64,10 @@ describe('ConfirmOrderRequest', function () {
$request->initialize();
// WHEN
$input = $request->toFinalizeOrderInput();
$input = $request->toPlacePendingOrderInput();
// THEN
expect($input)->toBeInstanceOf(FinalizeOrderInput::class)
expect($input)->toBeInstanceOf(PlacePendingOrderInput::class)
->and($input->shopperId)->toBe($shopperId);
});
});

View file

@ -1,435 +0,0 @@
<?php
declare(strict_types=1);
use App\Cqs\Actions\Orders\FinalizeOrder;
use App\Cqs\Actions\Orders\FinalizeOrderInput;
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
use App\Enums\FinalizeOrderStatus;
use App\Mail\OrderConfirmAdminMail;
use App\Mail\RegateOrderMail;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductInco;
use App\Models\Range;
use App\Models\Shop;
use App\Notifications\OrderConfirmed;
use App\Services\ActionExecutorService;
use App\Services\MailRegateService;
use Carbon\CarbonImmutable;
use Domain\Builders\OrderBuilder;
use Domain\Enums\OrderStatus;
use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Models\Entities\Basket;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\IncoId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Policies\CustomerOrderLimitPolicy;
use Domain\Ports\Services\RegateService;
use Domain\Services\OrderService;
use Domain\Services\OrderTunnelService;
use Domain\Services\PickupSchedulingService;
use Domain\Services\ShopperService;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Session;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Infrastructure\Adapters\Repositories\EloquentOrderRepository;
use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository;
use Infrastructure\Adapters\Repositories\EloquentProductRepository;
use Infrastructure\Adapters\Repositories\EloquentShopperRepository;
use Infrastructure\Adapters\Repositories\EloquentShopRepository;
use Infrastructure\Adapters\Repositories\SessionBasketRepository;
use Infrastructure\Adapters\Serializers\BasketSerializer;
use Infrastructure\Adapters\Services\CsvGeneratorImpl;
use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService;
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
use Money\Currency;
use Money\Money;
use Psr\Log\NullLogger;
use Ramsey\Uuid\Uuid;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
use Shared\ValueObjects\CrmHashcode;
uses(RefreshDatabase::class);
describe('FinalizeOrder action', function (): void {
beforeEach(function (): void {
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
CarbonImmutable::setTestNow($now);
Date::setTestNow($now);
Config::set('mail.to.regate', 'regate@test.local');
Config::set('mail.to.contact', 'contact@test.local');
Mail::fake();
Notification::fake();
});
afterEach(function (): void {
CarbonImmutable::setTestNow();
Date::setTestNow();
});
/**
* @return array{
* customer: Customer,
* employee: Employee,
* shop: Shop,
* product: Product,
* builderManager: SessionOrderBuilderManager,
* dispatcher: LaravelDomainEventDispatcher,
* tunnelService: OrderTunnelService,
* executor: ActionExecutorService,
* }
*/
function buildFinalizeOrderScenario(
int $priceCents = 2500,
int $qty = 2,
bool $activeEmployee = true,
?RegateService $regateService = null,
?Lock $lock = null,
?CarbonImmutable $pickupAt = null,
): array {
$shop = Shop::factory()->create(['default' => true]);
$customer = new Customer();
$customer->email = new Email('buyer.order@example.com');
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->saveOrFail();
$employee = new Employee();
$employee->customer_id = $customer->id;
$employee->matricule = new Matricule('1000404');
$employee->code = new Code('ABCDEF');
$employee->nom = 'Petit';
$employee->prenom = 'Luc';
$employee->start_date = CarbonImmutable::parse('2025-01-01');
$employee->end_date = $activeEmployee ? null : CarbonImmutable::parse('2026-01-01');
$employee->etablissement = new ShopperEstablishmentCode('01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('01');
$employee->saveOrFail();
$range = new Range();
$range->name = 'Gamme Commande ' . uniqid();
$range->status = true;
$range->order = ((int) Range::query()->max('order')) + 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product([
'range_id' => $range->id,
'name' => 'Rôti Fermier',
'brand' => ProductBrand::loue,
'invoicing_unit' => InvoicingUnit::PCE,
'sell_unit' => SellUnit::PCE,
'order_unit' => OrderUnit::PCE,
'tax_rate' => TaxRate::TVA_5_5,
'description' => 'Desc',
'weight' => 1000,
'status' => true,
]);
$product->price = Money::EUR($priceCents);
$product->short_description = 'Court';
$product->picture_alt = 'alt';
$product->picture_title = 'title';
$product->picture_large_alt = 'alt large';
$product->picture_large_title = 'title large';
$product->saveOrFail();
$inco = new ProductInco();
$inco->product_id = $product->id;
$inco->no_art = 778899;
$inco->saveOrFail();
$basket = new Basket(new BasketId(Uuid::uuid7()), [
$product->id => new BasketProduct(
id: $product->getId(),
name: $product->name,
qty: $qty,
unitPriceHt: $product->price,
unitDiscount: Money::EUR(0),
taxRate: $product->tax_rate,
weightGrams: 1000,
brand: $product->brand,
incoId: new IncoId($inco->no_art),
orderUnit: OrderUnit::PCE,
slug: $product->slug,
picture: null,
description: $product->description,
weightVariable: false,
discountRate: DiscountRate::zero(),
priceKgTtc: Money::EUR(1000),
options: [],
),
]);
$slot = new PickupTimeSlot(
$pickupAt ?? CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'),
new \DateInterval('PT2H'),
);
$builder = OrderBuilder::fromBasket($basket, $customer->getId())
->withPickupTimeSlot($shop->getId(), $slot);
$session = Session::driver();
$basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer());
$basketRepo->persist($basket);
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
$builderManager->save($builder);
$dispatcher = new LaravelDomainEventDispatcher();
$shopRepo = new EloquentShopRepository();
$shopperRepo = new EloquentShopperRepository();
$orderRepo = new EloquentOrderRepository();
$tunnelService = new OrderTunnelService(
$dispatcher,
new ShopperService($shopRepo, $shopperRepo),
$builderManager,
new PickupSchedulingService(new EloquentPickupExceptionRepository()),
$orderRepo,
new EloquentProductRepository(),
new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')),
$shopRepo,
$shopperRepo,
new OrderService($orderRepo),
new EloquentEmployeeStatisticsService(),
$regateService ?? new MailRegateService(new CsvGeneratorImpl(), Mail::getFacadeRoot()),
);
$executor = new ActionExecutorService(
$lock ?? new LaravelCacheLock(new Repository(new ArrayStore())),
new NullLogger(),
$dispatcher,
);
return [
'customer' => $customer,
'employee' => $employee,
'shop' => $shop,
'product' => $product,
'basketId' => $basket->id,
'basketRepository' => $basketRepo,
'builderManager' => $builderManager,
'dispatcher' => $dispatcher,
'tunnelService' => $tunnelService,
'executor' => $executor,
];
}
it('persists order and lines, sends Regate mail synchronously, dispatches notifications, and returns SUCCESS', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$ctx = buildFinalizeOrderScenario(priceCents: 2000, qty: 2);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($output->status)->toBe(FinalizeOrderStatus::SUCCESS)
->and($output->orderReference)->not->toBeNull();
$persistedOrder = Order::query()->with('lines')->first();
expect($persistedOrder)->not->toBeNull()
->and($persistedOrder?->status)->toBe(OrderStatus::VALIDATED)
->and($persistedOrder?->shop_id)->toBe($ctx['shop']->id)
->and($persistedOrder?->lines)->toHaveCount(1);
Mail::assertSent(RegateOrderMail::class, 1);
Mail::assertQueued(OrderConfirmAdminMail::class, 1);
Notification::assertSentTo($ctx['employee'], OrderConfirmed::class);
});
it('rolls back database order and rethrows when Regate export fails', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
/** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */
$failingRegate = \Mockery::mock(RegateService::class);
$failingRegate->shouldReceive('processOrder')
->once()
->andThrow(new RegateExportFailedException('SMTP transport failure'));
$ctx = buildFinalizeOrderScenario(regateService: $failingRegate);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN & THEN
expect(fn () => $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())))
->toThrow(RegateExportFailedException::class);
$this->assertDatabaseCount('orders', 0);
$this->assertDatabaseCount('order_lines', 0);
Notification::assertNothingSent();
});
it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
// 210 EUR HT -> > 200 EUR TTC order limit
$ctx = buildFinalizeOrderScenario(priceCents: 21000, qty: 1);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED)
->and($output->orderReference)->toBeNull();
$this->assertDatabaseCount('orders', 0);
Mail::assertNothingSent();
});
it('returns WEEKLY_LIMIT_EXCEEDED when cumulative weekly orders exceed 200 EUR', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$ctx = buildFinalizeOrderScenario(priceCents: 6000, qty: 1);
Order::query()->forceCreate([
'id' => Uuid::uuid7()->toString(),
'shop_id' => $ctx['shop']->id,
'reference' => new OrderReference(Uuid::uuid7()),
'status' => OrderStatus::VALIDATED->value,
'total' => Money::EUR(16000),
'employee' => new OrderEmployee(
$ctx['employee']->matricule,
$ctx['employee']->prenom,
$ctx['employee']->nom,
$ctx['employee']->etablissement,
$ctx['employee']->site,
$ctx['employee']->service,
),
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'),
'pickup_day' => '2026-11-20 14:00:00',
]);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED);
$this->assertDatabaseCount('orders', 1);
Mail::assertNothingSent();
});
it('returns INACTIVE_SHOPPER when linked employee end_date is in the past', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$ctx = buildFinalizeOrderScenario(activeEmployee: false);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::INACTIVE_SHOPPER);
$this->assertDatabaseCount('orders', 0);
Mail::assertNothingSent();
});
it('returns UNORDERABLE_PRODUCT when a basket product was disabled before finalization', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$ctx = buildFinalizeOrderScenario();
$ctx['product']->status = false;
$ctx['product']->saveOrFail();
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::UNORDERABLE_PRODUCT);
$this->assertDatabaseCount('orders', 0);
Mail::assertNothingSent();
});
it('returns EXPIRED_TIME_SLOT when selected pickup date is no longer open', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
// Past Friday (2026-11-13) relative to test now (2026-11-16)
$ctx = buildFinalizeOrderScenario(
pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'),
);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT);
$this->assertDatabaseCount('orders', 0);
Mail::assertNothingSent();
});
it('returns LOCK_TIMEOUT when lock acquisition times out inside ActionExecutorService', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
/** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */
$lock = \Mockery::mock(Lock::class);
$lock->shouldReceive('synchronize')
->once()
->andThrow(new LockTimeoutException('Lock timed out'));
$ctx = buildFinalizeOrderScenario(lock: $lock);
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::LOCK_TIMEOUT)
->and($output->orderReference)->toBeNull();
$this->assertDatabaseCount('orders', 0);
});
it('updates session basket and returns BASKET_PRICE_CHANGED when catalog price increases before finalization', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$ctx = buildFinalizeOrderScenario(priceCents: 1000, qty: 2);
$ctx['product']->price = Money::EUR(1500);
$ctx['product']->saveOrFail();
$action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED)
->and($output->orderReference)->toBeNull()
->and($ctx['basketRepository']->find($ctx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165');
$this->assertDatabaseCount('orders', 0);
Mail::assertNothingSent();
});
});

View file

@ -0,0 +1,466 @@
<?php
declare(strict_types=1);
use App\Cqs\Actions\Orders\CancelPendingOrder;
use App\Cqs\Actions\Orders\CancelPendingOrderInput;
use App\Cqs\Actions\Orders\CancelPendingOrderOutput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrder;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput;
use App\Cqs\Actions\Orders\ExportOrderToRegate;
use App\Cqs\Actions\Orders\ExportOrderToRegateInput;
use App\Cqs\Actions\Orders\ExportOrderToRegateOutput;
use App\Cqs\Actions\Orders\PlacePendingOrder;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use App\Enums\PlacePendingOrderStatus;
use App\Mail\OrderConfirmAdminMail;
use App\Mail\RegateOrderMail;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductInco;
use App\Models\Range;
use App\Models\Shop;
use App\Notifications\OrderConfirmed;
use App\Services\ActionExecutorService;
use App\Services\MailRegateService;
use Carbon\CarbonImmutable;
use Domain\Builders\OrderBuilder;
use Domain\Enums\OrderStatus;
use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Policies\CustomerOrderLimitPolicy;
use Domain\Ports\Repositories\BasketRepository;
use Domain\Ports\Services\RegateService;
use Domain\Services\BasketService;
use Domain\Services\OrderService;
use Domain\Services\OrderTunnelService;
use Domain\Services\PickupSchedulingService;
use Domain\Services\ShopperService;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Session;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Locks\LaravelCacheLock;
use Infrastructure\Adapters\Repositories\EloquentOrderRepository;
use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository;
use Infrastructure\Adapters\Repositories\EloquentProductRepository;
use Infrastructure\Adapters\Repositories\EloquentShopperRepository;
use Infrastructure\Adapters\Repositories\EloquentShopRepository;
use Infrastructure\Adapters\Services\CsvGeneratorImpl;
use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService;
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
use Money\Currency;
use Money\Money;
use Psr\Log\NullLogger;
use Ramsey\Uuid\Uuid;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
use Shared\ValueObjects\CrmHashcode;
uses(RefreshDatabase::class);
describe('Order placement two-step CQS actions', function (): void {
beforeEach(function (): void {
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
CarbonImmutable::setTestNow($now);
Date::setTestNow($now);
Config::set('mail.to.regate', 'regate@test.local');
Config::set('mail.to.contact', 'contact@test.local');
Mail::fake();
Notification::fake();
});
afterEach(function (): void {
CarbonImmutable::setTestNow();
Date::setTestNow();
});
/**
* @return array{
* customer: Customer,
* employee: Employee,
* shop: Shop,
* product: Product,
* basketId: BasketId,
* basketRepository: BasketRepository,
* builderManager: SessionOrderBuilderManager,
* dispatcher: LaravelDomainEventDispatcher,
* tunnelService: OrderTunnelService,
* executor: ActionExecutorService,
* }
*/
function buildOrderPlacementScenario(
int $priceCents = 2000,
int $qty = 2,
bool $activeEmployee = true,
?CarbonImmutable $pickupAt = null,
?RegateService $regateService = null,
?Lock $lock = null,
): array {
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => Uuid::uuid7()->toString(),
'email' => new Email('buyer-' . uniqid() . '@example.com'),
'hashcode' => new CrmHashcode(Uuid::uuid4()),
]);
/** @var int $sequence */
static $sequence = 0;
$sequence++;
$chars = Code::ALLOWED_CHARACTERS;
$uniqueCode = 'ABCDE' . $chars[$sequence % strlen($chars)] . $chars[(intdiv($sequence, strlen($chars))) % strlen($chars)];
$employee = new Employee();
$employee->matricule = new Matricule((string) random_int(1000000, 9999999));
$employee->code = new Code($uniqueCode);
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = $activeEmployee ? null : Date::now()->subDay();
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme Test ' . uniqid();
$range->status = true;
$range->order = random_int(1, 99999);
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet Test ' . uniqid();
$product->brand = ProductBrand::loue;
$product->description = 'Description complète de test';
$product->short_description = 'Court';
$product->price = Money::EUR($priceCents);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$product->picture_alt = 'alt';
$product->picture_title = 'title';
$product->picture_large_alt = 'alt large';
$product->picture_large_title = 'title large';
$product->saveOrFail();
$inco = new ProductInco();
$inco->product_id = $product->id;
$inco->no_art = 778800 + $sequence;
$inco->saveOrFail();
/** @var BasketService $basketService */
$basketService = resolve(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), $qty);
$basket = $basketService->getBasket();
/** @var BasketRepository $basketRepo */
$basketRepo = resolve(BasketRepository::class);
$slot = new PickupTimeSlot(
$pickupAt ?? CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'),
new \DateInterval('PT2H'),
);
$builder = OrderBuilder::fromBasket($basket, $customer->getId())
->withPickupTimeSlot($shop->getId(), $slot);
/** @var \Illuminate\Contracts\Session\Session $session */
$session = Session::driver();
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
$builderManager->save($builder);
$dispatcher = new LaravelDomainEventDispatcher();
$shopRepo = new EloquentShopRepository();
$shopperRepo = new EloquentShopperRepository();
$orderRepo = new EloquentOrderRepository();
/** @var \Illuminate\Contracts\Mail\Mailer $mailer */
$mailer = Mail::getFacadeRoot();
$tunnelService = new OrderTunnelService(
$dispatcher,
new ShopperService($shopRepo, $shopperRepo),
$builderManager,
new PickupSchedulingService(new EloquentPickupExceptionRepository()),
$orderRepo,
new EloquentProductRepository(),
new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')),
$shopRepo,
$shopperRepo,
new OrderService($orderRepo),
new EloquentEmployeeStatisticsService(),
$regateService ?? new MailRegateService(new CsvGeneratorImpl(), $mailer),
);
$executor = new ActionExecutorService(
$lock ?? new LaravelCacheLock(new Repository(new ArrayStore())),
new NullLogger(),
$dispatcher,
);
return [
'customer' => $customer,
'employee' => $employee,
'shop' => $shop,
'product' => $product,
'basketId' => $basket->id,
'basketRepository' => $basketRepo,
'builderManager' => $builderManager,
'dispatcher' => $dispatcher,
'tunnelService' => $tunnelService,
'executor' => $executor,
];
}
it('creates WAITING order, exports to Regate outside SQL transaction, and validates order with notifications', function (): void {
// GIVEN
$baseTxLevel = DB::transactionLevel();
$spyRegate = new class () implements RegateService
{
public ?int $recordedTxLevel = null;
#[\Override]
public function processOrder(
OrderReference $reference,
Matricule $employeeMatricule,
CarbonImmutable $pickupDay,
array $lines,
): void {
$this->recordedTxLevel = DB::transactionLevel();
}
};
$ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2, regateService: $spyRegate);
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
$confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']);
// WHEN: Step 1 - create pending WAITING order
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
// THEN: Order is WAITING and no notifications or emails were sent yet
expect($placeOutput->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED)
->and($placeOutput->orderId)->toBeInstanceOf(OrderId::class);
$pendingOrder = Order::query()->find($placeOutput->orderId?->value->toString());
expect($pendingOrder?->status)->toBe(OrderStatus::WAITING);
Notification::assertNothingSent();
// WHEN: Step 2 - export to Regate outside any extra SQL transaction
/** @var OrderId $orderId */
$orderId = $placeOutput->orderId;
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT)
->and($spyRegate->recordedTxLevel)->toBe($baseTxLevel);
// WHEN: Step 3 - confirm placed order (VALIDATED + AnOrderHasBeenPlaced)
$confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId));
// THEN
expect($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED);
$confirmedOrder = Order::query()->with('lines')->find($orderId->value->toString());
expect($confirmedOrder?->status)->toBe(OrderStatus::VALIDATED)
->and($confirmedOrder?->lines)->toHaveCount(1);
Mail::assertQueued(OrderConfirmAdminMail::class, 1);
Notification::assertSentTo($ctx['employee'], OrderConfirmed::class);
expect($ctx['basketRepository']->find($ctx['basketId']))->toBeNull();
});
it('cancels WAITING order cleanly and keeps basket intact when Regate export fails', function (): void {
// GIVEN
/** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */
$failingRegate = \Mockery::mock(RegateService::class);
$failingRegate->shouldReceive('processOrder')
->once()
->andThrow(new RegateExportFailedException('SMTP transport failure'));
$ctx = buildOrderPlacementScenario(regateService: $failingRegate);
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
$cancelAction = new CancelPendingOrder($ctx['tunnelService']);
// WHEN
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
/** @var OrderId $orderId */
$orderId = $placeOutput->orderId;
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
$cancelOutput = $ctx['executor']->execute($cancelAction, new CancelPendingOrderInput($orderId));
// THEN
expect($exportOutput)->toBe(ExportOrderToRegateOutput::FAILED)
->and($cancelOutput)->toBe(CancelPendingOrderOutput::CANCELLED);
$persistedOrder = Order::query()->find($orderId->value->toString());
expect($persistedOrder?->status)->toBe(OrderStatus::CANCELED)
->and($ctx['basketRepository']->find($ctx['basketId']))->not->toBeNull();
Mail::assertNothingQueued();
Notification::assertNothingSent();
});
it('sends Regate order email through real MailRegateService when export succeeds', function (): void {
// GIVEN
$ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2);
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
$confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']);
// WHEN
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
/** @var OrderId $orderId */
$orderId = $placeOutput->orderId;
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
$confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId));
// THEN
expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT)
->and($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED);
Mail::assertSent(RegateOrderMail::class, 1);
});
it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void {
// GIVEN
$ctx = buildOrderPlacementScenario(priceCents: 21000, qty: 1);
$action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED)
->and($output->orderReference)->toBeNull()
->and(Order::query()->count())->toBe(0);
Mail::assertNothingSent();
});
it('counts existing WAITING orders toward weekly limit to prevent concurrent overspending', function (): void {
// GIVEN
$ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1);
Order::query()->forceCreate([
'id' => Uuid::uuid7()->toString(),
'shop_id' => $ctx['shop']->id,
'reference' => new OrderReference(Uuid::uuid7()),
'status' => OrderStatus::WAITING->value,
'total' => Money::EUR(16000),
'employee' => new OrderEmployee(
$ctx['employee']->matricule,
$ctx['employee']->prenom,
$ctx['employee']->nom,
$ctx['employee']->etablissement,
$ctx['employee']->site,
$ctx['employee']->service,
),
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'),
'pickup_day' => '2026-11-20',
]);
$action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
// WHEN
$output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId()));
// THEN
expect($output->status)->toBe(PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED)
->and(Order::query()->count())->toBe(1);
Mail::assertNothingSent();
});
it('returns INACTIVE_SHOPPER, UNORDERABLE_PRODUCT, EXPIRED_TIME_SLOT, BASKET_PRICE_CHANGED and LOCK_TIMEOUT appropriately', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN: inactive employee
$inactiveCtx = buildOrderPlacementScenario(activeEmployee: false);
$inactiveOut = $inactiveCtx['executor']->execute(
new PlacePendingOrder($inactiveCtx['tunnelService'], $inactiveCtx['basketRepository']),
new PlacePendingOrderInput($inactiveCtx['customer']->getId()),
);
expect($inactiveOut->status)->toBe(PlacePendingOrderStatus::INACTIVE_SHOPPER);
// GIVEN: disabled product
$unorderableCtx = buildOrderPlacementScenario();
$unorderableCtx['product']->status = false;
$unorderableCtx['product']->saveOrFail();
$unorderableOut = $unorderableCtx['executor']->execute(
new PlacePendingOrder($unorderableCtx['tunnelService'], $unorderableCtx['basketRepository']),
new PlacePendingOrderInput($unorderableCtx['customer']->getId()),
);
expect($unorderableOut->status)->toBe(PlacePendingOrderStatus::UNORDERABLE_PRODUCT);
// GIVEN: expired pickup slot
$expiredCtx = buildOrderPlacementScenario(
pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'),
);
$expiredOut = $expiredCtx['executor']->execute(
new PlacePendingOrder($expiredCtx['tunnelService'], $expiredCtx['basketRepository']),
new PlacePendingOrderInput($expiredCtx['customer']->getId()),
);
expect($expiredOut->status)->toBe(PlacePendingOrderStatus::EXPIRED_TIME_SLOT);
// GIVEN: price increase before finalization
$priceCtx = buildOrderPlacementScenario(priceCents: 1000, qty: 2);
$priceCtx['product']->price = Money::EUR(1500);
$priceCtx['product']->saveOrFail();
$priceOut = $priceCtx['executor']->execute(
new PlacePendingOrder($priceCtx['tunnelService'], $priceCtx['basketRepository']),
new PlacePendingOrderInput($priceCtx['customer']->getId()),
);
expect($priceOut->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED)
->and($priceCtx['basketRepository']->find($priceCtx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165');
// GIVEN: lock timeout
/** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */
$lock = \Mockery::mock(Lock::class);
$lock->shouldReceive('synchronize')->once()->andThrow(new LockTimeoutException('Lock timed out'));
$lockCtx = buildOrderPlacementScenario(lock: $lock);
$lockOut = $lockCtx['executor']->execute(
new PlacePendingOrder($lockCtx['tunnelService'], $lockCtx['basketRepository']),
new PlacePendingOrderInput($lockCtx['customer']->getId()),
);
expect($lockOut->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT);
});
});

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
@ -796,4 +797,61 @@ describe('ActionExecutorService', function (): void {
expect($capturedException)->toBeInstanceOf(LockTimeoutException::class);
});
it('runs WithoutTransaction action outside DB transaction and flushes events dispatched inside onSuccess', function (): void {
// GIVEN
$lock = \Mockery::mock(Lock::class);
$lock->shouldNotReceive('synchronize');
$logger = \Mockery::mock(LoggerInterface::class);
$logger->shouldIgnoreMissing();
$postHookEvent = new class () implements Event
{
};
$eventDispatcher = \Mockery::mock(LaravelDomainEventDispatcher::class);
$eventDispatcher->shouldReceive('beginBuffering')->once()->ordered();
$eventDispatcher->shouldReceive('flush')->once()->ordered();
$eventDispatcher->shouldReceive('dispatch')->once()->with($postHookEvent)->ordered();
$txLevelInsideAction = null;
$action = new #[WithoutTransaction] class ($txLevelInsideAction, $postHookEvent, $eventDispatcher) implements Action, HandlesSuccess
{
public function __construct(
private ?int &$txLevelInsideAction,
private readonly Event $event,
private readonly LaravelDomainEventDispatcher $dispatcher,
) {
}
#[\Override]
public function __invoke(ActionInput $input): string
{
$this->txLevelInsideAction = DB::transactionLevel();
return 'exported';
}
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
$this->dispatcher->dispatch($this->event);
}
};
$input = new class () implements ActionInput
{
};
$executor = new ActionExecutorService($lock, $logger, $eventDispatcher);
$baseTx = DB::transactionLevel();
// WHEN
$result = $executor->execute($action, $input);
// THEN
expect($result)->toBe('exported')
->and($txLevelInsideAction)->toBe($baseTx);
});
});

View file

@ -63,3 +63,55 @@ it('retrieves the weekly order total for a given employee', function () {
expect($result->getAmount())->toBe('1500')
->and($result->getCurrency()->getCode())->toBe('EUR');
});
it('includes WAITING orders and excludes CANCELED orders in weekly total', function (): void {
// GIVEN
DB::table('shops')->insertOrIgnore(['id' => 1, 'name' => 'Shop 1', 'postcode' => '75000', 'city' => 'Paris', 'address' => 'Addr']);
$baseRow = [
'shop_id' => 1,
'employee' => json_encode([
'matricule' => '1234567',
'firstname' => 'Jean',
'lastname' => 'Dupont',
'facility' => 'Main Facility',
'site' => 'HQ',
'service' => 'IT',
]),
'delivery_address' => '{}',
'pickup_day' => '2023-01-05',
];
DB::table('orders')->insert([
array_merge($baseRow, [
'id' => Uuid::uuid7()->toString(),
'reference' => Uuid::uuid7()->toString(),
'status' => OrderStatus::VALIDATED->value,
'total' => 1000,
]),
array_merge($baseRow, [
'id' => Uuid::uuid7()->toString(),
'reference' => Uuid::uuid7()->toString(),
'status' => OrderStatus::WAITING->value,
'total' => 2500,
]),
array_merge($baseRow, [
'id' => Uuid::uuid7()->toString(),
'reference' => Uuid::uuid7()->toString(),
'status' => OrderStatus::CANCELED->value,
'total' => 9000,
]),
]);
$service = new EloquentEmployeeStatisticsService();
// WHEN
$result = $service->getWeeklyTotalForEmployee(
new Matricule('1234567'),
CarbonImmutable::parse('2023-01-01'),
CarbonImmutable::parse('2023-01-07')
);
// THEN
expect($result->getAmount())->toBe('3500');
});

View file

@ -1,334 +0,0 @@
<?php
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;
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
use App\Enums\FinalizeOrderStatus;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Enums\OrderStatus;
use Domain\Exceptions\OrderTunnel\BasketPriceChangedException;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\InactiveShopperException;
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;
use Domain\Models\Entities\Order;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Entities\ShopId;
use Domain\Models\ValueObjects\Entities\ShopperId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Ports\Repositories\BasketRepository;
use Domain\Services\OrderTunnelService;
use Money\Money;
use Ramsey\Uuid\Uuid;
describe('FinalizeOrder', function (): void {
it('finalizes order and returns reference via OrderTunnelService', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$orderReference = new OrderReference(Uuid::uuid7());
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$order = new Order(
id: new OrderId(Uuid::uuid7()),
shopId: new ShopId(Uuid::uuid7()),
reference: $orderReference,
employee: new OrderEmployee(
matricule: new Matricule('1234567'),
firstname: 'Jean',
lastname: 'Dupont',
facility: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101'),
),
deliveryAddress: new DeliveryAddress(
name: 'Shop',
address: '1 rue Test',
postcode: '75001',
city: 'Paris',
),
pickupTimeSlot: new PickupTimeSlot(now(), new \DateInterval('PT1H')),
status: OrderStatus::WAITING,
total: Money::EUR(1000),
lines: [],
);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
->andReturn($order);
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::SUCCESS)
->and($result->orderReference)->not->toBeNull()
->and($result->orderReference?->value)->toBe($orderReference->value);
});
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('finalizeOrder')
->once()
->with($builder)
->andThrow(new ExpiredPickupTimeSlotException('Invalid or unavailable time slot'));
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($action)->not->toBeInstanceOf(HandlesFailure::class)
->and($action)->not->toBeInstanceOf(HandlesSuccess::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 inactiveShopper output when finalizeOrder throws InactiveShopperException', 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 InactiveShopperException('Employee account is no longer active.'));
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::INACTIVE_SHOPPER)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('Employee account is no longer active.');
});
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('finalizeOrder')
->once()
->with($builder)
->andThrow(new UnorderableProductException('One or more products in your basket are no longer available for order.'));
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::UNORDERABLE_PRODUCT)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('One or more products in your basket are no longer available for order.');
});
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('finalizeOrder')
->once()
->with($builder)
->andThrow(new OrderLimitExceededException());
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('The total amount of this order has been exceeded. Please modify it to validate.');
});
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('finalizeOrder')
->once()
->with($builder)
->andThrow(new WeeklyLimitExceededException());
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED)
->and($result->orderReference)->toBeNull()
->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, \Mockery::mock(BasketRepository::class));
// 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);
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
$reflection = new \ReflectionClass(FinalizeOrder::class);
$attributes = $reflection->getAttributes(Locked::class);
// WHEN
$locked = ($attributes[0] ?? null)?->newInstance();
// THEN
expect($locked)->toBeInstanceOf(Locked::class)
->and($locked->ttlSeconds)->toBe(30)
->and($locked->waitSeconds)->toBe(10)
->and($locked->key)->toBeNull()
->and($action)->toBeInstanceOf(ProvidesLockKey::class)
->and($action)->toBeInstanceOf(HandlesLockTimeout::class);
});
it('builds lockKey from input shopperId when provided', function (): void {
// GIVEN
$shopperId = new ShopperId(Uuid::uuid7());
$input = new FinalizeOrderInput(shopperId: $shopperId);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldNotReceive('getBuilderCompletedOrFail');
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$key = $action->lockKey($input);
// THEN
expect($key)->toBe("order:finalize:shopper:{$shopperId->value}");
});
it('builds lockKey from completed builder when input shopperId is null', function (): void {
// GIVEN
$shopperId = new ShopperId(Uuid::uuid7());
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$builder->shouldReceive('getShopperId')
->once()
->andReturn($shopperId);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$key = $action->lockKey($input);
// THEN
expect($key)->toBe("order:finalize:shopper:{$shopperId->value}");
});
it('returns lockTimeout output on lock timeout', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class));
// WHEN
$result = $action->onLockTimeout($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::LOCK_TIMEOUT)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBeNull();
});
it('persists refreshed basket and returns basketPriceChanged output when finalizeOrder throws BasketPriceChangedException', function (): void {
// GIVEN
$input = new FinalizeOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []);
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('finalizeOrder')
->once()
->with($builder)
->andThrow(new BasketPriceChangedException($refreshedBasket));
$basketRepository = \Mockery::mock(BasketRepository::class);
$basketRepository->shouldReceive('persist')
->once()
->with($refreshedBasket);
$action = new FinalizeOrder($orderTunnelService, $basketRepository);
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.');
});
});

View file

@ -2,14 +2,14 @@
declare(strict_types=1);
use App\Cqs\Actions\Orders\FinalizeOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use Domain\Models\ValueObjects\Entities\ShopperId;
use Ramsey\Uuid\Uuid;
describe('FinalizeOrderInput', function (): void {
describe('PlacePendingOrderInput', function (): void {
it('can be instantiated with null shopperId', function (): void {
// GIVEN & WHEN
$input = new FinalizeOrderInput();
$input = new PlacePendingOrderInput();
// THEN
expect($input->shopperId)->toBeNull();
@ -20,7 +20,7 @@ describe('FinalizeOrderInput', function (): void {
$shopperId = new ShopperId(Uuid::uuid7());
// WHEN
$input = new FinalizeOrderInput(shopperId: $shopperId);
$input = new PlacePendingOrderInput(shopperId: $shopperId);
// THEN
expect($input->shopperId)->toBe($shopperId);

View file

@ -0,0 +1,307 @@
<?php
declare(strict_types=1);
use App\Attributes\Locked;
use App\Attributes\WithoutTransaction;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Cqs\Actions\Orders\CancelPendingOrder;
use App\Cqs\Actions\Orders\CancelPendingOrderInput;
use App\Cqs\Actions\Orders\CancelPendingOrderOutput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrder;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput;
use App\Cqs\Actions\Orders\ExportOrderToRegate;
use App\Cqs\Actions\Orders\ExportOrderToRegateInput;
use App\Cqs\Actions\Orders\ExportOrderToRegateOutput;
use App\Cqs\Actions\Orders\PlacePendingOrder;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderOutput;
use App\Enums\PlacePendingOrderStatus;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Enums\OrderStatus;
use Domain\Exceptions\OrderTunnel\BasketPriceChangedException;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\InactiveShopperException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Models\Entities\Basket;
use Domain\Models\Entities\Order;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Entities\ShopId;
use Domain\Models\ValueObjects\Entities\ShopperId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Ports\Repositories\BasketRepository;
use Domain\Services\OrderTunnelService;
use Money\Money;
use Ramsey\Uuid\Uuid;
describe('PlacePendingOrder', function (): void {
it('places a pending order and returns id and reference via OrderTunnelService', function (): void {
// GIVEN
$input = new PlacePendingOrderInput();
$orderId = new OrderId(Uuid::uuid7());
$orderReference = new OrderReference(Uuid::uuid7());
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$order = new Order(
id: $orderId,
shopId: new ShopId(Uuid::uuid7()),
reference: $orderReference,
employee: new OrderEmployee(
matricule: new Matricule('1234567'),
firstname: 'Jean',
lastname: 'Dupont',
facility: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101'),
),
deliveryAddress: new DeliveryAddress(
name: 'Shop',
address: '1 rue Test',
postcode: '75001',
city: 'Paris',
),
pickupTimeSlot: new PickupTimeSlot(new \DateTimeImmutable('+2 days'), new \DateInterval('PT1H')),
status: OrderStatus::WAITING,
total: Money::EUR(1000),
lines: [],
);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')
->once()
->andReturn($builder);
$orderTunnelService->shouldReceive('placePendingOrder')
->once()
->with($builder)
->andReturn($order);
/** @var \Mockery\MockInterface&BasketRepository $basketRepository */
$basketRepository = \Mockery::mock(BasketRepository::class);
$action = new PlacePendingOrder($orderTunnelService, $basketRepository);
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class)
->and($result->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED)
->and($result->orderId)->toBe($orderId)
->and($result->orderReference?->value)->toBe($orderReference->value);
});
it('maps domain exceptions cleanly into PlacePendingOrderOutput', function (
\Throwable $exception,
PlacePendingOrderStatus $expectedStatus,
string $expectedMessage,
): void {
// GIVEN
$input = new PlacePendingOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('placePendingOrder')
->once()
->with($builder)
->andThrow($exception);
/** @var \Mockery\MockInterface&BasketRepository $basketRepository */
$basketRepository = \Mockery::mock(BasketRepository::class);
$action = new PlacePendingOrder($orderTunnelService, $basketRepository);
// WHEN
$result = $action($input);
// THEN
expect($action)->not->toBeInstanceOf(HandlesFailure::class)
->and($action)->not->toBeInstanceOf(HandlesSuccess::class)
->and($result)->toBeInstanceOf(PlacePendingOrderOutput::class)
->and($result->status)->toBe($expectedStatus)
->and($result->orderId)->toBeNull()
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe($expectedMessage);
})->with([
'expired slot' => [
new ExpiredPickupTimeSlotException('Invalid or unavailable time slot'),
PlacePendingOrderStatus::EXPIRED_TIME_SLOT,
'Invalid or unavailable time slot',
],
'inactive shopper' => [
new InactiveShopperException('Employee account is no longer active.'),
PlacePendingOrderStatus::INACTIVE_SHOPPER,
'Employee account is no longer active.',
],
'unorderable product' => [
new UnorderableProductException('One or more products in your basket are no longer available for order.'),
PlacePendingOrderStatus::UNORDERABLE_PRODUCT,
'One or more products in your basket are no longer available for order.',
],
'order limit' => [
new OrderLimitExceededException(),
PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED,
'The total amount of this order has been exceeded. Please modify it to validate.',
],
'weekly limit' => [
new WeeklyLimitExceededException(),
PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED,
'The total amount for this delivery date has been exceeded. Please modify it to validate.',
],
]);
it('persists refreshed basket and returns basketPriceChanged output when placePendingOrder throws BasketPriceChangedException', function (): void {
// GIVEN
$input = new PlacePendingOrderInput();
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder);
$orderTunnelService->shouldReceive('placePendingOrder')
->once()
->with($builder)
->andThrow(new BasketPriceChangedException($refreshedBasket));
/** @var \Mockery\MockInterface&BasketRepository $basketRepository */
$basketRepository = \Mockery::mock(BasketRepository::class);
$basketRepository->shouldReceive('persist')
->once()
->with($refreshedBasket);
$action = new PlacePendingOrder($orderTunnelService, $basketRepository);
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(PlacePendingOrderOutput::class)
->and($result->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.');
});
it('has Locked attribute and lock key contracts', function (): void {
// GIVEN
$shopperId = new ShopperId(Uuid::uuid7());
$input = new PlacePendingOrderInput(shopperId: $shopperId);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
/** @var \Mockery\MockInterface&BasketRepository $basketRepository */
$basketRepository = \Mockery::mock(BasketRepository::class);
$action = new PlacePendingOrder($orderTunnelService, $basketRepository);
$reflection = new \ReflectionClass(PlacePendingOrder::class);
$attributes = $reflection->getAttributes(Locked::class);
$locked = ($attributes[0] ?? null)?->newInstance();
// WHEN
$key = $action->lockKey($input);
$timeout = $action->onLockTimeout($input);
// THEN
expect($locked)->toBeInstanceOf(Locked::class)
->and($locked?->ttlSeconds)->toBe(30)
->and($locked?->waitSeconds)->toBe(10)
->and($action)->toBeInstanceOf(ProvidesLockKey::class)
->and($action)->toBeInstanceOf(HandlesLockTimeout::class)
->and($key)->toBe("order:finalize:shopper:{$shopperId->value}")
->and($timeout->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT);
});
});
describe('ExportOrderToRegate, ConfirmPlacedOrder and CancelPendingOrder', function (): void {
it('marks ExportOrderToRegate with WithoutTransaction and Locked attributes', function (): void {
// GIVEN
$reflection = new \ReflectionClass(ExportOrderToRegate::class);
// WHEN
$withoutTx = $reflection->getAttributes(WithoutTransaction::class);
$locked = $reflection->getAttributes(Locked::class);
// THEN
expect($withoutTx)->toHaveCount(1)
->and($locked)->toHaveCount(1);
});
it('exports order via OrderTunnelService and handles lock timeout', function (): void {
// GIVEN
$orderId = new OrderId(Uuid::uuid7());
$input = new ExportOrderToRegateInput($orderId);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('exportOrderToRegate')->once()->with($orderId);
$action = new ExportOrderToRegate($orderTunnelService);
// WHEN
$result = $action($input);
// THEN
expect($result)->toBe(ExportOrderToRegateOutput::SENT)
->and($action->lockKey($input))->toBe("order:export:{$orderId->value}")
->and($action->onLockTimeout($input))->toBe(ExportOrderToRegateOutput::LOCK_TIMEOUT);
});
it('confirms a placed order and cancels a pending order', function (): void {
// GIVEN
$orderId = new OrderId(Uuid::uuid7());
$order = new Order(
id: $orderId,
shopId: new ShopId(Uuid::uuid7()),
reference: new OrderReference(Uuid::uuid7()),
employee: new OrderEmployee(
matricule: new Matricule('1234567'),
firstname: 'Jean',
lastname: 'Dupont',
facility: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101'),
),
deliveryAddress: new DeliveryAddress(
name: 'Shop',
address: '1 rue Test',
postcode: '75001',
city: 'Paris',
),
pickupTimeSlot: new PickupTimeSlot(new \DateTimeImmutable('+2 days'), new \DateInterval('PT1H')),
status: OrderStatus::VALIDATED,
total: Money::EUR(1000),
lines: [],
);
/** @var \Mockery\MockInterface&OrderTunnelService $orderTunnelService */
$orderTunnelService = \Mockery::mock(OrderTunnelService::class);
$orderTunnelService->shouldReceive('confirmPlacedOrder')
->once()
->with($orderId)
->andReturn($order);
$orderTunnelService->shouldReceive('cancelPendingOrder')
->once()
->with($orderId);
$confirmAction = new ConfirmPlacedOrder($orderTunnelService);
$cancelAction = new CancelPendingOrder($orderTunnelService);
// WHEN
$confirmResult = $confirmAction(new ConfirmPlacedOrderInput($orderId));
$cancelResult = $cancelAction(new CancelPendingOrderInput($orderId));
// THEN
expect($confirmResult)->toBe(ConfirmPlacedOrderOutput::CONFIRMED)
->and($cancelResult)->toBe(CancelPendingOrderOutput::CANCELLED);
});
});

View file

@ -280,6 +280,69 @@ describe('Order - fromBasket factory', function (): void {
->and($order->getLines()[0]->product->name)->toBe('Poulet Rôti')
->and($order->getLines()[0]->quantity)->toBe(2);
});
it('creates an order in WAITING status via pendingFromBasket and validates it to VALIDATED', function (): void {
// GIVEN
$basket = new Basket(new BasketId(Uuid::uuid7()), [
new BasketProduct(
id: new ProductId(Uuid::uuid7()),
name: 'Poulet Rôti',
qty: 1,
unitPriceHt: Money::EUR(1000),
unitDiscount: Money::EUR(0),
taxRate: TaxRate::TVA_5_5,
weightGrams: 1000,
brand: ProductBrand::loue,
incoId: new IncoId(123456),
orderUnit: OrderUnit::PCE,
slug: 'poulet-roti',
picture: null,
description: null,
weightVariable: false,
discountRate: DiscountRate::zero(),
priceKgTtc: Money::EUR(1000),
),
]);
$shopper = new Shopper(
id: new ShopperId(Uuid::uuid7()),
email: new Email('jean.dupont@example.com'),
matricule: new Matricule('1234567'),
nom: 'Dupont',
prenom: 'Jean',
startDate: CarbonImmutable::now(),
endDate: null,
etablissement: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101')
);
$shop = new Shop(
id: new ShopId(Uuid::uuid7()),
name: 'Cocotte Lyon',
address: '12 rue de la Paix',
postcode: '69001',
city: 'Lyon',
phone: '0478123456'
);
// WHEN
$order = Order::pendingFromBasket(
new OrderId(Uuid::uuid7()),
new OrderReference(Uuid::uuid7()),
$basket,
new PickupTimeSlot(new \DateTimeImmutable('+1 day 10:00'), new \DateInterval('PT10M')),
$shopper,
$shop
);
// THEN
expect($order->status)->toBe(OrderStatus::WAITING);
$order->validate();
expect($order->status)->toBe(OrderStatus::VALIDATED);
$order->cancel();
expect(fn () => $order->validate())->toThrow(\DomainException::class, 'Cannot validate a canceled order.');
});
});
describe('Order - Domain Events', function (): void {

View file

@ -10,8 +10,10 @@ use DateInterval;
use Domain\Builders\OrderBuilder;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Builders\OrderBuilderWithBasket;
use Domain\Enums\OrderStatus;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Events\AnOrderHasBeenPlaced;
use Domain\Exceptions\OrderTunnel\BasketPriceChangedException;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\InactiveShopperException;
@ -26,11 +28,13 @@ use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\DiscountRate;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Entities\ProductId;
use Domain\Models\ValueObjects\Entities\ShopId;
use Domain\Models\ValueObjects\Entities\ShopperId;
use Domain\Models\ValueObjects\IncoId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
@ -910,4 +914,110 @@ describe('OrderTunnelService', function (): void {
// THEN
expect($action)->toThrow(InactiveShopperException::class);
});
it('places a WAITING order without calling Regate or dispatching AnOrderHasBeenPlaced', function (): void {
// GIVEN
$builder = createTestBuilder(completed: true);
$shopperId = $builder->getShopperId();
$shopper = new Shopper(
id: $shopperId,
email: new Email('pending@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 = \Mockery::mock(ShopperRepository::class);
$shopperRepo->shouldReceive('getByIdOrFail')->andReturn($shopper);
$shop = new Shop(clone $builder->getShopId(), 'Shop', 'Address', '75000', 'Paris');
$shopRepo = \Mockery::mock(ShopRepository::class);
$shopRepo->shouldReceive('find')->andReturn($shop);
$orderRepo = \Mockery::mock(OrderRepository::class);
$orderRepo->shouldReceive('persist')->once();
$eventDispatcher = \Mockery::mock(DomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('dispatch');
$regateService = \Mockery::mock(RegateService::class);
$regateService->shouldNotReceive('processOrder');
$service = createOrderTunnelService(
shopRepository: $shopRepo,
shopperRepository: $shopperRepo,
orderRepository: $orderRepo,
eventDispatcher: $eventDispatcher,
regateService: $regateService,
);
// WHEN
$order = $service->placePendingOrder($builder);
// THEN
expect($order)->toBeInstanceOf(Order::class)
->and($order->status)->toBe(OrderStatus::WAITING);
});
it('exports, confirms and cancels a pending order across split steps', function (): void {
// GIVEN
$shopId = new ShopId(Uuid::uuid7());
$shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris');
$shopper = new Shopper(
id: new ShopperId(Uuid::uuid7()),
email: new Email('split@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')
);
$basket = createTestBasket(1);
$order = Order::pendingFromBasket(
new OrderId(Uuid::uuid7()),
new OrderReference(Uuid::uuid7()),
$basket,
new PickupTimeSlot(CarbonImmutable::now()->next('Friday'), new DateInterval('PT1H')),
$shopper,
$shop
);
$orderRepo = \Mockery::mock(OrderRepository::class);
$orderRepo->shouldReceive('find')->with($order->id())->andReturn($order);
$orderRepo->shouldReceive('persist')->twice();
$eventDispatcher = \Mockery::mock(DomainEventDispatcher::class);
$eventDispatcher->shouldReceive('dispatch')
->once()
->with(\Mockery::type(AnOrderHasBeenPlaced::class));
$regateService = \Mockery::mock(RegateService::class);
$regateService->shouldReceive('processOrder')->once();
$service = createOrderTunnelService(
orderRepository: $orderRepo,
eventDispatcher: $eventDispatcher,
regateService: $regateService,
);
// WHEN
$service->exportOrderToRegate($order->id());
$confirmed = $service->confirmPlacedOrder($order->id());
// THEN
expect($confirmed->status)->toBe(OrderStatus::VALIDATED);
// WHEN cancelPendingOrder is invoked
$service->cancelPendingOrder($order->id());
// THEN
expect($order->status)->toBe(OrderStatus::CANCELED);
});
});