diff --git a/app/Cqs/Actions/Orders/FinalizeOrder.php b/app/Cqs/Actions/Orders/FinalizeOrder.php index df65eb30..17518e56 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrder.php +++ b/app/Cqs/Actions/Orders/FinalizeOrder.php @@ -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()), + }; + } } } diff --git a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php new file mode 100644 index 00000000..e37f3aaa --- /dev/null +++ b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php @@ -0,0 +1,58 @@ +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 -- * diff --git a/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php b/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php new file mode 100644 index 00000000..95092ba9 --- /dev/null +++ b/domain/Exceptions/OrderTunnel/ExpiredPickupTimeSlotException.php @@ -0,0 +1,16 @@ +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); diff --git a/infra/Adapters/Repositories/EloquentProductRepository.php b/infra/Adapters/Repositories/EloquentProductRepository.php index 4b93fe95..155ec077 100644 --- a/infra/Adapters/Repositories/EloquentProductRepository.php +++ b/infra/Adapters/Repositories/EloquentProductRepository.php @@ -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, diff --git a/lang/en.json b/lang/en.json index 1c017d99..23b7abe1 100644 --- a/lang/en.json +++ b/lang/en.json @@ -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", diff --git a/lang/fr.json b/lang/fr.json index 2f3d679f..36157b6a 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -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", diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index f5d9319f..c542d5b0 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -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 diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php index 37d35260..c3881c82 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentProductRepositoryTest.php @@ -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(); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php index 3db69d85..2067dafc 100644 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php @@ -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.'); }); }); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index 1efbf9db..ac8ff48c 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -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); + }); });