ldc-cocotte/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php

1737 lines
67 KiB
PHP
Raw Normal View History

2026-06-14 21:32:07 +02:00
<?php
declare(strict_types=1);
namespace Tests\Feature\App\Http\Controllers\Fo;
use App\Contracts\Executor;
use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrder;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderInput;
use App\Cqs\Actions\Orders\ConfirmPlacedOrderOutput;
use App\Cqs\Actions\Orders\ExportOrderToRegate;
use App\Cqs\Actions\Orders\ExportOrderToRegateInput;
use App\Cqs\Actions\Orders\ExportOrderToRegateOutput;
use App\Cqs\Actions\Orders\FailPendingOrder;
use App\Cqs\Actions\Orders\FailPendingOrderInput;
use App\Cqs\Actions\Orders\FailPendingOrderOutput;
use App\Cqs\Actions\Orders\PlacePendingOrder;
use App\Cqs\Actions\Orders\PlacePendingOrderInput;
use App\Cqs\Actions\Orders\PlacePendingOrderOutput;
use App\Cqs\Queries\Orders\GetBasketSummaryQueryOutput;
use App\Cqs\Queries\Orders\GetOrderConfirmationQueryOutput;
use App\Cqs\Queries\Orders\GetPickTimeSlotQueryOutput;
use App\Dto\ShopDto;
use App\Http\Middleware\CustomerIsEmployed;
use App\Http\Middleware\EnsureCustomerEmailIsVerified;
use App\Mail\OrderConfirmAdminMail;
use App\Mail\RegateOrderMail;
use App\Models\Customer;
use App\Models\Employee;
use App\Models\Order;
use App\Models\OrderTunnelAttempt;
2026-06-14 21:32:07 +02:00
use App\Models\Page;
use App\Models\Product;
use App\Models\ProductInco;
use App\Models\Range;
use App\Models\Shop;
use App\Notifications\OrderConfirmed;
use App\Services\CrmService;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
2026-06-14 21:32:07 +02:00
use Database\Seeders\ContentSeeder;
use Domain\Builders\OrderBuilder;
use Domain\Builders\OrderBuilderCompleted;
use Domain\Builders\OrderBuilderWithBasket;
use Domain\Enums\Country;
use Domain\Enums\OrderStatus;
use Domain\Enums\OrderTunnelStep;
use Domain\Enums\ProductBrand;
use Domain\Enums\SellUnit;
use Domain\Enums\TaxRate;
use Domain\Enums\Units\InvoicingUnit;
use Domain\Enums\Units\OrderUnit;
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
use Domain\Models\Entities\Basket;
use Domain\Models\Entities\Shopper;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\CrmCustomer;
use Domain\Models\ValueObjects\DeliveryAddress;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Entities\BasketId;
use Domain\Models\ValueObjects\Entities\OrderId;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\OrderEmployee;
use Domain\Models\ValueObjects\OrderReference;
use Domain\Models\ValueObjects\PickupTimeSlot;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Domain\Ports\Repositories\ShopperRepository;
use Domain\Ports\Services\OrderBuilderSessionManager;
use Domain\Ports\Services\RegateService;
use Domain\Services\BasketService;
use Domain\Services\OrderTunnelService;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
2026-06-14 21:32:07 +02:00
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
2026-06-14 21:32:07 +02:00
use Illuminate\Support\Facades\View;
use Mockery\MockInterface;
use Money\Money;
use Sentry\State\HubInterface;
use Shared\Helpers\UuidHelper;
use Shared\ValueObjects\CrmHashcode;
2026-06-14 21:32:07 +02:00
describe('TunnelController', function (): void {
it('redirects unauthenticated guest accessing basket summary to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->get('/commande/panier');
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest submitting basket summary to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->post('/commande/panier', []);
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest accessing pick time slot to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->get('/commande/creneaux');
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest submitting pick time slot to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->post('/commande/creneaux', []);
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest accessing confirmation to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->get('/commande/confirmation');
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest submitting confirmation to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->post('/commande/confirmation', []);
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('redirects unauthenticated guest accessing confirmed order to login', function (): void {
/** @var \Tests\TestCase $this */
2026-06-14 21:32:07 +02:00
// GIVEN
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
// WHEN
$response = $this->get('/commande/confirmation/1');
2026-06-14 21:32:07 +02:00
// THEN
$response->assertRedirectToRoute('fo.auth.connexion');
2026-06-14 21:32:07 +02:00
});
it('displays basket summary when customer is authorized', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$basket = new Basket(new BasketId(UuidHelper::v7()));
$this->mock(Executor::class, function (MockInterface $mock) use ($basket): void {
$mock->shouldReceive('execute')
->once()
->andReturn(new GetBasketSummaryQueryOutput(
step: OrderTunnelStep::REVIEW,
basket: $basket,
));
});
// WHEN
$response = $this->get('/commande/panier');
// THEN
$response->assertOk()
->assertViewIs('fo.tunnel.basket-summary')
->assertViewHas('step', OrderTunnelStep::REVIEW)
->assertViewHas('basket', $basket);
});
it('submits basket summary and redirects to pick time slot', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once();
});
// WHEN
$response = $this->post('/commande/panier', []);
// THEN
$response->assertRedirectToRoute('fo.sales.pick-time-slot');
});
it('displays pick time slot when customer is authorized', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$shopDto = new ShopDto(
id: 'test-shop',
name: 'Test Shop',
address: '1 rue Test',
postcode: '75001',
city: 'Paris',
phone: null,
latitude: null,
longitude: null,
default: true,
);
$this->mock(Executor::class, function (MockInterface $mock) use ($shopDto): void {
$mock->shouldReceive('execute')
->once()
->andReturn(new GetPickTimeSlotQueryOutput(
step: OrderTunnelStep::BOOKING,
shop: $shopDto,
timeSlots: [],
mapUrl: 'https://maps.example.com',
));
});
// WHEN
$response = $this->get('/commande/creneaux');
// THEN
$response->assertOk()
->assertViewIs('fo.tunnel.pick-time-slot')
->assertViewHas('step', OrderTunnelStep::BOOKING)
->assertViewHas('shop', $shopDto)
->assertViewHas('mapUrl', 'https://maps.example.com');
});
it('submits pick time slot and redirects to confirmation when slot is valid', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$shopper = new Shopper(
id: $customer->getId(),
email: new Email('test@example.com'),
matricule: new Matricule('1234567'),
nom: 'Dupont',
prenom: 'Jean',
startDate: now()->subMonth(),
endDate: null,
etablissement: new ShopperEstablishmentCode('FAC01'),
site: new ShopperSiteCode('SITE'),
service: new ShopperServiceCode('101'),
);
$this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void {
$mock->shouldReceive('getByIdOrFail')->andReturn($shopper);
});
$basket = new Basket(new BasketId(UuidHelper::v7()));
$builder = \Mockery::mock(OrderBuilderWithBasket::class);
$builder->shouldReceive('getBasket')->andReturn($basket);
$this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void {
$mock->shouldReceive('getBuilderFromBasketOrFail')->andReturn($builder);
$mock->shouldReceive('assertBasketWeeklyAmountWithinLimitFor');
});
$slot = new PickupTimeSlot(now(), new \DateInterval('PT1H'));
$this->mock(Executor::class, function (MockInterface $mock) use ($slot): void {
$mock->shouldReceive('execute')
->once()
->andReturn(ApplyPickTimeSlotOutput::matched($slot));
});
// WHEN
$response = $this->post('/commande/creneaux', [
'timeslot' => now()->format('Y-m-d'),
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation');
});
it('submits pick time slot and redirects back with error when slot is invalid', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$shopper = new Shopper(
id: $customer->getId(),
email: new Email('test@example.com'),
matricule: new Matricule('1234567'),
nom: 'Dupont',
prenom: 'Jean',
startDate: now()->subMonth(),
endDate: null,
etablissement: new ShopperEstablishmentCode('FAC01'),
site: new ShopperSiteCode('SITE'),
service: new ShopperServiceCode('101'),
);
$this->mock(ShopperRepository::class, function (MockInterface $mock) use ($shopper): void {
$mock->shouldReceive('getByIdOrFail')->andReturn($shopper);
});
$basket = new Basket(new BasketId(UuidHelper::v7()));
$builder = \Mockery::mock(OrderBuilderWithBasket::class);
$builder->shouldReceive('getBasket')->andReturn($basket);
$this->mock(OrderTunnelService::class, function (MockInterface $mock) use ($builder): void {
$mock->shouldReceive('getBuilderFromBasketOrFail')->andReturn($builder);
$mock->shouldReceive('assertBasketWeeklyAmountWithinLimitFor');
});
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(ApplyPickTimeSlotOutput::unavailable());
});
// WHEN
$response = $this->from('/commande/creneaux')->post('/commande/creneaux', [
'timeslot' => now()->format('Y-m-d'),
]);
// THEN
$response->assertRedirect('/commande/creneaux')
->assertSessionHasErrors('timeslot');
});
it('displays order confirmation when customer is authorized', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$basket = new Basket(new BasketId(UuidHelper::v7()));
$builder = \Mockery::mock(OrderBuilderCompleted::class);
$slot = new PickupTimeSlot(now(), new \DateInterval('PT1H'));
$builder->shouldReceive('getPickupTimeSlot')->andReturn($slot);
$shopDto = new ShopDto(
id: 'test-shop',
name: 'Test Shop',
address: '1 rue Test',
postcode: '75001',
city: 'Paris',
phone: null,
latitude: null,
longitude: null,
default: true,
);
$this->mock(Executor::class, function (MockInterface $mock) use ($basket, $builder, $shopDto): void {
$mock->shouldReceive('execute')
->once()
->andReturn(new GetOrderConfirmationQueryOutput(
step: OrderTunnelStep::CONFIRMATION,
basket: $basket,
builder: $builder,
shop: $shopDto,
));
});
// WHEN
$response = $this->get('/commande/confirmation');
// THEN
$response->assertOk()
->assertViewIs('fo.tunnel.confirmation')
->assertViewHas('step', OrderTunnelStep::CONFIRMATION)
->assertViewHas('basket', $basket)
->assertViewHas('shop', $shopDto);
});
it('submits confirmation and redirects to confirmed view when cgv accepted', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$orderId = new OrderId(UuidHelper::v7());
$orderReference = new OrderReference(UuidHelper::v7());
$this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::SENT);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class))
->andReturn(ConfirmPlacedOrderOutput::CONFIRMED);
});
// WHEN
$response = $this->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', (string) $orderReference);
});
it('cancels pending order and redirects back cleanly when Regate export fails 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('regate-export-fail@example.com');
$customer->hashcode = new CrmHashcode(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$orderId = new OrderId(UuidHelper::v7());
$orderReference = new OrderReference(UuidHelper::v7());
$this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::FAILED);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(FailPendingOrder::class), \Mockery::type(FailPendingOrderInput::class))
->andReturn(FailPendingOrderOutput::FAILED);
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
});
it('redirects to confirmation with error when ConfirmPlacedOrder fails after Regate export', 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('confirm-sql-fail@example.com');
$customer->hashcode = new CrmHashcode(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$orderId = new OrderId(UuidHelper::v7());
$orderReference = new OrderReference(UuidHelper::v7());
$this->mock(Executor::class, function (MockInterface $mock) use ($orderId, $orderReference): void {
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(PlacePendingOrder::class), \Mockery::type(PlacePendingOrderInput::class))
->andReturn(PlacePendingOrderOutput::pendingCreated($orderId, $orderReference));
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ExportOrderToRegate::class), \Mockery::type(ExportOrderToRegateInput::class))
->andReturn(ExportOrderToRegateOutput::SENT);
$mock->shouldReceive('execute')
->once()
->with(\Mockery::type(ConfirmPlacedOrder::class), \Mockery::type(ConfirmPlacedOrderInput::class))
->andReturn(ConfirmPlacedOrderOutput::FAILED);
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
});
it('redirects back with message when limit exception 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::weeklyLimitExceeded(
'The total amount for this delivery date has been exceeded. Please modify it to validate.'
));
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirect('/commande/confirmation')
->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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::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('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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::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
$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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::lockTimeout());
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirect('/commande/confirmation')
->assertSessionHas('message', __('Your order is already being processed. Please wait a moment and try again.'));
});
it('logs out and redirects home with blocked message when inactiveShopper output 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-inactive@example.com');
$customer->hashcode = new CrmHashcode(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andReturn(PlacePendingOrderOutput::inactiveShopper('Employee account is no longer active.'));
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.pages.home')
->assertSessionHasErrors();
expect(auth('frontend')->check())->toBeFalse();
});
it('displays confirmed order view when customer is authorized', 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(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$shop = new Shop();
$shop->name = 'Boutique Test';
$shop->address = '1 rue Test';
$shop->postcode = '75001';
$shop->city = 'Paris';
$shop->default = true;
$shop->save();
$orderReference = new OrderReference(UuidHelper::v7());
$order = new Order();
$order->reference = $orderReference;
$order->total = Money::EUR(3000);
$order->status = OrderStatus::VALIDATED;
$order->pickup_day = now()->addDays(2);
$order->shop_id = $shop->id;
$order->employee = new OrderEmployee(
firstname: 'Jean',
lastname: 'Dupont',
matricule: new Matricule('1234567'),
facility: new ShopperEstablishmentCode('FAC01'),
site: new ShopperSiteCode('SITE'),
service: new ShopperServiceCode('101'),
);
$order->delivery_address = new DeliveryAddress(
name: $shop->name,
address: $shop->address,
postcode: $shop->postcode,
city: $shop->city,
);
$order->save();
// WHEN
$response = $this->get('/commande/confirmation/' . (string) $orderReference);
// THEN
$response->assertOk()
->assertViewIs('fo.tunnel.confirmed')
->assertViewHas('step', OrderTunnelStep::CONFIRMATION)
->assertViewHas('order')
->assertViewHas('shop')
->assertViewHas('mapUrl');
});
it('reports RegateExportFailedException to Sentry and redirects cleanly to confirmation instead of 500', 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('regate-fail@example.com');
$customer->hashcode = new CrmHashcode(UuidHelper::v4());
$customer->save();
$this->actingAs($customer, 'frontend');
$this->withoutMiddleware([
CustomerIsEmployed::class,
EnsureCustomerEmailIsVerified::class,
]);
Gate::before(fn () => true);
$sentryHub = \Mockery::mock(HubInterface::class);
$sentryHub->shouldReceive('captureException')
->once()
->with(\Mockery::type(RegateExportFailedException::class));
$this->app->instance(HubInterface::class, $sentryHub);
$this->mock(Executor::class, function (MockInterface $mock): void {
$mock->shouldReceive('execute')
->once()
->andThrow(new RegateExportFailedException('SMTP transport down'));
});
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
});
it('finalizes order end-to-end without mocking Executor on POST /commande/confirmation', function (): void {
/** @var \Tests\TestCase $this */
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
try {
// GIVEN
Config::set('mail.to.regate', 'regate@test.local');
Config::set('mail.to.contact', 'contact@test.local');
Mail::fake();
Notification::fake();
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$hashcode = new CrmHashcode(UuidHelper::v4());
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'email' => new Email('e2e-success@example.com'),
'hashcode' => $hashcode,
]);
$crmCustomer = new CrmCustomer(
hashcode: $hashcode->value,
email: 'e2e-success@example.com',
password: 'hashed-password',
firstname: 'Jean',
lastname: 'Dupont',
birthDate: null,
phone: null,
address: null,
address2: null,
city: null,
postcode: null,
country: Country::france,
optIn: false,
status: true,
lastConnection: null,
);
$crmService = $this->mock(CrmService::class);
$crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer);
$employee = new Employee();
$employee->matricule = new Matricule('7654321');
$employee->code = new Code('ABCDEFG');
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = null;
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé E2E';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme E2E';
$range->status = true;
$range->order = 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet E2E';
$product->brand = ProductBrand::loue;
$product->description = 'Description E2E';
$product->short_description = 'Court E2E';
$product->price = Money::EUR(1500);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$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 = 889901;
$inco->saveOrFail();
$this->actingAs($customer, 'frontend');
/** @var BasketService $basketService */
$basketService = $this->app->make(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), 2);
$basket = $basketService->getBasket();
$slot = new PickupTimeSlot(
CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'),
new \DateInterval('PT2H'),
);
$builder = OrderBuilder::fromBasket($basket, $customer->getId())
->withPickupTimeSlot($shop->getId(), $slot);
$this->app->make(OrderBuilderSessionManager::class)->save($builder);
// WHEN
$response = $this->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$order = Order::query()->where('employee_matricule', '7654321')->first();
expect($order)->not->toBeNull()
->and($order?->status)->toBe(OrderStatus::VALIDATED)
->and($basketService->hasItems())->toBeFalse();
$response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', (string) $order?->reference);
Mail::assertSent(RegateOrderMail::class);
Mail::assertQueued(OrderConfirmAdminMail::class);
Notification::assertSentTo($employee, OrderConfirmed::class);
} finally {
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
}
});
it('marks pending order as FAILED end-to-end without mocking Executor when Regate export fails', function (): void {
/** @var \Tests\TestCase $this */
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
try {
// GIVEN
Mail::fake();
Notification::fake();
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$hashcode = new CrmHashcode(UuidHelper::v4());
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'email' => new Email('e2e-fail@example.com'),
'hashcode' => $hashcode,
]);
$crmCustomer = new CrmCustomer(
hashcode: $hashcode->value,
email: 'e2e-fail@example.com',
password: 'hashed-password',
firstname: 'Jean',
lastname: 'Dupont',
birthDate: null,
phone: null,
address: null,
address2: null,
city: null,
postcode: null,
country: Country::france,
optIn: false,
status: true,
lastConnection: null,
);
$crmService = $this->mock(CrmService::class);
$crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer);
$employee = new Employee();
$employee->matricule = new Matricule('7654322');
$employee->code = new Code('ABCDEFH');
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = null;
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé E2E Fail';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme E2E Fail';
$range->status = true;
$range->order = 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet E2E Fail';
$product->brand = ProductBrand::loue;
$product->description = 'Description E2E Fail';
$product->short_description = 'Court E2E Fail';
$product->price = Money::EUR(1500);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$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 = 889902;
$inco->saveOrFail();
$sentryHub = \Mockery::mock(HubInterface::class);
$sentryHub->shouldReceive('captureException')
->once()
->with(\Mockery::type(RegateExportFailedException::class));
$this->app->instance(HubInterface::class, $sentryHub);
$regateService = \Mockery::mock(RegateService::class);
$regateService->shouldReceive('processOrder')
->once()
->andThrow(new RegateExportFailedException('SMTP transport down'));
$this->app->instance(RegateService::class, $regateService);
$this->actingAs($customer, 'frontend');
/** @var BasketService $basketService */
$basketService = $this->app->make(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), 2);
$basket = $basketService->getBasket();
$slot = new PickupTimeSlot(
CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'),
new \DateInterval('PT2H'),
);
$builder = OrderBuilder::fromBasket($basket, $customer->getId())
->withPickupTimeSlot($shop->getId(), $slot);
$this->app->make(OrderBuilderSessionManager::class)->save($builder);
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$order = Order::query()->where('employee_matricule', '7654322')->first();
expect($order)->not->toBeNull()
->and($order?->status)->toBe(OrderStatus::FAILED)
->and($basketService->hasItems())->toBeTrue();
$response->assertRedirectToRoute('fo.sales.confirmation')
->assertSessionHas('message', __('An error occurred while validating your order. Please try again later.'));
Notification::assertNothingSent();
} finally {
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
}
});
it('rejects concurrent confirmation immediately when shopper checkout lock is already held', function (): void {
/** @var \Tests\TestCase $this */
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
$heldLock = null;
try {
// GIVEN
Mail::fake();
Notification::fake();
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$hashcode = new CrmHashcode(UuidHelper::v4());
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'email' => new Email('e2e-lock@example.com'),
'hashcode' => $hashcode,
]);
$crmCustomer = new CrmCustomer(
hashcode: $hashcode->value,
email: 'e2e-lock@example.com',
password: 'hashed-password',
firstname: 'Jean',
lastname: 'Dupont',
birthDate: null,
phone: null,
address: null,
address2: null,
city: null,
postcode: null,
country: Country::france,
optIn: false,
status: true,
lastConnection: null,
);
$crmService = $this->mock(CrmService::class);
$crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer);
$employee = new Employee();
$employee->matricule = new Matricule('7654323');
$employee->code = new Code('ABCDEFJ');
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = null;
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé Lock';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme Lock';
$range->status = true;
$range->order = 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet Lock';
$product->brand = ProductBrand::loue;
$product->description = 'Description Lock';
$product->short_description = 'Court Lock';
$product->price = Money::EUR(1500);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$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 = 889903;
$inco->saveOrFail();
$this->actingAs($customer, 'frontend');
/** @var BasketService $basketService */
$basketService = $this->app->make(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), 2);
$basket = $basketService->getBasket();
$slot = new PickupTimeSlot(
CarbonImmutable::parse('2026-11-20 14:00:00', 'Europe/Paris'),
new \DateInterval('PT2H'),
);
$builder = OrderBuilder::fromBasket($basket, $customer->getId())
->withPickupTimeSlot($shop->getId(), $slot);
$this->app->make(OrderBuilderSessionManager::class)->save($builder);
$store = $this->app->make(CacheRepository::class)->getStore();
assert($store instanceof LockProvider);
$heldLock = $store->lock("order:checkout:shopper:{$customer->id}", 60);
expect($heldLock->get())->toBeTrue();
// WHEN
$response = $this->from('/commande/confirmation')->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN
$response->assertRedirect('/commande/confirmation')
->assertSessionHas('message', __('Your order is already being processed. Please wait a moment and try again.'));
expect(Order::query()->count())->toBe(0);
Mail::assertNothingSent();
} finally {
$heldLock?->release();
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
}
});
it('tracks unconverted tunnel attempts from step 1 and marks them converted upon step 3 confirmation', function (): void {
/** @var \Tests\TestCase $this */
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
try {
// GIVEN
Mail::fake();
Notification::fake();
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$hashcode = new CrmHashcode(UuidHelper::v4());
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'email' => new Email('e2e-attempt@example.com'),
'hashcode' => $hashcode,
]);
$crmCustomer = new CrmCustomer(
hashcode: $hashcode->value,
email: 'e2e-attempt@example.com',
password: 'hashed-password',
firstname: 'Jean',
lastname: 'Dupont',
birthDate: null,
phone: null,
address: null,
address2: null,
city: null,
postcode: null,
country: Country::france,
optIn: false,
status: true,
lastConnection: null,
);
$crmService = $this->mock(CrmService::class);
$crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer);
$employee = new Employee();
$employee->matricule = new Matricule('7654324');
$employee->code = new Code('ABCDEFK');
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = null;
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé Attempt';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme Attempt';
$range->status = true;
$range->order = 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet Attempt';
$product->brand = ProductBrand::loue;
$product->description = 'Description Attempt';
$product->short_description = 'Court Attempt';
$product->price = Money::EUR(1500);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$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 = 889904;
$inco->saveOrFail();
$this->actingAs($customer, 'frontend');
/** @var BasketService $basketService */
$basketService = $this->app->make(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), 2);
// WHEN: Step 1 submitted twice before completing checkout
$step1First = $this->post('/commande/panier', []);
$step1Second = $this->post('/commande/panier', []);
// THEN: single unconverted attempt recorded
$step1First->assertRedirectToRoute('fo.sales.pick-time-slot');
$step1Second->assertRedirectToRoute('fo.sales.pick-time-slot');
expect(OrderTunnelAttempt::query()->whereNull('converted_at')->count())->toBe(1);
// WHEN: Step 2 & Step 3 submitted
$this->post('/commande/creneaux', [
'timeslot' => '2026-11-20',
])->assertRedirectToRoute('fo.sales.confirmation');
$step3Response = $this->post('/commande/confirmation', [
'ok_cgv' => '1',
]);
// THEN: same attempt is now marked converted and linked to the validated order
$order = Order::query()->where('employee_matricule', '7654324')->firstOrFail();
$step3Response->assertRedirectToRoute('fo.sales.confirmation.show-confirmed', [
'order' => (string) $order->reference,
]);
$attempt = OrderTunnelAttempt::query()->firstOrFail();
expect(OrderTunnelAttempt::query()->count())->toBe(1)
->and($attempt->order_id)->toBe($order->id)
->and($attempt->converted_at)->not->toBeNull();
} finally {
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
}
});
it('keeps tunnel attempt unconverted when regate export fails on step 3', function (): void {
/** @var \Tests\TestCase $this */
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
Date::setTestNow($now);
CarbonImmutable::setTestNow($now);
Carbon::setTestNow($now);
try {
// GIVEN
Mail::fake();
Notification::fake();
$this->seed(ContentSeeder::class);
View::share('PageList', Page::getCached()
->mapWithKeys(fn ($page) => [
$page->slug->value() => $page,
]));
Cache::flush();
$hashcode = new CrmHashcode(UuidHelper::v4());
/** @var Customer $customer */
$customer = Customer::query()->forceCreate([
'id' => UuidHelper::v7()->toString(),
'email' => new Email('e2e-attempt-ko@example.com'),
'hashcode' => $hashcode,
]);
$crmCustomer = new CrmCustomer(
hashcode: $hashcode->value,
email: 'e2e-attempt-ko@example.com',
password: 'hashed-password',
firstname: 'Jean',
lastname: 'Dupont',
birthDate: null,
phone: null,
address: null,
address2: null,
city: null,
postcode: null,
country: Country::france,
optIn: false,
status: true,
lastConnection: null,
);
$crmService = $this->mock(CrmService::class);
$crmService->shouldReceive('getCustomerFromHashCode')->andReturn($crmCustomer);
$regateService = $this->mock(RegateService::class);
$regateService->shouldReceive('processOrder')
->once()
->andThrow(new RegateExportFailedException('SMTP unreachable'));
$employee = new Employee();
$employee->matricule = new Matricule('7654325');
$employee->code = new Code('ABCDEFM');
$employee->nom = 'Dupont';
$employee->prenom = 'Jean';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITEA');
$employee->service = new ShopperServiceCode('101');
$employee->start_date = Date::now()->subMonth();
$employee->end_date = null;
$employee->customer()->associate($customer);
$employee->saveOrFail();
$shop = new Shop();
$shop->name = 'Boutique Sablé Attempt KO';
$shop->address = '10 rue Test';
$shop->postcode = '72300';
$shop->city = 'Sablé';
$shop->default = true;
$shop->saveOrFail();
$range = new Range();
$range->name = 'Gamme Attempt KO';
$range->status = true;
$range->order = 1;
$range->picture_alt = 'alt';
$range->picture_title = 'title';
$range->saveOrFail();
$product = new Product();
$product->name = 'Poulet Attempt KO';
$product->brand = ProductBrand::loue;
$product->description = 'Description Attempt KO';
$product->short_description = 'Court Attempt KO';
$product->price = Money::EUR(1500);
$product->invoicing_unit = InvoicingUnit::PCE;
$product->tax_rate = TaxRate::TVA_5_5;
$product->stock = 50;
$product->weight = 1000;
$product->sell_unit = SellUnit::PCE;
$product->order_unit = OrderUnit::PCE;
$product->range_id = $range->id;
$product->status = true;
$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 = 889905;
$inco->saveOrFail();
$this->actingAs($customer, 'frontend');
/** @var BasketService $basketService */
$basketService = $this->app->make(BasketService::class);
$basketService->empty();
$basketService->add($product->getId(), 2);
// WHEN: Step 1 -> Step 2 -> failing Step 3
$this->post('/commande/panier', [])
->assertRedirectToRoute('fo.sales.pick-time-slot');
$this->post('/commande/creneaux', [
'timeslot' => '2026-11-20',
])->assertRedirectToRoute('fo.sales.confirmation');
$this->post('/commande/confirmation', ['ok_cgv' => '1'])
->assertRedirectToRoute('fo.sales.confirmation');
// THEN: order is FAILED, basket remains intact, and attempt stays unconverted
$order = Order::query()->where('employee_matricule', '7654325')->firstOrFail();
$attempt = OrderTunnelAttempt::query()->firstOrFail();
expect($order->status)->toBe(OrderStatus::FAILED)
->and($attempt->order_id)->toBeNull()
->and($attempt->converted_at)->toBeNull()
->and($basketService->hasItems())->toBeTrue();
} finally {
Date::setTestNow();
CarbonImmutable::setTestNow();
Carbon::setTestNow();
}
});
2026-06-14 21:32:07 +02:00
});