520 lines
23 KiB
PHP
520 lines
23 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Tests\Integration\WithApp\App\Cqs\Actions\Orders;
|
|
|
|
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\Enums\PlacePendingOrderStatus;
|
|
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\ValueObjects\Code;
|
|
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\Policies\CustomerOrderLimitPolicy;
|
|
use Domain\Ports\Repositories\BasketRepository;
|
|
use Domain\Ports\Services\RegateService;
|
|
use Domain\Services\BasketService;
|
|
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\Support\Facades\Config;
|
|
use Illuminate\Support\Facades\Date;
|
|
use Illuminate\Support\Facades\DB;
|
|
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\AppSessionService;
|
|
use Infrastructure\Adapters\Services\CsvGeneratorImpl;
|
|
use Infrastructure\Adapters\Services\DatabaseTunnelAttemptTrackerService;
|
|
use Infrastructure\Adapters\Services\EloquentEmployeeStatisticsService;
|
|
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
|
use Money\Currency;
|
|
use Money\Money;
|
|
use Psr\Log\NullLogger;
|
|
use Shared\Concurrency\Lock;
|
|
use Shared\Concurrency\LockTimeoutException;
|
|
use Shared\Helpers\UuidHelper;
|
|
use Shared\ValueObjects\CrmHashcode;
|
|
|
|
describe('Order placement two-step CQS actions', 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,
|
|
* basketId: BasketId,
|
|
* basketRepository: BasketRepository,
|
|
* builderManager: SessionOrderBuilderManager,
|
|
* dispatcher: LaravelDomainEventDispatcher,
|
|
* tunnelService: OrderTunnelService,
|
|
* executor: ActionExecutorService,
|
|
* }
|
|
*/
|
|
function buildOrderPlacementScenario(
|
|
int $priceCents = 2000,
|
|
int $qty = 2,
|
|
bool $activeEmployee = true,
|
|
?CarbonImmutable $pickupAt = null,
|
|
?RegateService $regateService = null,
|
|
?Lock $lock = null,
|
|
): array {
|
|
/** @var Customer $customer */
|
|
$customer = Customer::query()->forceCreate([
|
|
'id' => UuidHelper::v7()->toString(),
|
|
'email' => new Email('buyer-' . uniqid() . '@example.com'),
|
|
'hashcode' => new CrmHashcode(UuidHelper::v4()),
|
|
]);
|
|
|
|
/** @var int $sequence */
|
|
static $sequence = 0;
|
|
$sequence++;
|
|
$chars = Code::ALLOWED_CHARACTERS;
|
|
$uniqueCode = 'ABCDE' . $chars[$sequence % strlen($chars)] . $chars[(intdiv($sequence, strlen($chars))) % strlen($chars)];
|
|
|
|
$employee = new Employee();
|
|
$employee->matricule = new Matricule((string) random_int(1000000, 9999999));
|
|
$employee->code = new Code($uniqueCode);
|
|
$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 = $activeEmployee ? null : Date::now()->subDay();
|
|
$employee->customer()->associate($customer);
|
|
$employee->saveOrFail();
|
|
|
|
$shop = new Shop();
|
|
$shop->name = 'Boutique Sablé';
|
|
$shop->address = '10 rue Test';
|
|
$shop->postcode = '72300';
|
|
$shop->city = 'Sablé';
|
|
$shop->default = true;
|
|
$shop->saveOrFail();
|
|
|
|
$range = new Range();
|
|
$range->name = 'Gamme Test ' . uniqid();
|
|
$range->status = true;
|
|
$range->order = random_int(1, 99999);
|
|
$range->picture_alt = 'alt';
|
|
$range->picture_title = 'title';
|
|
$range->saveOrFail();
|
|
|
|
$product = new Product();
|
|
$product->name = 'Poulet Test ' . uniqid();
|
|
$product->brand = ProductBrand::loue;
|
|
$product->description = 'Description complète de test';
|
|
$product->short_description = 'Court';
|
|
$product->price = Money::EUR($priceCents);
|
|
$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 = 778800 + $sequence;
|
|
$inco->saveOrFail();
|
|
|
|
/** @var \Illuminate\Contracts\Session\Session $session */
|
|
$session = Session::driver();
|
|
$basketRepo = new SessionBasketRepository($session, 'basket_', new BasketSerializer());
|
|
$dispatcher = new LaravelDomainEventDispatcher();
|
|
$basketService = new BasketService(
|
|
$basketRepo,
|
|
new EloquentProductRepository(),
|
|
new AppSessionService('domain_session_uuid'),
|
|
$dispatcher,
|
|
);
|
|
$basketService->empty();
|
|
$basketService->add($product->getId(), $qty);
|
|
$basket = $basketService->getBasket();
|
|
|
|
$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);
|
|
|
|
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
|
$builderManager->save($builder);
|
|
|
|
$shopRepo = new EloquentShopRepository();
|
|
$shopperRepo = new EloquentShopperRepository();
|
|
$orderRepo = new EloquentOrderRepository();
|
|
/** @var \Illuminate\Contracts\Mail\Mailer $mailer */
|
|
$mailer = Mail::getFacadeRoot();
|
|
|
|
$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(), $mailer),
|
|
new DatabaseTunnelAttemptTrackerService($session, 'order_tunnel_attempt_id'),
|
|
);
|
|
|
|
$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('creates WAITING order, exports to Regate outside SQL transaction, and validates order with notifications', function (): void {
|
|
// GIVEN
|
|
$baseTxLevel = DB::transactionLevel();
|
|
|
|
$spyRegate = new class () implements RegateService
|
|
{
|
|
public ?int $recordedTxLevel = null;
|
|
|
|
#[\Override]
|
|
public function processOrder(
|
|
OrderReference $reference,
|
|
Matricule $employeeMatricule,
|
|
CarbonImmutable $pickupDay,
|
|
array $lines,
|
|
): void {
|
|
$this->recordedTxLevel = DB::transactionLevel();
|
|
}
|
|
};
|
|
|
|
$ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2, regateService: $spyRegate);
|
|
|
|
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
|
|
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
|
|
$confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']);
|
|
|
|
// WHEN: Step 1 - create pending PENDING order
|
|
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
|
|
|
|
// THEN: Order is PENDING and no notifications or emails were sent yet
|
|
expect($placeOutput->status)->toBe(PlacePendingOrderStatus::PENDING_CREATED)
|
|
->and($placeOutput->orderId)->toBeInstanceOf(OrderId::class);
|
|
|
|
$pendingOrder = Order::query()->find($placeOutput->orderId?->value->toString());
|
|
expect($pendingOrder?->status)->toBe(OrderStatus::PENDING);
|
|
Notification::assertNothingSent();
|
|
|
|
// WHEN: Step 2 - export to Regate outside any extra SQL transaction
|
|
/** @var OrderId $orderId */
|
|
$orderId = $placeOutput->orderId;
|
|
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
|
|
|
|
expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT)
|
|
->and($spyRegate->recordedTxLevel)->toBe($baseTxLevel);
|
|
|
|
// WHEN: Step 3 - confirm placed order (VALIDATED + AnOrderHasBeenPlaced)
|
|
$confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId));
|
|
|
|
// THEN
|
|
expect($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED);
|
|
$confirmedOrder = Order::query()->with('lines')->find($orderId->value->toString());
|
|
expect($confirmedOrder?->status)->toBe(OrderStatus::VALIDATED)
|
|
->and($confirmedOrder?->lines)->toHaveCount(1);
|
|
|
|
Mail::assertQueued(OrderConfirmAdminMail::class, 1);
|
|
Notification::assertSentTo($ctx['employee'], OrderConfirmed::class);
|
|
expect($ctx['basketRepository']->find($ctx['basketId']))->toBeNull();
|
|
});
|
|
|
|
it('marks PENDING order as FAILED cleanly, frees weekly limit and keeps basket intact when Regate export fails', function (): void {
|
|
// 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 = buildOrderPlacementScenario(regateService: $failingRegate);
|
|
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
|
|
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
|
|
$failAction = new FailPendingOrder($ctx['tunnelService']);
|
|
|
|
// WHEN
|
|
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
|
|
/** @var OrderId $orderId */
|
|
$orderId = $placeOutput->orderId;
|
|
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
|
|
$failOutput = $ctx['executor']->execute($failAction, new FailPendingOrderInput($orderId));
|
|
|
|
// THEN
|
|
expect($exportOutput)->toBe(ExportOrderToRegateOutput::FAILED)
|
|
->and($failOutput)->toBe(FailPendingOrderOutput::FAILED);
|
|
|
|
$persistedOrder = Order::query()->find($orderId->value->toString());
|
|
expect($persistedOrder?->status)->toBe(OrderStatus::FAILED)
|
|
->and($ctx['basketRepository']->find($ctx['basketId']))->not->toBeNull();
|
|
Mail::assertNothingQueued();
|
|
Notification::assertNothingSent();
|
|
});
|
|
|
|
it('sends Regate order email through real MailRegateService when export succeeds', function (): void {
|
|
// GIVEN
|
|
$ctx = buildOrderPlacementScenario(priceCents: 2000, qty: 2);
|
|
$placeAction = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
|
|
$exportAction = new ExportOrderToRegate($ctx['tunnelService']);
|
|
$confirmAction = new ConfirmPlacedOrder($ctx['tunnelService']);
|
|
|
|
// WHEN
|
|
$placeOutput = $ctx['executor']->execute($placeAction, new PlacePendingOrderInput($ctx['customer']->getId()));
|
|
/** @var OrderId $orderId */
|
|
$orderId = $placeOutput->orderId;
|
|
$exportOutput = $ctx['executor']->execute($exportAction, new ExportOrderToRegateInput($orderId));
|
|
$confirmOutput = $ctx['executor']->execute($confirmAction, new ConfirmPlacedOrderInput($orderId));
|
|
|
|
// THEN
|
|
expect($exportOutput)->toBe(ExportOrderToRegateOutput::SENT)
|
|
->and($confirmOutput)->toBe(ConfirmPlacedOrderOutput::CONFIRMED);
|
|
Mail::assertSent(RegateOrderMail::class, 1);
|
|
});
|
|
|
|
it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void {
|
|
// GIVEN
|
|
$ctx = buildOrderPlacementScenario(priceCents: 21000, qty: 1);
|
|
$action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
|
|
|
|
// WHEN
|
|
$output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId()));
|
|
|
|
// THEN
|
|
expect($output->status)->toBe(PlacePendingOrderStatus::ORDER_LIMIT_EXCEEDED)
|
|
->and($output->orderReference)->toBeNull()
|
|
->and(Order::query()->count())->toBe(0);
|
|
Mail::assertNothingSent();
|
|
});
|
|
|
|
it('counts existing PENDING orders toward weekly limit to prevent concurrent overspending', function (): void {
|
|
// GIVEN
|
|
$ctx = buildOrderPlacementScenario(priceCents: 6000, qty: 1);
|
|
|
|
Order::query()->forceCreate([
|
|
'id' => UuidHelper::v7()->toString(),
|
|
'shop_id' => $ctx['shop']->id,
|
|
'reference' => new OrderReference(UuidHelper::v7()),
|
|
'status' => OrderStatus::PENDING->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',
|
|
]);
|
|
|
|
$action = new PlacePendingOrder($ctx['tunnelService'], $ctx['basketRepository']);
|
|
|
|
// WHEN
|
|
$output = $ctx['executor']->execute($action, new PlacePendingOrderInput($ctx['customer']->getId()));
|
|
|
|
// THEN
|
|
expect($output->status)->toBe(PlacePendingOrderStatus::WEEKLY_LIMIT_EXCEEDED)
|
|
->and(Order::query()->count())->toBe(1);
|
|
Mail::assertNothingSent();
|
|
});
|
|
|
|
it('returns INACTIVE_SHOPPER, UNORDERABLE_PRODUCT, EXPIRED_TIME_SLOT, BASKET_PRICE_CHANGED and LOCK_TIMEOUT appropriately', function (): void {
|
|
/** @var \Tests\TestCase $this */
|
|
// GIVEN: inactive employee
|
|
$inactiveCtx = buildOrderPlacementScenario(activeEmployee: false);
|
|
$inactiveOut = $inactiveCtx['executor']->execute(
|
|
new PlacePendingOrder($inactiveCtx['tunnelService'], $inactiveCtx['basketRepository']),
|
|
new PlacePendingOrderInput($inactiveCtx['customer']->getId()),
|
|
);
|
|
expect($inactiveOut->status)->toBe(PlacePendingOrderStatus::INACTIVE_SHOPPER);
|
|
|
|
// GIVEN: disabled product
|
|
$unorderableCtx = buildOrderPlacementScenario();
|
|
$unorderableCtx['product']->status = false;
|
|
$unorderableCtx['product']->saveOrFail();
|
|
$unorderableOut = $unorderableCtx['executor']->execute(
|
|
new PlacePendingOrder($unorderableCtx['tunnelService'], $unorderableCtx['basketRepository']),
|
|
new PlacePendingOrderInput($unorderableCtx['customer']->getId()),
|
|
);
|
|
expect($unorderableOut->status)->toBe(PlacePendingOrderStatus::UNORDERABLE_PRODUCT);
|
|
|
|
// GIVEN: expired pickup slot
|
|
$expiredCtx = buildOrderPlacementScenario(
|
|
pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'),
|
|
);
|
|
$expiredOut = $expiredCtx['executor']->execute(
|
|
new PlacePendingOrder($expiredCtx['tunnelService'], $expiredCtx['basketRepository']),
|
|
new PlacePendingOrderInput($expiredCtx['customer']->getId()),
|
|
);
|
|
expect($expiredOut->status)->toBe(PlacePendingOrderStatus::EXPIRED_TIME_SLOT);
|
|
|
|
// GIVEN: price increase before finalization
|
|
$priceCtx = buildOrderPlacementScenario(priceCents: 1000, qty: 2);
|
|
$priceCtx['product']->price = Money::EUR(1500);
|
|
$priceCtx['product']->saveOrFail();
|
|
$priceOut = $priceCtx['executor']->execute(
|
|
new PlacePendingOrder($priceCtx['tunnelService'], $priceCtx['basketRepository']),
|
|
new PlacePendingOrderInput($priceCtx['customer']->getId()),
|
|
);
|
|
expect($priceOut->status)->toBe(PlacePendingOrderStatus::BASKET_PRICE_CHANGED)
|
|
->and($priceCtx['basketRepository']->find($priceCtx['basketId'])?->totalTaxIncluded()->getAmount())->toBe('3165');
|
|
|
|
// GIVEN: lock timeout
|
|
/** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */
|
|
$lock = \Mockery::mock(Lock::class);
|
|
$lock->shouldReceive('synchronize')->once()->andThrow(new LockTimeoutException('Lock timed out'));
|
|
$lockCtx = buildOrderPlacementScenario(lock: $lock);
|
|
$lockOut = $lockCtx['executor']->execute(
|
|
new PlacePendingOrder($lockCtx['tunnelService'], $lockCtx['basketRepository']),
|
|
new PlacePendingOrderInput($lockCtx['customer']->getId()),
|
|
);
|
|
expect($lockOut->status)->toBe(PlacePendingOrderStatus::LOCK_TIMEOUT);
|
|
});
|
|
|
|
it('executes ExportOrderToRegate without opening a DB transaction and returns LOCK_TIMEOUT when lock fails', function (): void {
|
|
// GIVEN
|
|
$orderId = new OrderId(UuidHelper::v7());
|
|
$input = new ExportOrderToRegateInput($orderId);
|
|
$levelBeforeExecute = DB::transactionLevel();
|
|
$levelInsideAction = null;
|
|
|
|
/** @var OrderTunnelService&\Mockery\MockInterface $tunnelService */
|
|
$tunnelService = \Mockery::mock(OrderTunnelService::class);
|
|
$tunnelService->shouldReceive('exportOrderToRegate')
|
|
->once()
|
|
->with($orderId)
|
|
->andReturnUsing(function () use (&$levelInsideAction): void {
|
|
$levelInsideAction = DB::transactionLevel();
|
|
});
|
|
|
|
$memoryExecutor = new ActionExecutorService(
|
|
new LaravelCacheLock(new Repository(new ArrayStore())),
|
|
new NullLogger(),
|
|
new LaravelDomainEventDispatcher(),
|
|
);
|
|
|
|
// WHEN
|
|
$sentOutput = $memoryExecutor->execute(new ExportOrderToRegate($tunnelService), $input);
|
|
|
|
// GIVEN (contended lock)
|
|
/** @var Lock&\Mockery\MockInterface $contendedLock */
|
|
$contendedLock = \Mockery::mock(Lock::class);
|
|
$contendedLock->shouldReceive('synchronize')
|
|
->once()
|
|
->with("order:export:{$orderId->value}", \Mockery::type(\Closure::class), 30, 10)
|
|
->andThrow(new LockTimeoutException('Lock timed out'));
|
|
|
|
$contendedExecutor = new ActionExecutorService(
|
|
$contendedLock,
|
|
new NullLogger(),
|
|
new LaravelDomainEventDispatcher(),
|
|
);
|
|
|
|
// WHEN
|
|
$timeoutOutput = $contendedExecutor->execute(new ExportOrderToRegate($tunnelService), $input);
|
|
|
|
// THEN
|
|
expect($sentOutput)->toBe(ExportOrderToRegateOutput::SENT)
|
|
->and($levelInsideAction)->toBe($levelBeforeExecute)
|
|
->and($timeoutOutput)->toBe(ExportOrderToRegateOutput::LOCK_TIMEOUT);
|
|
});
|
|
});
|