435 lines
18 KiB
PHP
435 lines
18 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Cqs\Actions\Orders\FinalizeOrder;
|
|
use App\Cqs\Actions\Orders\FinalizeOrderInput;
|
|
use App\Cqs\Actions\Orders\FinalizeOrderOutput;
|
|
use App\Enums\FinalizeOrderStatus;
|
|
use App\Mail\OrderConfirmAdminMail;
|
|
use App\Mail\RegateOrderMail;
|
|
use App\Models\Customer;
|
|
use App\Models\Employee;
|
|
use App\Models\Order;
|
|
use App\Models\Product;
|
|
use App\Models\ProductInco;
|
|
use App\Models\Range;
|
|
use App\Models\Shop;
|
|
use App\Notifications\OrderConfirmed;
|
|
use App\Services\ActionExecutorService;
|
|
use App\Services\MailRegateService;
|
|
use Carbon\CarbonImmutable;
|
|
use Domain\Builders\OrderBuilder;
|
|
use Domain\Enums\OrderStatus;
|
|
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\ValueObjects\BasketProduct;
|
|
use Domain\Models\ValueObjects\Code;
|
|
use Domain\Models\ValueObjects\DeliveryAddress;
|
|
use Domain\Models\ValueObjects\DiscountRate;
|
|
use Domain\Models\ValueObjects\Email;
|
|
use Domain\Models\ValueObjects\Entities\BasketId;
|
|
use Domain\Models\ValueObjects\IncoId;
|
|
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\Policies\CustomerOrderLimitPolicy;
|
|
use Domain\Ports\Services\RegateService;
|
|
use Domain\Services\OrderService;
|
|
use Domain\Services\OrderTunnelService;
|
|
use Domain\Services\PickupSchedulingService;
|
|
use Domain\Services\ShopperService;
|
|
use Illuminate\Cache\ArrayStore;
|
|
use Illuminate\Cache\Repository;
|
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
|
use Illuminate\Support\Facades\Config;
|
|
use Illuminate\Support\Facades\Date;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Facades\Notification;
|
|
use Illuminate\Support\Facades\Session;
|
|
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
|
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
|
use Infrastructure\Adapters\Repositories\EloquentOrderRepository;
|
|
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;
|
|
use Money\Currency;
|
|
use Money\Money;
|
|
use Psr\Log\NullLogger;
|
|
use Ramsey\Uuid\Uuid;
|
|
use Shared\Concurrency\Lock;
|
|
use Shared\Concurrency\LockTimeoutException;
|
|
use Shared\ValueObjects\CrmHashcode;
|
|
|
|
uses(RefreshDatabase::class);
|
|
|
|
describe('FinalizeOrder action', function (): void {
|
|
beforeEach(function (): void {
|
|
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
|
|
CarbonImmutable::setTestNow($now);
|
|
Date::setTestNow($now);
|
|
|
|
Config::set('mail.to.regate', 'regate@test.local');
|
|
Config::set('mail.to.contact', 'contact@test.local');
|
|
Mail::fake();
|
|
Notification::fake();
|
|
});
|
|
|
|
afterEach(function (): void {
|
|
CarbonImmutable::setTestNow();
|
|
Date::setTestNow();
|
|
});
|
|
|
|
/**
|
|
* @return array{
|
|
* customer: Customer,
|
|
* employee: Employee,
|
|
* shop: Shop,
|
|
* product: Product,
|
|
* builderManager: SessionOrderBuilderManager,
|
|
* dispatcher: LaravelDomainEventDispatcher,
|
|
* tunnelService: OrderTunnelService,
|
|
* executor: ActionExecutorService,
|
|
* }
|
|
*/
|
|
function buildFinalizeOrderScenario(
|
|
int $priceCents = 2500,
|
|
int $qty = 2,
|
|
bool $activeEmployee = true,
|
|
?RegateService $regateService = null,
|
|
?Lock $lock = null,
|
|
?CarbonImmutable $pickupAt = null,
|
|
): array {
|
|
$shop = Shop::factory()->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();
|
|
$basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer());
|
|
$basketRepo->persist($basket);
|
|
$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,
|
|
'basketId' => $basket->id,
|
|
'basketRepository' => $basketRepo,
|
|
'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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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'], $ctx['basketRepository']);
|
|
|
|
// 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);
|
|
});
|
|
|
|
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();
|
|
});
|
|
});
|