diff --git a/tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php b/tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php new file mode 100644 index 00000000..1c63839e --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php @@ -0,0 +1,157 @@ +name = 'Gamme Panier ' . 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' => 'Produit Panier ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description panier', + 'status' => $status, + ]); + $product->price = Money::EUR(1000); + $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(); + + if ($withInco) { + $inco = new ProductInco(); + $inco->product_id = $product->id; + $inco->no_art = random_int(10000, 99999); + $inco->saveOrFail(); + } + + return $product; +} + +describe('AddToBasket action', function (): void { + it('adds an orderable product to session basket and increments quantity on repeated additions', function (): void { + // GIVEN + $product = makeBasketProductFixture(); + $session = Session::driver(); + $repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $dispatcher = new LaravelDomainEventDispatcher(); + $basketSvc = new BasketService( + $repository, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $action = new AddToBasket($basketSvc); + + // WHEN + $action(new AddToBasketInput($product->getId(), 2)); + $action(new AddToBasketInput($product->getId(), 3)); + + // THEN + $basket = $basketSvc->getBasket(); + expect($basket->countItems())->toBe(5) + ->and($basket->items())->toHaveCount(1) + ->and($basket->items()[$product->id]->qty)->toBe(5) + ->and($basket->items()[$product->id]->unitPriceHt->getAmount())->toBe('1000'); + }); + + it('invalidates existing order builder in session when executed through ActionExecutorService', function (): void { + // GIVEN + $product = makeBasketProductFixture(); + $session = Session::driver(); + $repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + )); + + $dispatcher = new LaravelDomainEventDispatcher(); + $basketSvc = new BasketService( + $repository, + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new AddToBasket($basketSvc), new AddToBasketInput($product->getId(), 1)); + + // THEN + expect($builderManager->get())->toBeNull() + ->and($basketSvc->getBasket()->countItems())->toBe(1); + }); + + it('throws UnorderableProductException when product is disabled or missing inco', function (): void { + // GIVEN + $inactiveProduct = makeBasketProductFixture(status: false, withInco: true); + $noIncoProduct = makeBasketProductFixture(status: true, withInco: false); + $session = Session::driver(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + new LaravelDomainEventDispatcher(), + ); + $action = new AddToBasket($basketSvc); + + // WHEN & THEN + expect(fn () => $action(new AddToBasketInput($inactiveProduct->getId(), 1))) + ->toThrow(UnorderableProductException::class); + expect(fn () => $action(new AddToBasketInput($noIncoProduct->getId(), 1))) + ->toThrow(UnorderableProductException::class); + expect($basketSvc->hasItems())->toBeFalse(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php b/tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php new file mode 100644 index 00000000..b0e8b943 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php @@ -0,0 +1,103 @@ +name = 'Gamme Vider Panier ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit À Vider ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc', + 'status' => true, + ]); + $product->price = Money::EUR(900); + $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 = random_int(10000, 99999); + $inco->saveOrFail(); + + $session = Session::driver(); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $dispatcher = new LaravelDomainEventDispatcher(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $basketSvc->add($product->getId(), 2); + + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + )); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new EmptyBasket($basketSvc), ActionInputEmpty::create()); + + // THEN + expect($basketSvc->hasItems())->toBeFalse() + ->and($basketSvc->getBasket()->items())->toBeEmpty() + ->and($builderManager->get())->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Basket/RemoveFromBasketTest.php b/tests/Integration/WithApp/App/Actions/Basket/RemoveFromBasketTest.php new file mode 100644 index 00000000..7d618c49 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Basket/RemoveFromBasketTest.php @@ -0,0 +1,141 @@ +name = 'Gamme Retrait Panier ' . 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' => 'Produit Retrait ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Description retrait', + 'status' => true, + ]); + $product->price = Money::EUR(800); + $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 = random_int(10000, 99999); + $inco->saveOrFail(); + + return $product; +} + +describe('RemoveFromBasket action', function (): void { + it('decrements quantity and removes the line when RemoveQuantityFromBasketInput hits zero', function (): void { + // GIVEN + $product = makeRemovableProductFixture(); + $session = Session::driver(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + new LaravelDomainEventDispatcher(), + ); + $basketSvc->add($product->getId(), 5); + $action = new RemoveFromBasket($basketSvc); + + // WHEN + $action(new RemoveQuantityFromBasketInput($product->getId(), 2)); + + // THEN + expect($basketSvc->getBasket()->items()[$product->id]->qty)->toBe(3); + + // WHEN removing remaining quantity + $action(new RemoveQuantityFromBasketInput($product->getId(), 3)); + + // THEN + expect($basketSvc->hasItems())->toBeFalse(); + }); + + it('removes the whole product line with RemoveProductFromBasketInput and clears order builder', function (): void { + // GIVEN + $product1 = makeRemovableProductFixture(); + $product2 = makeRemovableProductFixture(); + $session = Session::driver(); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $dispatcher = new LaravelDomainEventDispatcher(); + $basketSvc = new BasketService( + new SessionBasketRepository($session, 'basket_', new BasketSerializer()), + new EloquentProductRepository(), + new AppSessionService('domain_session_uuid'), + $dispatcher, + ); + $basketSvc->add($product1->getId(), 4); + $basketSvc->add($product2->getId(), 2); + + $builderManager->save(OrderBuilder::fromBasket( + new Basket(new BasketId(Uuid::uuid7()), []), + new ShopperId(Uuid::uuid7()), + )); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + $dispatcher, + ); + + // WHEN + $executor->execute(new RemoveFromBasket($basketSvc), new RemoveProductFromBasketInput($product1->getId())); + + // THEN + $basket = $basketSvc->getBasket(); + expect($basket->countItems())->toBe(2) + ->and($basket->items())->toHaveCount(1) + ->and(array_key_exists($product1->id, $basket->items()))->toBeFalse() + ->and($basket->items()[$product2->id]->qty)->toBe(2) + ->and($builderManager->get())->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Crm/UnsubscribeFromNewsletterTest.php b/tests/Integration/WithApp/App/Actions/Crm/UnsubscribeFromNewsletterTest.php new file mode 100644 index 00000000..2145cd8f --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Crm/UnsubscribeFromNewsletterTest.php @@ -0,0 +1,71 @@ +shouldReceive('unsubscribeCustomer') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value)) + ->andReturnTrue(); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::SUCCESS); + }); + + it('returns FAILURE when CRM service returns false', function (): void { + // GIVEN + $hashcode = new CrmHashcode(Uuid::uuid4()); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('unsubscribeCustomer') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value)) + ->andReturnFalse(); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE); + }); + + it('returns FAILURE without throwing when CRM service throws an exception', function (): void { + // GIVEN + $hashcode = new CrmHashcode(Uuid::uuid4()); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('unsubscribeCustomer') + ->once() + ->andThrow(new \RuntimeException('CRM timeout')); + + $action = new UnsubscribeFromNewsletter($crmService); + + // WHEN + $output = $action(new UnsubscribeFromNewsletterInput($hashcode)); + + // THEN + expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerPasswordTest.php b/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerPasswordTest.php new file mode 100644 index 00000000..c5927488 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerPasswordTest.php @@ -0,0 +1,154 @@ +toString(); + $customer = new Customer(); + $customer->email = new Email('claire.dupuis@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode)) + ->andReturn($crmCustomer); + $crmService->shouldReceive('changePassword') + ->once() + ->with($crmCustomer, 'OldPass123!', 'NewPass456!') + ->andReturn($crmCustomer); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output)->toBeInstanceOf(UpdateCustomerPasswordOutput::class) + ->and($output->result)->toBe($crmCustomer); + }); + + it('returns false output when customer cannot be resolved in CRM', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(); + $customer->email = new Email('missing.crm@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturnNull(); + $crmService->shouldNotReceive('changePassword'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('returns false output when changePassword throws an unexpected exception', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $hashcodeUuid = Uuid::uuid4(); + $hashcode = $hashcodeUuid->toString(); + $customer = new Customer(); + $customer->email = new Email('pwd.error@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('getCustomerFromHashCode') + ->once() + ->andReturn($crmCustomer); + $crmService->shouldReceive('changePassword') + ->once() + ->andThrow(new \RuntimeException('CRM error')); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN + $output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('throws AuthServiceException when unauthenticated', function (): void { + // GIVEN + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('getCustomerFromHashCode'); + $crmService->shouldNotReceive('changePassword'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomerPassword($authService, $crmService); + + // WHEN & THEN + expect(fn () => $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!'))) + ->toThrow(AuthServiceException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php b/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php new file mode 100644 index 00000000..05584cd1 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php @@ -0,0 +1,206 @@ +toString(); + $customer = new Customer(); + $customer->email = new Email('jeanne.martin@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $expectedCrmCustomer = makeCrmCustomerDto($hashcode, $customer->email->value); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->withArgs(function (Customer $passedCustomer, array $data) use ($customer): bool { + return $passedCustomer->id === $customer->id + && $data === [ + 'firstname' => 'Jeanne', + 'lastname' => 'Martin', + 'birth_date' => '1992-05-14', + 'postcode' => '53000', + 'city' => 'Laval', + 'opt_in' => true, + 'phone' => '+33611223344', + 'address' => '12 rue des Lilas', + ]; + }) + ->andReturn($expectedCrmCustomer); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Jeanne', + lastname: 'Martin', + birthDate: '1992-05-14', + phone: '+33611223344', + address: '12 rue des Lilas', + postcode: '53000', + city: 'Laval', + optIn: true, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output)->toBeInstanceOf(UpdateCustomerOutput::class) + ->and($output->result)->toBe($expectedCrmCustomer); + }); + + it('omits nullable phone and address when null and propagates validation exceptions', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $hashcodeUuid = Uuid::uuid4(); + $customer = new Customer(); + $customer->email = new Email('no.phone@example.com'); + $customer->hashcode = new CrmHashcode($hashcodeUuid); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + $validationException = ValidationException::withMessages(['postcode' => ['Code postal invalide']]); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->withArgs(function (Customer $_, array $data): bool { + return ! array_key_exists('phone', $data) + && ! array_key_exists('address', $data) + && $data['opt_in'] === false; + }) + ->andReturn($validationException); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Paul', + lastname: 'Durand', + birthDate: '1985-03-10', + phone: null, + address: null, + postcode: '00000', + city: 'Sablé', + optIn: false, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output->result)->toBe($validationException); + }); + + it('returns false output when CRM service throws an unexpected error', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $customer = new Customer(); + $customer->email = new Email('err.crm@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->saveOrFail(); + + $this->actingAs($customer, 'frontend'); + + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldReceive('updateCustomerInfos') + ->once() + ->andThrow(new \RuntimeException('CRM unavailable')); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Paul', + lastname: 'Durand', + birthDate: '1985-03-10', + phone: null, + address: null, + postcode: '72300', + city: 'Sablé', + optIn: true, + ); + + // WHEN + $output = $action($input); + + // THEN + expect($output->result)->toBeFalse(); + }); + + it('throws AuthServiceException when no customer is authenticated', function (): void { + // GIVEN + /** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */ + $crmService = \Mockery::mock(CrmService::class); + $crmService->shouldNotReceive('updateCustomerInfos'); + + $authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService); + $action = new UpdateCustomer($authService, $crmService); + + $input = new UpdateCustomerInput( + firstname: 'Guest', + lastname: 'User', + birthDate: '1990-01-01', + phone: null, + address: null, + postcode: '72300', + city: 'Sablé', + optIn: false, + ); + + // WHEN & THEN + expect(fn () => $action($input)) + ->toThrow(AuthServiceException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/ApplyPickTimeSlotTest.php b/tests/Integration/WithApp/App/Actions/Orders/ApplyPickTimeSlotTest.php new file mode 100644 index 00000000..0116ce0c --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/ApplyPickTimeSlotTest.php @@ -0,0 +1,185 @@ +create(['default' => true]); + + $customer = new Customer(); + $customer->email = new Email('slot.buyer@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->saveOrFail(); + + $employee = new Employee(); + $employee->customer_id = $customer->id; + $employee->matricule = new Matricule('1000303'); + $employee->code = new Code('ABCDEF'); + $employee->nom = 'Durand'; + $employee->prenom = 'Sophie'; + $employee->start_date = CarbonImmutable::parse('2025-01-01'); + $employee->etablissement = new ShopperEstablishmentCode('01'); + $employee->site = new ShopperSiteCode('SITE'); + $employee->service = new ShopperServiceCode('01'); + $employee->saveOrFail(); + + $productId = new ProductId(Uuid::uuid7()); + $basket = new Basket(new BasketId(Uuid::uuid7()), [ + $productId->value->toString() => new BasketProduct( + id: $productId, + name: 'Filet de Poulet', + qty: 1, + unitPriceHt: Money::EUR(1000), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 500, + brand: ProductBrand::loue, + incoId: new IncoId(654321), + orderUnit: OrderUnit::PCE, + slug: 'filet-de-poulet', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::zero(), + priceKgTtc: Money::EUR(1000), + options: [], + ), + ]); + + $session = Session::driver(); + $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); + $builderManager->save(OrderBuilder::fromBasket($basket, $customer->getId())); + + $shopRepo = new EloquentShopRepository(); + $shopperRepo = new EloquentShopperRepository(); + $orderRepo = new EloquentOrderRepository(); + + /** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $regateService */ + $regateService = \Mockery::mock(RegateService::class); + + $tunnelService = new OrderTunnelService( + new LaravelDomainEventDispatcher(), + 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, + ); + + return [$customer, $shop, $builderManager, $tunnelService]; + } + + it('matches an open pickup day and upgrades the session builder to OrderBuilderCompleted', function (): void { + // GIVEN + [$customer, $shop, $builderManager, $tunnelService] = makePickSlotEnvironment(); + $action = new ApplyPickTimeSlot($tunnelService); + + // Friday of current week after Monday 10:00 cutoff -> open + $targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris'); + + // WHEN + $output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday)); + + // THEN + expect($output)->toBeInstanceOf(ApplyPickTimeSlotOutput::class) + ->and($output->status)->toBe(ApplyPickTimeSlotStatus::MATCHED) + ->and($output->timeSlot)->not->toBeNull() + ->and($output->timeSlot?->getAt()->format('Y-m-d'))->toBe('2026-11-20'); + + $completed = $builderManager->get(); + expect($completed)->toBeInstanceOf(OrderBuilderCompleted::class) + ->and($completed?->getShopId()->equals($shop->getId()))->toBeTrue(); + }); + + it('returns UNAVAILABLE when the requested date is blocked by a shop PickupException', function (): void { + // GIVEN + [$customer, $shop, $_, $tunnelService] = makePickSlotEnvironment(); + + $blockedException = PickupException::factory()->create([ + 'date' => '2026-11-20', + 'label' => 'Fermeture exceptionnelle', + ]); + $shop->pickupExceptions()->attach($blockedException->id, [ + 'replacement_date' => null, + 'order_deadline_at' => null, + ]); + + $action = new ApplyPickTimeSlot($tunnelService); + $targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris'); + + // WHEN + $output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday)); + + // THEN + expect($output->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE) + ->and($output->timeSlot)->toBeNull(); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/CancelOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/CancelOrderTest.php new file mode 100644 index 00000000..54b9d01a --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/CancelOrderTest.php @@ -0,0 +1,77 @@ +create(); + + return Order::query()->forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'shop_id' => $shop->id, + 'reference' => new OrderReference(Uuid::uuid7()), + 'status' => $status->value, + 'total' => new Money(2500, new Currency('EUR')), + 'employee' => new OrderEmployee( + new Matricule('1000202'), + 'Alice', + 'Martin', + new ShopperEstablishmentCode('01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('01'), + ), + 'delivery_address' => new DeliveryAddress('Shop Test', '2 rue Test', '72300', 'Sablé'), + 'pickup_day' => '2026-11-20 14:00:00', + ]); +} + +describe('CancelOrder action', function (): void { + it('cancels an existing persisted order and updates status in database', function (): void { + // GIVEN + $order = makeCancelOrderFixture(OrderStatus::VALIDATED); + $action = new CancelOrder(new OrderService(new EloquentOrderRepository())); + + // WHEN + $output = $action(new CancelOrderInput($order)); + + // THEN + expect($output)->toBe(CancelOrderOutput::CANCELLED) + ->and($order->fresh()?->status)->toBe(OrderStatus::CANCELED); + }); + + it('returns NOT_FOUND when the order does not exist in database', function (): void { + // GIVEN + $missingOrder = new Order(); + $missingOrder->id = Uuid::uuid7()->toString(); + + $action = new CancelOrder(new OrderService(new EloquentOrderRepository())); + + // WHEN + $output = $action(new CancelOrderInput($missingOrder)); + + // THEN + expect($output)->toBe(CancelOrderOutput::NOT_FOUND); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php new file mode 100644 index 00000000..d14d752d --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php @@ -0,0 +1,409 @@ +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(); + $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, + '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']); + + // 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']); + + // 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']); + + // 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']); + + // 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']); + + // 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']); + + // 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']); + + // 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']); + + // 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); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Orders/InitializeOrderTunnelTest.php b/tests/Integration/WithApp/App/Actions/Orders/InitializeOrderTunnelTest.php new file mode 100644 index 00000000..89360205 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Orders/InitializeOrderTunnelTest.php @@ -0,0 +1,102 @@ +value->toString() => new BasketProduct( + id: $productId, + name: 'Poulet Rôti', + qty: 2, + unitPriceHt: Money::EUR(1200), + unitDiscount: Money::EUR(0), + taxRate: TaxRate::TVA_5_5, + weightGrams: 1200, + 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), + options: [], + ), + ]); + $shopperId = new ShopperId(Uuid::uuid7()); + + $action = new InitializeOrderTunnel($tunnelService); + + // WHEN + $action(new InitializeOrderTunnelInput($basket, $shopperId)); + + // THEN + $storedBuilder = $builderManager->get(); + expect($storedBuilder)->toBeInstanceOf(OrderBuilderWithBasket::class) + ->and($storedBuilder?->getShopperId()->equals($shopperId))->toBeTrue() + ->and($storedBuilder?->getBasket()->countItems())->toBe(2); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Products/CreateProductTest.php b/tests/Integration/WithApp/App/Actions/Products/CreateProductTest.php new file mode 100644 index 00000000..31b0ab32 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Products/CreateProductTest.php @@ -0,0 +1,249 @@ +name = 'Gamme Produit ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->saveOrFail(); + + return $range; +} + +describe('CreateProduct action', function (): void { + it('creates a product with tags, associated products, and S3 pictures', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $range = makeCreateProductRange(); + + $existingTag = Tag::factory()->create([ + 'label' => 'Déjà existant', + 'status' => true, + ]); + + $associated1 = new Product([ + 'range_id' => $range->id, + 'name' => 'Associé 1 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc 1', + 'status' => true, + ]); + $associated1->price = Money::EUR(500); + $associated1->picture_alt = 'a1'; + $associated1->picture_title = 't1'; + $associated1->picture_large_alt = 'al1'; + $associated1->picture_large_title = 'tl1'; + $associated1->saveOrFail(); + + $associated2 = new Product([ + 'range_id' => $range->id, + 'name' => 'Associé 2 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_5_5, + 'description' => 'Desc 2', + 'status' => true, + ]); + $associated2->price = Money::EUR(700); + $associated2->picture_alt = 'a2'; + $associated2->picture_title = 't2'; + $associated2->picture_large_alt = 'al2'; + $associated2->picture_large_title = 'tl2'; + $associated2->saveOrFail(); + + $disk = new PublicS3Disk('https://cdn.test'); + $picturePath = new StorageFilePath('products/create-pic.jpg'); + $largePath = new StorageFilePath('products/create-large.jpg'); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->twice() + ->andReturn($picturePath, $largePath); + $storage->shouldNotReceive('removeFromDisk'); + + $action = new CreateProduct( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + $orderableStart = CarbonImmutable::parse('2026-11-01 08:00:00'); + $orderableEnd = CarbonImmutable::parse('2026-12-31 20:00:00'); + + $input = new CreateProductInput( + name: 'Poulet Fermier Bio', + shortDescription: 'Courte description', + description: '
Description complète
', + price: Money::EUR(1990), + invoicingUnit: InvoicingUnit::KGM, + stock: 15, + rangeId: $range->id, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::COLIS, + taxRate: TaxRate::TVA_5_5, + brand: ProductBrand::loue, + weight: 1400, + weightVariable: true, + orderableStart: $orderableStart, + orderableEnd: $orderableEnd, + star: true, + status: true, + picture: UploadedFile::fake()->image('pic.jpg', 300, 300), + pictureAlt: 'Alt pic', + pictureTitle: 'Title pic', + pictureLarge: UploadedFile::fake()->image('large.jpg', 800, 800), + pictureLargeAlt: 'Alt large', + pictureLargeTitle: 'Title large', + tags: [ + ['id' => $existingTag->id, 'label' => $existingTag->label], + ['label' => 'Nouveau Tag Bio'], + ], + associatedProductsIds: [$associated2->id, $associated1->id], + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN + $product = $executor->execute($action, $input); + + // THEN + expect($product)->toBeInstanceOf(Product::class) + ->and($product->name)->toBe('Poulet Fermier Bio') + ->and($product->price->getAmount())->toBe('1990') + ->and($product->stock)->toBe(15) + ->and($product->weight)->toBe(1400) + ->and($product->weight_variable)->toBeTrue() + ->and($product->star)->toBeTrue() + ->and($product->status)->toBeTrue() + ->and($product->picture?->value)->toBe('products/create-pic.jpg') + ->and($product->picture_large?->value)->toBe('products/create-large.jpg') + ->and($product->tags()->pluck('label')->all())->toBe(['Déjà existant', 'Nouveau Tag Bio']); + + $associatedOrder = $product->products + ->pluck('id') + ->all(); + expect($associatedOrder)->toBe([$associated2->id, $associated1->id]); + + $this->assertDatabaseHas('products', [ + 'id' => $product->id, + 'name' => 'Poulet Fermier Bio', + 'range_id' => $range->id, + ]); + }); + + it('cleans up uploaded S3 files when persistence fails inside executor transaction', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $disk = new PublicS3Disk('https://cdn.test'); + $orphanPic = new StorageFilePath('products/orphan-pic.jpg'); + $orphanLarge = new StorageFilePath('products/orphan-large.jpg'); + + /** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */ + $storage = \Mockery::mock(StorageService::class); + $storage->shouldReceive('storeFileOntoDisk') + ->twice() + ->andReturn($orphanPic, $orphanLarge); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('fileExistsOnDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk) + ->andReturnTrue(); + $storage->shouldReceive('removeFromDisk') + ->once() + ->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk) + ->andReturnTrue(); + + $action = new CreateProduct( + $storage, + $disk, + new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()), + ); + + // Non-existent rangeId triggers FK constraint violation on saveOrFail() + $input = new CreateProductInput( + name: 'Produit Échec FK', + shortDescription: 'Court', + description: 'Description', + price: Money::EUR(1000), + invoicingUnit: InvoicingUnit::PCE, + stock: 1, + rangeId: 999999, + sellUnit: SellUnit::PCE, + orderUnit: OrderUnit::PCE, + taxRate: TaxRate::TVA_20, + brand: ProductBrand::loue, + picture: UploadedFile::fake()->image('pic.jpg', 200, 200), + pictureAlt: 'alt', + pictureTitle: 'title', + pictureLarge: UploadedFile::fake()->image('large.jpg', 400, 400), + pictureLargeAlt: 'alt large', + pictureLargeTitle: 'title large', + ); + + $executor = new ActionExecutorService( + new LaravelCacheLock(new Repository(new ArrayStore())), + new NullLogger(), + new LaravelDomainEventDispatcher(), + ); + + // WHEN & THEN + expect(fn () => $executor->execute($action, $input)) + ->toThrow(QueryException::class); + + $this->assertDatabaseMissing('products', [ + 'name' => 'Produit Échec FK', + ]); + }); +});