fix(orders): revalidate timeslot cutoff, product orderability and use contractual FinalizeOrderOutput

This commit is contained in:
Jérémy Munsch 2026-11-14 18:40:25 +01:00
parent 9c537d83b2
commit 4c3fa373da
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
15 changed files with 654 additions and 29 deletions

View file

@ -6,12 +6,15 @@ namespace App\Cqs\Actions\Orders;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Services\OrderTunnelService;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\FinalizeOrderInput, \Domain\Models\ValueObjects\OrderReference>
* @implements \App\Contracts\Action<\App\Cqs\Actions\Orders\FinalizeOrderInput, \App\Cqs\Actions\Orders\FinalizeOrderOutput>
*/
final class FinalizeOrder implements Action
{
@ -24,13 +27,23 @@ final class FinalizeOrder implements Action
* @param \App\Cqs\Actions\Orders\FinalizeOrderInput $input
*/
#[\Override]
public function __invoke(ActionInput $input): OrderReference
public function __invoke(ActionInput $input): FinalizeOrderOutput
{
Assert::isInstanceOf($input, FinalizeOrderInput::class);
$builder = $this->orderTunnelService->getBuilderCompletedOrFail();
$order = $this->orderTunnelService->finalizeOrder($builder);
return $order->reference;
try {
$order = $this->orderTunnelService->finalizeOrder($builder);
return FinalizeOrderOutput::success($order->reference);
} catch (ExpiredPickupTimeSlotException | UnorderableProductException | OrderLimitExceededException | WeeklyLimitExceededException $e) {
return match (true) {
$e instanceof ExpiredPickupTimeSlotException => FinalizeOrderOutput::expiredTimeSlot($e->getMessage()),
$e instanceof UnorderableProductException => FinalizeOrderOutput::unorderableProduct($e->getMessage()),
$e instanceof OrderLimitExceededException => FinalizeOrderOutput::orderLimitExceeded($e->getMessage()),
$e instanceof WeeklyLimitExceededException => FinalizeOrderOutput::weeklyLimitExceeded($e->getMessage()),
};
}
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Orders;
use App\Enums\FinalizeOrderStatus;
use Domain\Models\ValueObjects\OrderReference;
final readonly class FinalizeOrderOutput
{
private function __construct(
public FinalizeOrderStatus $status,
public ?OrderReference $orderReference = null,
public ?string $errorMessage = null,
) {
}
public static function success(OrderReference $orderReference): self
{
return new self(
status: FinalizeOrderStatus::SUCCESS,
orderReference: $orderReference,
);
}
public static function expiredTimeSlot(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::EXPIRED_TIME_SLOT,
errorMessage: $errorMessage,
);
}
public static function unorderableProduct(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::UNORDERABLE_PRODUCT,
errorMessage: $errorMessage,
);
}
public static function orderLimitExceeded(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
public static function weeklyLimitExceeded(string $errorMessage): self
{
return new self(
status: FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED,
errorMessage: $errorMessage,
);
}
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum FinalizeOrderStatus
{
case SUCCESS;
case EXPIRED_TIME_SLOT;
case UNORDERABLE_PRODUCT;
case ORDER_LIMIT_EXCEEDED;
case WEEKLY_LIMIT_EXCEEDED;
}

View file

@ -7,6 +7,7 @@ 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\InitializeOrderTunnel;
use App\Cqs\Queries\Orders\GetBasketSummaryQuery;
use App\Cqs\Queries\Orders\GetBasketSummaryQueryInput;
@ -16,14 +17,13 @@ use App\Cqs\Queries\Orders\GetPickTimeSlotQuery;
use App\Cqs\Queries\Orders\GetPickTimeSlotQueryInput;
use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQuery;
use App\Cqs\Queries\Orders\GetTunnelOrderConfirmedQueryInput;
use App\Enums\FinalizeOrderStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Fo\Orders\ConfirmOrderRequest;
use App\Http\Requests\Fo\Orders\PickTimeSlotRequest;
use App\Http\Requests\Fo\Orders\ValidateSummaryRequest;
use App\Models\Order;
use Domain\Enums\OrderTunnelStep;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
@ -133,17 +133,27 @@ class TunnelController extends Controller
): RedirectResponse {
$this->authorize('canFinalizeOrder', OrderTunnelStep::class);
try {
/** @var \Domain\Models\ValueObjects\OrderReference $orderReference */
$orderReference = $this->executor->execute(
$action,
$request->toFinalizeOrderInput()
);
} catch (WeeklyLimitExceededException | OrderLimitExceededException $e) {
return back()->with('message', $e->getMessage());
}
/** @var FinalizeOrderOutput $output */
$output = $this->executor->execute(
$action,
$request->toFinalizeOrderInput()
);
return to_route('fo.sales.confirmation.show-confirmed', (string) $orderReference);
return match ($output->status) {
FinalizeOrderStatus::SUCCESS => to_route(
'fo.sales.confirmation.show-confirmed',
(string) ($output->orderReference
?? throw new \LogicException('Order reference is missing on success output.'))
),
FinalizeOrderStatus::EXPIRED_TIME_SLOT => to_route('fo.sales.pick-time-slot')->withErrors([
'timeslot' => trans($output->errorMessage ?? ''),
]),
FinalizeOrderStatus::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),
};
}
// * -- CONFIRMATION -- *

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Domain\Exceptions\OrderTunnel;
class ExpiredPickupTimeSlotException extends \DomainException
{
public function __construct(
string $message = 'Invalid or unavailable time slot',
int $code = 0,
?\Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Domain\Exceptions\OrderTunnel;
class UnorderableProductException extends \DomainException
{
public function __construct(
string $message = 'One or more products in your basket are no longer available for order.',
int $code = 0,
?\Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}

View file

@ -31,5 +31,8 @@ interface ProductRepository extends Repository
public function delete(Product $product): void;
/**
* @throws \Domain\Exceptions\OrderTunnel\UnorderableProductException
*/
public function getBasketProduct(ProductId $id, int $qty): BasketProduct;
}

View file

@ -10,8 +10,10 @@ use Domain\Builders\OrderBuilder;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Builders\OrderBuilderWithBasket;
use Domain\Enums\OrderTunnelStep;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException;
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;
@ -184,6 +186,8 @@ class OrderTunnelService
/**
* @throws WeeklyLimitExceededException
* @throws OrderLimitExceededException
* @throws ExpiredPickupTimeSlotException
* @throws UnorderableProductException
*/
public function finalizeOrder(OrderBuilderCompleted $builder): Order
{
@ -206,6 +210,8 @@ class OrderTunnelService
throw new \DomainException("Shop with id '{$shopId->value}' not found.");
}
$this->assertPickupTimeSlotIsAvailable($shop, $pickupTimeSlot);
$order = $this->orderService->createOrderFromBasket(
$basket,
$pickupTimeSlot,
@ -224,6 +230,22 @@ class OrderTunnelService
});
}
/**
* @throws \Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException
*/
private function assertPickupTimeSlotIsAvailable(Shop $shop, PickupTimeSlot $pickupTimeSlot): void
{
$availableSlots = $this->getAvailableTimeSlots($shop);
foreach ($availableSlots as $slot) {
if (CarbonImmutable::instance($pickupTimeSlot->getAt())->isSameDay($slot->getAt())) {
return;
}
}
throw new ExpiredPickupTimeSlotException();
}
private function getTimeslotsUntil(): CarbonInterface
{
return CarbonImmutable::now()->addDays(self::TIMESLOTS_DAY_TARGET);

View file

@ -7,6 +7,7 @@ namespace Infrastructure\Adapters\Repositories;
use App\Models\Product;
use Carbon\CarbonImmutable;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Models\Entities\Product as DomainProduct;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\Entities\ProductId;
@ -95,6 +96,10 @@ class EloquentProductRepository implements ProductRepository
->delete();
}
/**
* @throws \Domain\Exceptions\OrderTunnel\UnorderableProductException
*/
#[\Override]
public function getBasketProduct(ProductId $id, int $qty): BasketProduct
{
$product = Product::query()
@ -103,7 +108,12 @@ class EloquentProductRepository implements ProductRepository
->firstOrFail();
$domainProduct = $this->toEntity($product);
$pricing = $domainProduct->pricing();
if (! $domainProduct->isOrderable()) {
throw new UnorderableProductException();
}
$pricing = $domainProduct->pricing();
return new BasketProduct(
id: $id,

View file

@ -487,6 +487,7 @@
"OK": "OK",
"Old password": "Old password",
"On": "On",
"One or more products in your basket are no longer available for order.": "One or more products in your basket are no longer available for order.",
"Oops! An error occurred...": "Oops! An error occurred...",
"Open": "Open",
"Open in a current window": "Open in a current window",

View file

@ -481,6 +481,7 @@
"OK": "OK",
"Old password": "Ancien mot de passe",
"On": "Le",
"One or more products in your basket are no longer available for order.": "Un ou plusieurs produits de votre panier ne sont plus disponibles à la commande.",
"Oops! An error occurred...": "Oups ! Une erreur s'est produite...",
"Open": "Ouvrir",
"Open in a current window": "Ouvrir dans une fenêtre actuelle",

View file

@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Contracts\Executor;
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput;
use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput;
use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput;
@ -17,7 +18,6 @@ use Database\Seeders\ContentSeeder;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Enums\OrderStatus;
use Domain\Enums\OrderTunnelStep;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Models\Entities\Basket;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\DeliveryAddress;
@ -492,7 +492,7 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock) use ($orderReference): void {
$mock->shouldReceive('execute')
->once()
->andReturn($orderReference);
->andReturn(FinalizeOrderOutput::success($orderReference));
});
// WHEN
@ -529,7 +529,9 @@ describe('TunnelController', function (): void {
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andThrow(new WeeklyLimitExceededException());
->andReturn(FinalizeOrderOutput::weeklyLimitExceeded(
'The total amount for this delivery date has been exceeded. Please modify it to validate.'
));
});
// WHEN
@ -542,6 +544,88 @@ describe('TunnelController', function (): void {
->assertSessionHas('message');
});
it('redirects to pick time slot with errors when ExpiredPickupTimeSlotException occurs 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('test@example.com');
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::expiredTimeSlot('Invalid or unavailable time slot'));
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.pick-time-slot')
->assertSessionHasErrors([
'timeslot' => trans('Invalid or unavailable time slot'),
]);
});
it('redirects to basket summary with errors when UnorderableProductException occurs 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('test@example.com');
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function ($mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(FinalizeOrderOutput::unorderableProduct(
'One or more products in your basket are no longer available for order.'
));
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.summary')
->assertSessionHasErrors([
'basket' => trans('One or more products in your basket are no longer available for order.'),
]);
});
it('displays confirmed order view when customer is authorized', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Models\Product;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Models\Entities\Product as DomainProduct;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Models\ValueObjects\Entities\ProductId;
@ -40,16 +41,31 @@ beforeEach(function () {
$table->boolean('weight_variable')->default(false);
// Required for toDomain
$table->string('invoicing_unit')->nullable();
$table->string('sell_unit')->nullable();
$table->unsignedBigInteger('range_id')->default(1);
$table->string('status')->nullable();
$table->integer('price')->nullable();
$table->integer('price_kg')->nullable();
$table->string('origin_country')->nullable();
$table->text('conservation')->nullable();
$table->timestamp('orderable_start')->nullable();
$table->timestamp('orderable_end')->nullable();
$table->timestamps();
});
}
if (! Schema::hasTable('product_incos')) {
Schema::create('product_incos', function (Blueprint $table) {
$table->id();
$table->uuid('product_id');
$table->unsignedInteger('no_art');
$table->timestamps();
});
}
DB::table('product_incos')->delete();
DB::table('products')->delete();
});
@ -79,6 +95,7 @@ it('retrieves a basket product', function () {
'status' => 1,
'price' => new Money(100, $currency),
]);
DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]);
$id = new ProductId(Uuid::fromString($uuid));
@ -93,6 +110,146 @@ it('retrieves a basket product', function () {
->and($result->qty)->toBe(2);
});
it('throws UnorderableProductException when retrieving a basket product without inco', function (): void {
// GIVEN
$uuid = Uuid::uuid7()->toString();
$currency = new Currency('EUR');
Product::query()->forceCreate([
'id' => $uuid,
'name' => 'Product Without Inco',
'tax_rate' => 1,
'weight' => 1000,
'brand' => 'none',
'order_unit' => OrderUnit::PCE->value,
'invoicing_unit' => 'PCE',
'sell_unit' => 'PCE',
'range_id' => 1,
'slug' => 'product-without-inco',
'picture' => 'pic.jpg',
'picture_alt' => '',
'picture_title' => '',
'picture_large_alt' => '',
'picture_large_title' => '',
'description' => 'Desc',
'weight_variable' => false,
'status' => 1,
'price' => new Money(100, $currency),
]);
$id = new ProductId(Uuid::fromString($uuid));
$repo = new EloquentProductRepository();
// WHEN
$action = fn () => $repo->getBasketProduct($id, 1);
// THEN
expect($action)->toThrow(UnorderableProductException::class);
});
it('throws UnorderableProductException when retrieving an unpublished basket product', function (): void {
// GIVEN
$uuid = Uuid::uuid7()->toString();
$currency = new Currency('EUR');
Product::query()->forceCreate([
'id' => $uuid,
'name' => 'Unpublished Product',
'tax_rate' => 1,
'weight' => 1000,
'brand' => 'none',
'order_unit' => OrderUnit::PCE->value,
'invoicing_unit' => 'PCE',
'sell_unit' => 'PCE',
'range_id' => 1,
'slug' => 'unpublished-product',
'picture' => 'pic.jpg',
'picture_alt' => '',
'picture_title' => '',
'picture_large_alt' => '',
'picture_large_title' => '',
'description' => 'Desc',
'weight_variable' => false,
'status' => 0,
'price' => new Money(100, $currency),
]);
DB::table('product_incos')->insert(['product_id' => $uuid, 'no_art' => 12345]);
$id = new ProductId(Uuid::fromString($uuid));
$repo = new EloquentProductRepository();
// WHEN
$action = fn () => $repo->getBasketProduct($id, 1);
// THEN
expect($action)->toThrow(UnorderableProductException::class);
});
it('throws UnorderableProductException when retrieving a basket product outside orderable dates', function (): void {
// GIVEN
$expiredUuid = Uuid::uuid7()->toString();
$futureUuid = Uuid::uuid7()->toString();
$currency = new Currency('EUR');
Product::query()->forceCreate([
'id' => $expiredUuid,
'name' => 'Expired Product',
'tax_rate' => 1,
'weight' => 1000,
'brand' => 'none',
'order_unit' => OrderUnit::PCE->value,
'invoicing_unit' => 'PCE',
'sell_unit' => 'PCE',
'range_id' => 1,
'slug' => 'expired-product',
'picture' => 'pic.jpg',
'picture_alt' => '',
'picture_title' => '',
'picture_large_alt' => '',
'picture_large_title' => '',
'description' => 'Desc',
'weight_variable' => false,
'status' => 1,
'orderable_end' => now()->subDay(),
'price' => new Money(100, $currency),
]);
DB::table('product_incos')->insert(['product_id' => $expiredUuid, 'no_art' => 12345]);
Product::query()->forceCreate([
'id' => $futureUuid,
'name' => 'Future Product',
'tax_rate' => 1,
'weight' => 1000,
'brand' => 'none',
'order_unit' => OrderUnit::PCE->value,
'invoicing_unit' => 'PCE',
'sell_unit' => 'PCE',
'range_id' => 1,
'slug' => 'future-product',
'picture' => 'pic.jpg',
'picture_alt' => '',
'picture_title' => '',
'picture_large_alt' => '',
'picture_large_title' => '',
'description' => 'Desc',
'weight_variable' => false,
'status' => 1,
'orderable_start' => now()->addDay(),
'price' => new Money(100, $currency),
]);
DB::table('product_incos')->insert(['product_id' => $futureUuid, 'no_art' => 12346]);
$repo = new EloquentProductRepository();
// WHEN
$expiredAction = fn () => $repo->getBasketProduct(new ProductId(Uuid::fromString($expiredUuid)), 1);
$futureAction = fn () => $repo->getBasketProduct(new ProductId(Uuid::fromString($futureUuid)), 1);
// THEN
expect($expiredAction)->toThrow(UnorderableProductException::class)
->and($futureAction)->toThrow(UnorderableProductException::class);
});
it('finds a product by id', function () {
// GIVEN
$uuid = Uuid::uuid7()->toString();

View file

@ -4,8 +4,14 @@ 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 Domain\Builders\OrderBuilderCompleted;
use Domain\Enums\OrderStatus;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
use Domain\Models\Entities\Order;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Entities\OrderId;
@ -67,7 +73,109 @@ describe('FinalizeOrder', function (): void {
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(OrderReference::class)
->and($result->value)->toBe($orderReference->value);
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 ExpiredPickupTimeSlotException is thrown', 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);
// WHEN
$result = $action($input);
// THEN
expect($result)->toBeInstanceOf(FinalizeOrderOutput::class)
->and($result->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT)
->and($result->orderReference)->toBeNull()
->and($result->errorMessage)->toBe('Invalid or unavailable time slot');
});
it('returns unorderableProduct output when UnorderableProductException is thrown', function (): void {
// 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);
// 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 OrderLimitExceededException is thrown', 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);
// 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 WeeklyLimitExceededException is thrown', 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);
// 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.');
});
});

View file

@ -5,12 +5,15 @@ declare(strict_types=1);
namespace Tests\Unit\Domain\Services;
use Carbon\CarbonImmutable;
use Carbon\WeekDay;
use DateInterval;
use Domain\Builders\OrderBuilder;
use Domain\Enums\OrderTunnelStep;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException;
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
use Domain\Models\Entities\Basket;
use Domain\Models\Entities\Order;
use Domain\Models\Entities\Shop;
@ -88,9 +91,10 @@ function createTestBuilder(bool $completed = false): OrderBuilder
$builder = OrderBuilder::fromBasket($basket, $shopperId);
if ($completed) {
$shopId = new ShopId(Uuid::uuid7());
$timeSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new DateInterval('PT1H'));
$builder = $builder->withPickupTimeSlot($shopId, $timeSlot);
$shopId = new ShopId(Uuid::uuid7());
$nextFriday = CarbonImmutable::now('Europe/Paris')->next(WeekDay::Friday->value)->addWeek()->startOfDay();
$timeSlot = new PickupTimeSlot($nextFriday, new DateInterval('PT1H'));
$builder = $builder->withPickupTimeSlot($shopId, $timeSlot);
}
/** @var OrderBuilder $builder */
@ -135,9 +139,12 @@ function createOrderTunnelService(
);
})->byDefault();
}
$shopRepository ??= mock(ShopRepository::class);
$shopperRepository ??= mock(ShopperRepository::class);
$pickupExceptionRepository ??= mock(PickupExceptionRepository::class);
$shopRepository ??= mock(ShopRepository::class);
$shopperRepository ??= mock(ShopperRepository::class);
if ($pickupExceptionRepository === null) {
$pickupExceptionRepository = mock(PickupExceptionRepository::class);
$pickupExceptionRepository->shouldReceive('getExceptionsForShop')->andReturn([])->byDefault();
}
$orderBuilderSessionManager ??= mock(OrderBuilderSessionManager::class);
$orderRepository ??= mock(OrderRepository::class);
@ -723,4 +730,109 @@ describe('OrderTunnelService', function (): void {
// THEN
expect($order)->toBeInstanceOf(Order::class);
});
it('throws ExpiredPickupTimeSlotException when finalizing order with an expired or unavailable pickup time slot', function (): void {
// GIVEN
$basket = createTestBasket(1);
$shopperId = new ShopperId(Uuid::uuid7());
$shopId = new ShopId(Uuid::uuid7());
$expiredSlot = new PickupTimeSlot(CarbonImmutable::create(2025, 1, 1), new DateInterval('PT1H'));
$builder = OrderBuilder::fromBasket($basket, $shopperId)->withPickupTimeSlot($shopId, $expiredSlot);
/** @var \Domain\Builders\OrderBuilderCompleted $builder */
$shopper = new Shopper(
id: $shopperId,
email: new Email('test@test.com'),
matricule: new Matricule('1234567'),
nom: 'Doe',
prenom: 'John',
startDate: CarbonImmutable::now()->subYear(),
endDate: null,
etablissement: new ShopperEstablishmentCode('ETAB01'),
site: new ShopperSiteCode('SITEA'),
service: new ShopperServiceCode('101')
);
$shopperRepo = mock(ShopperRepository::class);
$shopperRepo->shouldReceive('getByIdOrFail')->with(\Mockery::type(ShopperId::class))->andReturn($shopper);
$shop = new Shop($shopId, 'Shop', 'Address', '75000', 'Paris');
$shopRepo = mock(ShopRepository::class);
$shopRepo->shouldReceive('find')->andReturn($shop);
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldReceive('persist')->once();
$basketRepo->shouldNotReceive('delete');
$orderRepo = mock(OrderRepository::class);
$orderRepo->shouldNotReceive('persist');
$transactionManager = mock(TransactionManager::class);
$transactionManager->shouldReceive('execute')->once()->andReturnUsing(function ($callback) {
return $callback();
});
$eventDispatcher = mock(DomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('dispatch');
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldNotReceive('clear');
$service = createOrderTunnelService(
basketRepository: $basketRepo,
shopRepository: $shopRepo,
shopperRepository: $shopperRepo,
orderBuilderSessionManager: $builderRepo,
orderRepository: $orderRepo,
transactionManager: $transactionManager,
eventDispatcher: $eventDispatcher
);
// WHEN
$action = fn () => $service->finalizeOrder($builder);
// THEN
expect($action)->toThrow(ExpiredPickupTimeSlotException::class);
});
it('throws UnorderableProductException when finalizing order with an unorderable product in basket', function (): void {
// GIVEN
/** @var \Domain\Builders\OrderBuilderCompleted $builder */
$builder = createTestBuilder(completed: true);
$productRepo = mock(ProductRepository::class);
$productRepo->shouldReceive('getBasketProduct')
->once()
->andThrow(new UnorderableProductException());
$basketRepo = mock(BasketRepository::class);
$basketRepo->shouldNotReceive('persist');
$basketRepo->shouldNotReceive('delete');
$orderRepo = mock(OrderRepository::class);
$orderRepo->shouldNotReceive('persist');
$transactionManager = mock(TransactionManager::class);
$transactionManager->shouldNotReceive('execute');
$eventDispatcher = mock(DomainEventDispatcher::class);
$eventDispatcher->shouldNotReceive('dispatch');
$builderRepo = mock(OrderBuilderSessionManager::class);
$builderRepo->shouldNotReceive('clear');
$service = createOrderTunnelService(
basketRepository: $basketRepo,
productRepository: $productRepo,
orderBuilderSessionManager: $builderRepo,
orderRepository: $orderRepo,
transactionManager: $transactionManager,
eventDispatcher: $eventDispatcher
);
// WHEN
$action = fn () => $service->finalizeOrder($builder);
// THEN
expect($action)->toThrow(UnorderableProductException::class);
});
});