ldc-cocotte/tests/Unit/App/Actions/Orders/PlacePendingOrderTest.php

307 lines
13 KiB
PHP

<?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);
});
});