diff --git a/app/Cqs/Actions/Orders/FinalizeOrder.php b/app/Cqs/Actions/Orders/FinalizeOrder.php index edd13222..84cac1e9 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrder.php +++ b/app/Cqs/Actions/Orders/FinalizeOrder.php @@ -9,11 +9,13 @@ use App\Contracts\Action; use App\Contracts\ActionInput; use App\Contracts\HandlesLockTimeout; use App\Contracts\ProvidesLockKey; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; +use Domain\Ports\Repositories\BasketRepository; use Domain\Services\OrderTunnelService; use Webmozart\Assert\Assert; @@ -33,6 +35,7 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey { public function __construct( private readonly OrderTunnelService $orderTunnelService, + private readonly BasketRepository $basketRepository, ) { } @@ -72,6 +75,10 @@ final class FinalizeOrder implements Action, HandlesLockTimeout, ProvidesLockKey try { $order = $this->orderTunnelService->finalizeOrder($builder); + } catch (BasketPriceChangedException $e) { + $this->basketRepository->persist($e->refreshedBasket); + + return FinalizeOrderOutput::basketPriceChanged($e->getMessage()); } catch ( ExpiredPickupTimeSlotException | InactiveShopperException diff --git a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php index 599221eb..a4028001 100644 --- a/app/Cqs/Actions/Orders/FinalizeOrderOutput.php +++ b/app/Cqs/Actions/Orders/FinalizeOrderOutput.php @@ -48,6 +48,14 @@ final readonly class FinalizeOrderOutput ); } + public static function basketPriceChanged(string $errorMessage): self + { + return new self( + status: FinalizeOrderStatus::BASKET_PRICE_CHANGED, + errorMessage: $errorMessage, + ); + } + public static function orderLimitExceeded(string $errorMessage): self { return new self( diff --git a/app/Enums/FinalizeOrderStatus.php b/app/Enums/FinalizeOrderStatus.php index 9953047f..4a2b8416 100644 --- a/app/Enums/FinalizeOrderStatus.php +++ b/app/Enums/FinalizeOrderStatus.php @@ -9,6 +9,7 @@ enum FinalizeOrderStatus case SUCCESS; case EXPIRED_TIME_SLOT; case INACTIVE_SHOPPER; + case BASKET_PRICE_CHANGED; case UNORDERABLE_PRODUCT; case ORDER_LIMIT_EXCEEDED; case WEEKLY_LIMIT_EXCEEDED; diff --git a/app/Http/Controllers/Fo/TunnelController.php b/app/Http/Controllers/Fo/TunnelController.php index c349b10e..d57176e9 100644 --- a/app/Http/Controllers/Fo/TunnelController.php +++ b/app/Http/Controllers/Fo/TunnelController.php @@ -150,6 +150,7 @@ class TunnelController extends Controller 'timeslot' => trans($output->errorMessage ?? ''), ]), FinalizeOrderStatus::INACTIVE_SHOPPER => throw new CustomerNotEmployedException(), + FinalizeOrderStatus::BASKET_PRICE_CHANGED, FinalizeOrderStatus::UNORDERABLE_PRODUCT => to_route('fo.sales.summary')->withErrors([ 'basket' => trans($output->errorMessage ?? ''), ]), diff --git a/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php b/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php new file mode 100644 index 00000000..563dcb5d --- /dev/null +++ b/domain/Exceptions/OrderTunnel/BasketPriceChangedException.php @@ -0,0 +1,19 @@ +items() as $item) { - $refreshedItems[] = $this->productRepository->getBasketProduct($item->id, $item->qty); + $refreshed = $this->productRepository->getBasketProduct($item->id, $item->qty); + + if ($this->hasItemPricingChanged($item, $refreshed)) { + $priceChanged = true; + } + + $refreshedItems[] = $refreshed; } - return new Basket($basket->id, $refreshedItems); + $refreshedBasket = new Basket($basket->id, $refreshedItems); + + if ($priceChanged || ! $refreshedBasket->totalTaxIncluded()->equals($basket->totalTaxIncluded())) { + throw new BasketPriceChangedException($refreshedBasket); + } + + return $refreshedBasket; + } + + private function hasItemPricingChanged(BasketProduct $original, BasketProduct $refreshed): bool + { + return ! $refreshed->unitPriceHt->equals($original->unitPriceHt) + || ! $refreshed->unitDiscount->equals($original->unitDiscount) + || $refreshed->taxRate !== $original->taxRate + || ! $refreshed->totalTtc()->equals($original->totalTtc()); } /** diff --git a/lang/en.json b/lang/en.json index 1afd1c5f..f9765592 100644 --- a/lang/en.json +++ b/lang/en.json @@ -764,6 +764,7 @@ "The order": "The order", "The order deadline has passed. This item will no longer be available for purchase.": "The order deadline has passed. This item will no longer be available for purchase.", "The password must contain": "The password must contain", + "The price of one or more products in your basket has changed.": "The price of one or more products in your basket has changed.", "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.": "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.", "The range associated with the product": "The range associated with the product", "The response is not a streamed response.": "The response is not a streamed response.", diff --git a/lang/fr.json b/lang/fr.json index 035ac78f..9be9c2a8 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -764,6 +764,7 @@ "The order": "La commande", "The order deadline has passed. This item will no longer be available for purchase.": "La date limite de commande est dépassée. Le remplacement ne sera plus proposé aux clients.", "The password must contain": "Le mot de passe doit contenir", + "The price of one or more products in your basket has changed.": "Le prix d'un ou plusieurs produits de votre panier a changé.", "The publication status is updated according to the scheduled dates. To change the publication status, please edit or remove the corresponding dates.": "La publication est modifiée en concordance avec les dates enregistrées. Pour modifier l'état de publication, veuillez modifier ou enlever les dates correspondantes.", "The range associated with the product": "La gamme associée au produit", "The response is not a streamed response.": "La réponse n'est pas une réponse diffusée.", diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index 8e6005ed..c5acc13a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -638,6 +638,48 @@ describe('TunnelController', function (): void { ]); }); + it('redirects to basket summary with errors when BasketPriceChangedException 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::basketPriceChanged( + 'The price of one or more products in your basket has changed.' + )); + }); + + // WHEN + $response = $this->from('/commande/confirmation')->post('/commande/confirmation', [ + 'ok_cgv' => '1', + ]); + + // THEN + $response->assertRedirectToRoute('fo.sales.summary') + ->assertSessionHasErrors([ + 'basket' => trans('The price of one or more products in your basket has changed.'), + ]); + }); + it('redirects back with message when LockTimeout occurs on confirmation submit', function (): void { /** @var \Tests\TestCase $this */ // GIVEN diff --git a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php index d14d752d..f7555be9 100644 --- a/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Integration/WithApp/App/Actions/Orders/FinalizeOrderTest.php @@ -63,6 +63,8 @@ use Infrastructure\Adapters\Repositories\EloquentPickupExceptionRepository; use Infrastructure\Adapters\Repositories\EloquentProductRepository; use Infrastructure\Adapters\Repositories\EloquentShopperRepository; use Infrastructure\Adapters\Repositories\EloquentShopRepository; +use Infrastructure\Adapters\Repositories\SessionBasketRepository; +use Infrastructure\Adapters\Serializers\BasketSerializer; use Infrastructure\Adapters\Services\CsvGeneratorImpl; use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService; use Infrastructure\Adapters\Services\SessionOrderBuilderManager; @@ -197,6 +199,8 @@ describe('FinalizeOrder action', function (): void { ->withPickupTimeSlot($shop->getId(), $slot); $session = Session::driver(); + $basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer()); + $basketRepo->persist($basket); $builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session'); $builderManager->save($builder); @@ -227,14 +231,16 @@ describe('FinalizeOrder action', function (): void { ); return [ - 'customer' => $customer, - 'employee' => $employee, - 'shop' => $shop, - 'product' => $product, - 'builderManager' => $builderManager, - 'dispatcher' => $dispatcher, - 'tunnelService' => $tunnelService, - 'executor' => $executor, + 'customer' => $customer, + 'employee' => $employee, + 'shop' => $shop, + 'product' => $product, + 'basketId' => $basket->id, + 'basketRepository' => $basketRepo, + 'builderManager' => $builderManager, + 'dispatcher' => $dispatcher, + 'tunnelService' => $tunnelService, + 'executor' => $executor, ]; } @@ -242,7 +248,7 @@ describe('FinalizeOrder action', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $ctx = buildFinalizeOrderScenario(priceCents: 2000, qty: 2); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -273,7 +279,7 @@ describe('FinalizeOrder action', function (): void { ->andThrow(new RegateExportFailedException('SMTP transport failure')); $ctx = buildFinalizeOrderScenario(regateService: $failingRegate); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN & THEN expect(fn () => $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()))) @@ -289,7 +295,7 @@ describe('FinalizeOrder action', function (): void { // GIVEN // 210 EUR HT -> > 200 EUR TTC order limit $ctx = buildFinalizeOrderScenario(priceCents: 21000, qty: 1); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -324,7 +330,7 @@ describe('FinalizeOrder action', function (): void { 'pickup_day' => '2026-11-20 14:00:00', ]); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -339,7 +345,7 @@ describe('FinalizeOrder action', function (): void { /** @var \Tests\TestCase $this */ // GIVEN $ctx = buildFinalizeOrderScenario(activeEmployee: false); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -357,7 +363,7 @@ describe('FinalizeOrder action', function (): void { $ctx['product']->status = false; $ctx['product']->saveOrFail(); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -375,7 +381,7 @@ describe('FinalizeOrder action', function (): void { $ctx = buildFinalizeOrderScenario( pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'), ); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -396,7 +402,7 @@ describe('FinalizeOrder action', function (): void { ->andThrow(new LockTimeoutException('Lock timed out')); $ctx = buildFinalizeOrderScenario(lock: $lock); - $action = new FinalizeOrder($ctx['tunnelService']); + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); // WHEN $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); @@ -406,4 +412,24 @@ describe('FinalizeOrder action', function (): void { ->and($output->orderReference)->toBeNull(); $this->assertDatabaseCount('orders', 0); }); + + it('updates session basket and returns BASKET_PRICE_CHANGED when catalog price increases before finalization', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $ctx = buildFinalizeOrderScenario(priceCents: 1000, qty: 2); + $ctx['product']->price = Money::EUR(1500); + $ctx['product']->saveOrFail(); + + $action = new FinalizeOrder($ctx['tunnelService'], $ctx['basketRepository']); + + // WHEN + $output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())); + + // THEN + expect($output->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) + ->and($output->orderReference)->toBeNull() + ->and($ctx['basketRepository']->find($ctx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165'); + $this->assertDatabaseCount('orders', 0); + Mail::assertNothingSent(); + }); }); diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php index 0e51c735..cd974949 100644 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php @@ -13,14 +13,17 @@ use App\Cqs\Actions\Orders\FinalizeOrderOutput; use App\Enums\FinalizeOrderStatus; use Domain\Builders\OrderBuilderCompleted; use Domain\Enums\OrderStatus; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\RegateExportFailedException; use Domain\Exceptions\OrderTunnel\UnorderableProductException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; +use Domain\Models\Entities\Basket; use Domain\Models\Entities\Order; use Domain\Models\ValueObjects\DeliveryAddress; +use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ShopId; use Domain\Models\ValueObjects\Entities\ShopperId; @@ -31,6 +34,7 @@ use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Models\ValueObjects\ShopperEstablishmentCode; use Domain\Models\ValueObjects\ShopperServiceCode; use Domain\Models\ValueObjects\ShopperSiteCode; +use Domain\Ports\Repositories\BasketRepository; use Domain\Services\OrderTunnelService; use Money\Money; use Ramsey\Uuid\Uuid; @@ -75,7 +79,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andReturn($order); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -98,7 +102,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new ExpiredPickupTimeSlotException('Invalid or unavailable time slot')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -123,7 +127,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new InactiveShopperException('Employee account is no longer active.')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -146,7 +150,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new UnorderableProductException('One or more products in your basket are no longer available for order.')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -169,7 +173,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new OrderLimitExceededException()); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -192,7 +196,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new WeeklyLimitExceededException()); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action($input); @@ -215,7 +219,7 @@ describe('FinalizeOrder', function (): void { ->with($builder) ->andThrow(new RegateExportFailedException('SMTP transport error')); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN expect(fn () => $action($input)) @@ -226,7 +230,7 @@ describe('FinalizeOrder', function (): void { it('has Locked attribute with expected TTL and wait seconds and implements lock contracts', function (): void { // GIVEN $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); $reflection = new \ReflectionClass(FinalizeOrder::class); $attributes = $reflection->getAttributes(Locked::class); @@ -249,7 +253,7 @@ describe('FinalizeOrder', function (): void { $orderTunnelService = \Mockery::mock(OrderTunnelService::class); $orderTunnelService->shouldNotReceive('getBuilderCompletedOrFail'); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $key = $action->lockKey($input); @@ -273,7 +277,7 @@ describe('FinalizeOrder', function (): void { ->once() ->andReturn($builder); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $key = $action->lockKey($input); @@ -287,7 +291,7 @@ describe('FinalizeOrder', function (): void { $input = new FinalizeOrderInput(); $orderTunnelService = \Mockery::mock(OrderTunnelService::class); - $action = new FinalizeOrder($orderTunnelService); + $action = new FinalizeOrder($orderTunnelService, \Mockery::mock(BasketRepository::class)); // WHEN $result = $action->onLockTimeout($input); @@ -298,4 +302,33 @@ describe('FinalizeOrder', function (): void { ->and($result->orderReference)->toBeNull() ->and($result->errorMessage)->toBeNull(); }); + + it('persists refreshed basket and returns basketPriceChanged output when finalizeOrder throws BasketPriceChangedException', function (): void { + // GIVEN + $input = new FinalizeOrderInput(); + $builder = \Mockery::mock(OrderBuilderCompleted::class); + $refreshedBasket = new Basket(new BasketId(Uuid::uuid7()), []); + $orderTunnelService = \Mockery::mock(OrderTunnelService::class); + $orderTunnelService->shouldReceive('getBuilderCompletedOrFail')->once()->andReturn($builder); + $orderTunnelService->shouldReceive('finalizeOrder') + ->once() + ->with($builder) + ->andThrow(new BasketPriceChangedException($refreshedBasket)); + + $basketRepository = \Mockery::mock(BasketRepository::class); + $basketRepository->shouldReceive('persist') + ->once() + ->with($refreshedBasket); + + $action = new FinalizeOrder($orderTunnelService, $basketRepository); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeInstanceOf(FinalizeOrderOutput::class) + ->and($result->status)->toBe(FinalizeOrderStatus::BASKET_PRICE_CHANGED) + ->and($result->orderReference)->toBeNull() + ->and($result->errorMessage)->toBe('The price of one or more products in your basket has changed.'); + }); }); diff --git a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php index bbd60cf6..a1a2f3bd 100644 --- a/tests/Unit/Domain/Services/OrderTunnelServiceTest.php +++ b/tests/Unit/Domain/Services/OrderTunnelServiceTest.php @@ -12,6 +12,7 @@ use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; +use Domain\Exceptions\OrderTunnel\BasketPriceChangedException; use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException; use Domain\Exceptions\OrderTunnel\InactiveShopperException; use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; @@ -650,8 +651,8 @@ describe('OrderTunnelService', function (): void { id: $id, name: 'Updated Product Name', qty: $qty, - unitPriceHt: Money::EUR(250), - unitDiscount: Money::EUR(50), + unitPriceHt: Money::EUR(100), + unitDiscount: Money::EUR(0), taxRate: TaxRate::TVA_20, weightGrams: 200, brand: null, @@ -662,7 +663,7 @@ describe('OrderTunnelService', function (): void { description: null, weightVariable: false, discountRate: DiscountRate::fromRatio(0.0), - priceKgTtc: Money::EUR(240) + priceKgTtc: Money::EUR(120) ); }); @@ -682,6 +683,61 @@ describe('OrderTunnelService', function (): void { expect($order)->toBeInstanceOf(Order::class); }); + it('throws BasketPriceChangedException with refreshed basket when product price changes before finalization', function (): void { + // GIVEN + $builder = createTestBuilder(completed: true); + $shopperRepo = mock(ShopperRepository::class); + $shopperRepo->shouldNotReceive('getByIdOrFail'); + + $orderRepo = mock(OrderRepository::class); + $orderRepo->shouldNotReceive('persist'); + + $eventDispatcher = mock(DomainEventDispatcher::class); + $eventDispatcher->shouldNotReceive('dispatch'); + + $productRepo = mock(ProductRepository::class); + $productRepo->shouldReceive('getBasketProduct')->once()->andReturnUsing(function ($id, $qty) { + return new BasketProduct( + id: $id, + name: 'Updated Price Product', + qty: $qty, + unitPriceHt: Money::EUR(250), + unitDiscount: Money::EUR(50), + taxRate: TaxRate::TVA_20, + weightGrams: 200, + brand: null, + incoId: new IncoId(123), + orderUnit: OrderUnit::PCE, + slug: 'updated-price-product', + picture: null, + description: null, + weightVariable: false, + discountRate: DiscountRate::fromRatio(0.2), + priceKgTtc: Money::EUR(240) + ); + }); + + $service = createOrderTunnelService( + productRepository: $productRepo, + shopperRepository: $shopperRepo, + orderRepository: $orderRepo, + eventDispatcher: $eventDispatcher + ); + + // WHEN + $caught = null; + + try { + $service->finalizeOrder($builder); + } catch (BasketPriceChangedException $e) { + $caught = $e; + } + + // THEN + expect($caught)->toBeInstanceOf(BasketPriceChangedException::class) + ->and($caught?->refreshedBasket->totalTaxIncluded()->getAmount())->toBe('240'); + }); + it('throws ExpiredPickupTimeSlotException when finalizing order with an expired or unavailable pickup time slot', function (): void { // GIVEN $basket = createTestBasket(1);