test(actions): add missing integration tests for Products, Basket, CRM, and Orders
This commit is contained in:
parent
e0d2074b2b
commit
8029bcd959
11 changed files with 1854 additions and 0 deletions
157
tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php
Normal file
157
tests/Integration/WithApp/App/Actions/Basket/AddToBasketTest.php
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Basket\AddToBasket;
|
||||
use App\Cqs\Actions\Basket\AddToBasketInput;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductInco;
|
||||
use App\Models\Range;
|
||||
use App\Services\ActionExecutorService;
|
||||
use Domain\Builders\OrderBuilder;
|
||||
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\UnorderableProductException;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use Domain\Models\ValueObjects\Entities\BasketId;
|
||||
use Domain\Models\ValueObjects\Entities\ShopperId;
|
||||
use Domain\Services\BasketService;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
||||
use Infrastructure\Adapters\Repositories\EloquentProductRepository;
|
||||
use Infrastructure\Adapters\Repositories\SessionBasketRepository;
|
||||
use Infrastructure\Adapters\Serializers\BasketSerializer;
|
||||
use Infrastructure\Adapters\Services\AppSessionService;
|
||||
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
||||
use Money\Money;
|
||||
use Psr\Log\NullLogger;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makeBasketProductFixture(bool $status = true, bool $withInco = true): Product
|
||||
{
|
||||
$range = new Range();
|
||||
$range->name = 'Gamme Panier ' . uniqid();
|
||||
$range->status = true;
|
||||
$range->order = ((int) Range::query()->max('order')) + 1;
|
||||
$range->picture_alt = 'alt';
|
||||
$range->picture_title = 'title';
|
||||
$range->saveOrFail();
|
||||
|
||||
$product = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => 'Produit Panier ' . uniqid(),
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_5_5,
|
||||
'description' => 'Description panier',
|
||||
'status' => $status,
|
||||
]);
|
||||
$product->price = Money::EUR(1000);
|
||||
$product->short_description = 'Court';
|
||||
$product->picture_alt = 'alt';
|
||||
$product->picture_title = 'title';
|
||||
$product->picture_large_alt = 'alt large';
|
||||
$product->picture_large_title = 'title large';
|
||||
$product->saveOrFail();
|
||||
|
||||
if ($withInco) {
|
||||
$inco = new ProductInco();
|
||||
$inco->product_id = $product->id;
|
||||
$inco->no_art = random_int(10000, 99999);
|
||||
$inco->saveOrFail();
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
describe('AddToBasket action', function (): void {
|
||||
it('adds an orderable product to session basket and increments quantity on repeated additions', function (): void {
|
||||
// GIVEN
|
||||
$product = makeBasketProductFixture();
|
||||
$session = Session::driver();
|
||||
$repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer());
|
||||
$dispatcher = new LaravelDomainEventDispatcher();
|
||||
$basketSvc = new BasketService(
|
||||
$repository,
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
$dispatcher,
|
||||
);
|
||||
$action = new AddToBasket($basketSvc);
|
||||
|
||||
// WHEN
|
||||
$action(new AddToBasketInput($product->getId(), 2));
|
||||
$action(new AddToBasketInput($product->getId(), 3));
|
||||
|
||||
// THEN
|
||||
$basket = $basketSvc->getBasket();
|
||||
expect($basket->countItems())->toBe(5)
|
||||
->and($basket->items())->toHaveCount(1)
|
||||
->and($basket->items()[$product->id]->qty)->toBe(5)
|
||||
->and($basket->items()[$product->id]->unitPriceHt->getAmount())->toBe('1000');
|
||||
});
|
||||
|
||||
it('invalidates existing order builder in session when executed through ActionExecutorService', function (): void {
|
||||
// GIVEN
|
||||
$product = makeBasketProductFixture();
|
||||
$session = Session::driver();
|
||||
$repository = new SessionBasketRepository($session, 'basket_', new BasketSerializer());
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$builderManager->save(OrderBuilder::fromBasket(
|
||||
new Basket(new BasketId(Uuid::uuid7()), []),
|
||||
new ShopperId(Uuid::uuid7()),
|
||||
));
|
||||
|
||||
$dispatcher = new LaravelDomainEventDispatcher();
|
||||
$basketSvc = new BasketService(
|
||||
$repository,
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
$dispatcher,
|
||||
);
|
||||
$executor = new ActionExecutorService(
|
||||
new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
$dispatcher,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$executor->execute(new AddToBasket($basketSvc), new AddToBasketInput($product->getId(), 1));
|
||||
|
||||
// THEN
|
||||
expect($builderManager->get())->toBeNull()
|
||||
->and($basketSvc->getBasket()->countItems())->toBe(1);
|
||||
});
|
||||
|
||||
it('throws UnorderableProductException when product is disabled or missing inco', function (): void {
|
||||
// GIVEN
|
||||
$inactiveProduct = makeBasketProductFixture(status: false, withInco: true);
|
||||
$noIncoProduct = makeBasketProductFixture(status: true, withInco: false);
|
||||
$session = Session::driver();
|
||||
$basketSvc = new BasketService(
|
||||
new SessionBasketRepository($session, 'basket_', new BasketSerializer()),
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
new LaravelDomainEventDispatcher(),
|
||||
);
|
||||
$action = new AddToBasket($basketSvc);
|
||||
|
||||
// WHEN & THEN
|
||||
expect(fn () => $action(new AddToBasketInput($inactiveProduct->getId(), 1)))
|
||||
->toThrow(UnorderableProductException::class);
|
||||
expect(fn () => $action(new AddToBasketInput($noIncoProduct->getId(), 1)))
|
||||
->toThrow(UnorderableProductException::class);
|
||||
expect($basketSvc->hasItems())->toBeFalse();
|
||||
});
|
||||
});
|
||||
103
tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php
Normal file
103
tests/Integration/WithApp/App/Actions/Basket/EmptyBasketTest.php
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Contracts\ActionInputEmpty;
|
||||
use App\Cqs\Actions\Basket\EmptyBasket;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductInco;
|
||||
use App\Models\Range;
|
||||
use App\Services\ActionExecutorService;
|
||||
use Domain\Builders\OrderBuilder;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\SellUnit;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\InvoicingUnit;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use Domain\Models\ValueObjects\Entities\BasketId;
|
||||
use Domain\Models\ValueObjects\Entities\ShopperId;
|
||||
use Domain\Services\BasketService;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
||||
use Infrastructure\Adapters\Repositories\EloquentProductRepository;
|
||||
use Infrastructure\Adapters\Repositories\SessionBasketRepository;
|
||||
use Infrastructure\Adapters\Serializers\BasketSerializer;
|
||||
use Infrastructure\Adapters\Services\AppSessionService;
|
||||
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
||||
use Money\Money;
|
||||
use Psr\Log\NullLogger;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
describe('EmptyBasket action', function (): void {
|
||||
it('removes all items from session basket and clears order builder', function (): void {
|
||||
// GIVEN
|
||||
$range = new Range();
|
||||
$range->name = 'Gamme Vider Panier ' . uniqid();
|
||||
$range->status = true;
|
||||
$range->order = 1;
|
||||
$range->picture_alt = 'alt';
|
||||
$range->picture_title = 'title';
|
||||
$range->saveOrFail();
|
||||
|
||||
$product = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => 'Produit À Vider ' . uniqid(),
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_5_5,
|
||||
'description' => 'Desc',
|
||||
'status' => true,
|
||||
]);
|
||||
$product->price = Money::EUR(900);
|
||||
$product->short_description = 'Court';
|
||||
$product->picture_alt = 'alt';
|
||||
$product->picture_title = 'title';
|
||||
$product->picture_large_alt = 'alt large';
|
||||
$product->picture_large_title = 'title large';
|
||||
$product->saveOrFail();
|
||||
|
||||
$inco = new ProductInco();
|
||||
$inco->product_id = $product->id;
|
||||
$inco->no_art = random_int(10000, 99999);
|
||||
$inco->saveOrFail();
|
||||
|
||||
$session = Session::driver();
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$dispatcher = new LaravelDomainEventDispatcher();
|
||||
$basketSvc = new BasketService(
|
||||
new SessionBasketRepository($session, 'basket_', new BasketSerializer()),
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
$dispatcher,
|
||||
);
|
||||
$basketSvc->add($product->getId(), 2);
|
||||
|
||||
$builderManager->save(OrderBuilder::fromBasket(
|
||||
new Basket(new BasketId(Uuid::uuid7()), []),
|
||||
new ShopperId(Uuid::uuid7()),
|
||||
));
|
||||
|
||||
$executor = new ActionExecutorService(
|
||||
new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
$dispatcher,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$executor->execute(new EmptyBasket($basketSvc), ActionInputEmpty::create());
|
||||
|
||||
// THEN
|
||||
expect($basketSvc->hasItems())->toBeFalse()
|
||||
->and($basketSvc->getBasket()->items())->toBeEmpty()
|
||||
->and($builderManager->get())->toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Basket\RemoveFromBasket;
|
||||
use App\Cqs\Actions\Basket\RemoveProductFromBasketInput;
|
||||
use App\Cqs\Actions\Basket\RemoveQuantityFromBasketInput;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductInco;
|
||||
use App\Models\Range;
|
||||
use App\Services\ActionExecutorService;
|
||||
use Domain\Builders\OrderBuilder;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\SellUnit;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\InvoicingUnit;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use Domain\Models\ValueObjects\Entities\BasketId;
|
||||
use Domain\Models\ValueObjects\Entities\ShopperId;
|
||||
use Domain\Services\BasketService;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
||||
use Infrastructure\Adapters\Repositories\EloquentProductRepository;
|
||||
use Infrastructure\Adapters\Repositories\SessionBasketRepository;
|
||||
use Infrastructure\Adapters\Serializers\BasketSerializer;
|
||||
use Infrastructure\Adapters\Services\AppSessionService;
|
||||
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
||||
use Money\Money;
|
||||
use Psr\Log\NullLogger;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makeRemovableProductFixture(): Product
|
||||
{
|
||||
$range = new Range();
|
||||
$range->name = 'Gamme Retrait Panier ' . uniqid();
|
||||
$range->status = true;
|
||||
$range->order = ((int) Range::query()->max('order')) + 1;
|
||||
$range->picture_alt = 'alt';
|
||||
$range->picture_title = 'title';
|
||||
$range->saveOrFail();
|
||||
|
||||
$product = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => 'Produit Retrait ' . uniqid(),
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_5_5,
|
||||
'description' => 'Description retrait',
|
||||
'status' => true,
|
||||
]);
|
||||
$product->price = Money::EUR(800);
|
||||
$product->short_description = 'Court';
|
||||
$product->picture_alt = 'alt';
|
||||
$product->picture_title = 'title';
|
||||
$product->picture_large_alt = 'alt large';
|
||||
$product->picture_large_title = 'title large';
|
||||
$product->saveOrFail();
|
||||
|
||||
$inco = new ProductInco();
|
||||
$inco->product_id = $product->id;
|
||||
$inco->no_art = random_int(10000, 99999);
|
||||
$inco->saveOrFail();
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
describe('RemoveFromBasket action', function (): void {
|
||||
it('decrements quantity and removes the line when RemoveQuantityFromBasketInput hits zero', function (): void {
|
||||
// GIVEN
|
||||
$product = makeRemovableProductFixture();
|
||||
$session = Session::driver();
|
||||
$basketSvc = new BasketService(
|
||||
new SessionBasketRepository($session, 'basket_', new BasketSerializer()),
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
new LaravelDomainEventDispatcher(),
|
||||
);
|
||||
$basketSvc->add($product->getId(), 5);
|
||||
$action = new RemoveFromBasket($basketSvc);
|
||||
|
||||
// WHEN
|
||||
$action(new RemoveQuantityFromBasketInput($product->getId(), 2));
|
||||
|
||||
// THEN
|
||||
expect($basketSvc->getBasket()->items()[$product->id]->qty)->toBe(3);
|
||||
|
||||
// WHEN removing remaining quantity
|
||||
$action(new RemoveQuantityFromBasketInput($product->getId(), 3));
|
||||
|
||||
// THEN
|
||||
expect($basketSvc->hasItems())->toBeFalse();
|
||||
});
|
||||
|
||||
it('removes the whole product line with RemoveProductFromBasketInput and clears order builder', function (): void {
|
||||
// GIVEN
|
||||
$product1 = makeRemovableProductFixture();
|
||||
$product2 = makeRemovableProductFixture();
|
||||
$session = Session::driver();
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$dispatcher = new LaravelDomainEventDispatcher();
|
||||
$basketSvc = new BasketService(
|
||||
new SessionBasketRepository($session, 'basket_', new BasketSerializer()),
|
||||
new EloquentProductRepository(),
|
||||
new AppSessionService('domain_session_uuid'),
|
||||
$dispatcher,
|
||||
);
|
||||
$basketSvc->add($product1->getId(), 4);
|
||||
$basketSvc->add($product2->getId(), 2);
|
||||
|
||||
$builderManager->save(OrderBuilder::fromBasket(
|
||||
new Basket(new BasketId(Uuid::uuid7()), []),
|
||||
new ShopperId(Uuid::uuid7()),
|
||||
));
|
||||
|
||||
$executor = new ActionExecutorService(
|
||||
new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
$dispatcher,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$executor->execute(new RemoveFromBasket($basketSvc), new RemoveProductFromBasketInput($product1->getId()));
|
||||
|
||||
// THEN
|
||||
$basket = $basketSvc->getBasket();
|
||||
expect($basket->countItems())->toBe(2)
|
||||
->and($basket->items())->toHaveCount(1)
|
||||
->and(array_key_exists($product1->id, $basket->items()))->toBeFalse()
|
||||
->and($basket->items()[$product2->id]->qty)->toBe(2)
|
||||
->and($builderManager->get())->toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Crm\UnsubscribeFromNewsletter;
|
||||
use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterInput;
|
||||
use App\Cqs\Actions\Crm\UnsubscribeFromNewsletterOutput;
|
||||
use App\Services\CrmService;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
|
||||
describe('UnsubscribeFromNewsletter action', function (): void {
|
||||
it('returns SUCCESS when CRM service unsubscribes the customer', function (): void {
|
||||
// GIVEN
|
||||
$hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('unsubscribeCustomer')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value))
|
||||
->andReturnTrue();
|
||||
|
||||
$action = new UnsubscribeFromNewsletter($crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UnsubscribeFromNewsletterInput($hashcode));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBe(UnsubscribeFromNewsletterOutput::SUCCESS);
|
||||
});
|
||||
|
||||
it('returns FAILURE when CRM service returns false', function (): void {
|
||||
// GIVEN
|
||||
$hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('unsubscribeCustomer')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode->value))
|
||||
->andReturnFalse();
|
||||
|
||||
$action = new UnsubscribeFromNewsletter($crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UnsubscribeFromNewsletterInput($hashcode));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE);
|
||||
});
|
||||
|
||||
it('returns FAILURE without throwing when CRM service throws an exception', function (): void {
|
||||
// GIVEN
|
||||
$hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('unsubscribeCustomer')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('CRM timeout'));
|
||||
|
||||
$action = new UnsubscribeFromNewsletter($crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UnsubscribeFromNewsletterInput($hashcode));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBe(UnsubscribeFromNewsletterOutput::FAILURE);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Crm\UpdateCustomerPassword;
|
||||
use App\Cqs\Actions\Crm\UpdateCustomerPasswordInput;
|
||||
use App\Cqs\Actions\Crm\UpdateCustomerPasswordOutput;
|
||||
use App\Models\Customer;
|
||||
use App\Services\CrmService;
|
||||
use Domain\Enums\Country;
|
||||
use Domain\Exceptions\AuthServiceException;
|
||||
use Domain\Models\ValueObjects\CrmCustomer;
|
||||
use Domain\Models\ValueObjects\Email;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Infrastructure\Adapters\Services\AppCustomerAuthService;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makePasswordTestCrmCustomer(string $hashcode, string $email): CrmCustomer
|
||||
{
|
||||
return new CrmCustomer(
|
||||
hashcode: $hashcode,
|
||||
email: $email,
|
||||
password: null,
|
||||
firstname: 'Claire',
|
||||
lastname: 'Dupuis',
|
||||
birthDate: '1991-07-20',
|
||||
phone: null,
|
||||
address: null,
|
||||
address2: null,
|
||||
city: 'Laval',
|
||||
postcode: '53000',
|
||||
country: Country::france,
|
||||
optIn: false,
|
||||
status: true,
|
||||
lastConnection: null,
|
||||
);
|
||||
}
|
||||
|
||||
describe('UpdateCustomerPassword action', function (): void {
|
||||
it('changes password in CRM for authenticated customer', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$hashcodeUuid = Uuid::uuid4();
|
||||
$hashcode = $hashcodeUuid->toString();
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('claire.dupuis@example.com');
|
||||
$customer->hashcode = new CrmHashcode($hashcodeUuid);
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
$crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value);
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('getCustomerFromHashCode')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (CrmHashcode $h): bool => $h->value === $hashcode))
|
||||
->andReturn($crmCustomer);
|
||||
$crmService->shouldReceive('changePassword')
|
||||
->once()
|
||||
->with($crmCustomer, 'OldPass123!', 'NewPass456!')
|
||||
->andReturn($crmCustomer);
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomerPassword($authService, $crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!'));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBeInstanceOf(UpdateCustomerPasswordOutput::class)
|
||||
->and($output->result)->toBe($crmCustomer);
|
||||
});
|
||||
|
||||
it('returns false output when customer cannot be resolved in CRM', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('missing.crm@example.com');
|
||||
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('getCustomerFromHashCode')
|
||||
->once()
|
||||
->andReturnNull();
|
||||
$crmService->shouldNotReceive('changePassword');
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomerPassword($authService, $crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!'));
|
||||
|
||||
// THEN
|
||||
expect($output->result)->toBeFalse();
|
||||
});
|
||||
|
||||
it('returns false output when changePassword throws an unexpected exception', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$hashcodeUuid = Uuid::uuid4();
|
||||
$hashcode = $hashcodeUuid->toString();
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('pwd.error@example.com');
|
||||
$customer->hashcode = new CrmHashcode($hashcodeUuid);
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
$crmCustomer = makePasswordTestCrmCustomer($hashcode, $customer->email->value);
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('getCustomerFromHashCode')
|
||||
->once()
|
||||
->andReturn($crmCustomer);
|
||||
$crmService->shouldReceive('changePassword')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('CRM error'));
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomerPassword($authService, $crmService);
|
||||
|
||||
// WHEN
|
||||
$output = $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!'));
|
||||
|
||||
// THEN
|
||||
expect($output->result)->toBeFalse();
|
||||
});
|
||||
|
||||
it('throws AuthServiceException when unauthenticated', function (): void {
|
||||
// GIVEN
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldNotReceive('getCustomerFromHashCode');
|
||||
$crmService->shouldNotReceive('changePassword');
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomerPassword($authService, $crmService);
|
||||
|
||||
// WHEN & THEN
|
||||
expect(fn () => $action(new UpdateCustomerPasswordInput('OldPass123!', 'NewPass456!')))
|
||||
->toThrow(AuthServiceException::class);
|
||||
});
|
||||
});
|
||||
206
tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php
Normal file
206
tests/Integration/WithApp/App/Actions/Crm/UpdateCustomerTest.php
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Crm\UpdateCustomer;
|
||||
use App\Cqs\Actions\Crm\UpdateCustomerInput;
|
||||
use App\Cqs\Actions\Crm\UpdateCustomerOutput;
|
||||
use App\Models\Customer;
|
||||
use App\Services\CrmService;
|
||||
use Domain\Enums\Country;
|
||||
use Domain\Exceptions\AuthServiceException;
|
||||
use Domain\Models\ValueObjects\CrmCustomer;
|
||||
use Domain\Models\ValueObjects\Email;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Infrastructure\Adapters\Services\AppCustomerAuthService;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makeCrmCustomerDto(string $hashcode, string $email): CrmCustomer
|
||||
{
|
||||
return new CrmCustomer(
|
||||
hashcode: $hashcode,
|
||||
email: $email,
|
||||
password: null,
|
||||
firstname: 'Jeanne',
|
||||
lastname: 'Martin',
|
||||
birthDate: '1992-05-14',
|
||||
phone: '+33611223344',
|
||||
address: '12 rue des Lilas',
|
||||
address2: null,
|
||||
city: 'Laval',
|
||||
postcode: '53000',
|
||||
country: Country::france,
|
||||
optIn: true,
|
||||
status: true,
|
||||
lastConnection: null,
|
||||
);
|
||||
}
|
||||
|
||||
describe('UpdateCustomer action', function (): void {
|
||||
it('updates customer information in CRM for the authenticated customer', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$hashcodeUuid = Uuid::uuid4();
|
||||
$hashcode = $hashcodeUuid->toString();
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('jeanne.martin@example.com');
|
||||
$customer->hashcode = new CrmHashcode($hashcodeUuid);
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
$expectedCrmCustomer = makeCrmCustomerDto($hashcode, $customer->email->value);
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('updateCustomerInfos')
|
||||
->once()
|
||||
->withArgs(function (Customer $passedCustomer, array $data) use ($customer): bool {
|
||||
return $passedCustomer->id === $customer->id
|
||||
&& $data === [
|
||||
'firstname' => 'Jeanne',
|
||||
'lastname' => 'Martin',
|
||||
'birth_date' => '1992-05-14',
|
||||
'postcode' => '53000',
|
||||
'city' => 'Laval',
|
||||
'opt_in' => true,
|
||||
'phone' => '+33611223344',
|
||||
'address' => '12 rue des Lilas',
|
||||
];
|
||||
})
|
||||
->andReturn($expectedCrmCustomer);
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomer($authService, $crmService);
|
||||
|
||||
$input = new UpdateCustomerInput(
|
||||
firstname: 'Jeanne',
|
||||
lastname: 'Martin',
|
||||
birthDate: '1992-05-14',
|
||||
phone: '+33611223344',
|
||||
address: '12 rue des Lilas',
|
||||
postcode: '53000',
|
||||
city: 'Laval',
|
||||
optIn: true,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$output = $action($input);
|
||||
|
||||
// THEN
|
||||
expect($output)->toBeInstanceOf(UpdateCustomerOutput::class)
|
||||
->and($output->result)->toBe($expectedCrmCustomer);
|
||||
});
|
||||
|
||||
it('omits nullable phone and address when null and propagates validation exceptions', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$hashcodeUuid = Uuid::uuid4();
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('no.phone@example.com');
|
||||
$customer->hashcode = new CrmHashcode($hashcodeUuid);
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
$validationException = ValidationException::withMessages(['postcode' => ['Code postal invalide']]);
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('updateCustomerInfos')
|
||||
->once()
|
||||
->withArgs(function (Customer $_, array $data): bool {
|
||||
return ! array_key_exists('phone', $data)
|
||||
&& ! array_key_exists('address', $data)
|
||||
&& $data['opt_in'] === false;
|
||||
})
|
||||
->andReturn($validationException);
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomer($authService, $crmService);
|
||||
|
||||
$input = new UpdateCustomerInput(
|
||||
firstname: 'Paul',
|
||||
lastname: 'Durand',
|
||||
birthDate: '1985-03-10',
|
||||
phone: null,
|
||||
address: null,
|
||||
postcode: '00000',
|
||||
city: 'Sablé',
|
||||
optIn: false,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$output = $action($input);
|
||||
|
||||
// THEN
|
||||
expect($output->result)->toBe($validationException);
|
||||
});
|
||||
|
||||
it('returns false output when CRM service throws an unexpected error', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('err.crm@example.com');
|
||||
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
$customer->saveOrFail();
|
||||
|
||||
$this->actingAs($customer, 'frontend');
|
||||
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldReceive('updateCustomerInfos')
|
||||
->once()
|
||||
->andThrow(new \RuntimeException('CRM unavailable'));
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomer($authService, $crmService);
|
||||
|
||||
$input = new UpdateCustomerInput(
|
||||
firstname: 'Paul',
|
||||
lastname: 'Durand',
|
||||
birthDate: '1985-03-10',
|
||||
phone: null,
|
||||
address: null,
|
||||
postcode: '72300',
|
||||
city: 'Sablé',
|
||||
optIn: true,
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$output = $action($input);
|
||||
|
||||
// THEN
|
||||
expect($output->result)->toBeFalse();
|
||||
});
|
||||
|
||||
it('throws AuthServiceException when no customer is authenticated', function (): void {
|
||||
// GIVEN
|
||||
/** @var \App\Services\CrmService&\Mockery\MockInterface $crmService */
|
||||
$crmService = \Mockery::mock(CrmService::class);
|
||||
$crmService->shouldNotReceive('updateCustomerInfos');
|
||||
|
||||
$authService = new AppCustomerAuthService(Auth::guard('frontend'), $crmService);
|
||||
$action = new UpdateCustomer($authService, $crmService);
|
||||
|
||||
$input = new UpdateCustomerInput(
|
||||
firstname: 'Guest',
|
||||
lastname: 'User',
|
||||
birthDate: '1990-01-01',
|
||||
phone: null,
|
||||
address: null,
|
||||
postcode: '72300',
|
||||
city: 'Sablé',
|
||||
optIn: false,
|
||||
);
|
||||
|
||||
// WHEN & THEN
|
||||
expect(fn () => $action($input))
|
||||
->toThrow(AuthServiceException::class);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Orders\ApplyPickTimeSlot;
|
||||
use App\Cqs\Actions\Orders\ApplyPickTimeSlotInput;
|
||||
use App\Cqs\Actions\Orders\ApplyPickTimeSlotOutput;
|
||||
use App\Enums\ApplyPickTimeSlotStatus;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Employee;
|
||||
use App\Models\PickupException;
|
||||
use App\Models\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Domain\Builders\OrderBuilder;
|
||||
use Domain\Builders\OrderBuilderCompleted;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use Domain\Models\ValueObjects\BasketProduct;
|
||||
use Domain\Models\ValueObjects\Code;
|
||||
use Domain\Models\ValueObjects\DiscountRate;
|
||||
use Domain\Models\ValueObjects\Email;
|
||||
use Domain\Models\ValueObjects\Entities\BasketId;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
use Domain\Models\ValueObjects\IncoId;
|
||||
use Domain\Models\ValueObjects\Matricule;
|
||||
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\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
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\Services\EloquentEmployeeStatisticsService;
|
||||
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
||||
use Money\Currency;
|
||||
use Money\Money;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Shared\ValueObjects\CrmHashcode;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
describe('ApplyPickTimeSlot action', function (): void {
|
||||
beforeEach(function (): void {
|
||||
$now = CarbonImmutable::parse('2026-11-16 10:00:00', 'Europe/Paris');
|
||||
CarbonImmutable::setTestNow($now);
|
||||
Date::setTestNow($now);
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
CarbonImmutable::setTestNow();
|
||||
Date::setTestNow();
|
||||
});
|
||||
|
||||
function makePickSlotEnvironment(): array
|
||||
{
|
||||
$shop = Shop::factory()->create(['default' => true]);
|
||||
|
||||
$customer = new Customer();
|
||||
$customer->email = new Email('slot.buyer@example.com');
|
||||
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
|
||||
$customer->saveOrFail();
|
||||
|
||||
$employee = new Employee();
|
||||
$employee->customer_id = $customer->id;
|
||||
$employee->matricule = new Matricule('1000303');
|
||||
$employee->code = new Code('ABCDEF');
|
||||
$employee->nom = 'Durand';
|
||||
$employee->prenom = 'Sophie';
|
||||
$employee->start_date = CarbonImmutable::parse('2025-01-01');
|
||||
$employee->etablissement = new ShopperEstablishmentCode('01');
|
||||
$employee->site = new ShopperSiteCode('SITE');
|
||||
$employee->service = new ShopperServiceCode('01');
|
||||
$employee->saveOrFail();
|
||||
|
||||
$productId = new ProductId(Uuid::uuid7());
|
||||
$basket = new Basket(new BasketId(Uuid::uuid7()), [
|
||||
$productId->value->toString() => new BasketProduct(
|
||||
id: $productId,
|
||||
name: 'Filet de Poulet',
|
||||
qty: 1,
|
||||
unitPriceHt: Money::EUR(1000),
|
||||
unitDiscount: Money::EUR(0),
|
||||
taxRate: TaxRate::TVA_5_5,
|
||||
weightGrams: 500,
|
||||
brand: ProductBrand::loue,
|
||||
incoId: new IncoId(654321),
|
||||
orderUnit: OrderUnit::PCE,
|
||||
slug: 'filet-de-poulet',
|
||||
picture: null,
|
||||
description: null,
|
||||
weightVariable: false,
|
||||
discountRate: DiscountRate::zero(),
|
||||
priceKgTtc: Money::EUR(1000),
|
||||
options: [],
|
||||
),
|
||||
]);
|
||||
|
||||
$session = Session::driver();
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$builderManager->save(OrderBuilder::fromBasket($basket, $customer->getId()));
|
||||
|
||||
$shopRepo = new EloquentShopRepository();
|
||||
$shopperRepo = new EloquentShopperRepository();
|
||||
$orderRepo = new EloquentOrderRepository();
|
||||
|
||||
/** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $regateService */
|
||||
$regateService = \Mockery::mock(RegateService::class);
|
||||
|
||||
$tunnelService = new OrderTunnelService(
|
||||
new LaravelDomainEventDispatcher(),
|
||||
new ShopperService($shopRepo, $shopperRepo),
|
||||
$builderManager,
|
||||
new PickupSchedulingService(new EloquentPickupExceptionRepository()),
|
||||
$orderRepo,
|
||||
new EloquentProductRepository(),
|
||||
new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')),
|
||||
$shopRepo,
|
||||
$shopperRepo,
|
||||
new OrderService($orderRepo),
|
||||
new EloquentEmployeeStatisticsService(),
|
||||
$regateService,
|
||||
);
|
||||
|
||||
return [$customer, $shop, $builderManager, $tunnelService];
|
||||
}
|
||||
|
||||
it('matches an open pickup day and upgrades the session builder to OrderBuilderCompleted', function (): void {
|
||||
// GIVEN
|
||||
[$customer, $shop, $builderManager, $tunnelService] = makePickSlotEnvironment();
|
||||
$action = new ApplyPickTimeSlot($tunnelService);
|
||||
|
||||
// Friday of current week after Monday 10:00 cutoff -> open
|
||||
$targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris');
|
||||
|
||||
// WHEN
|
||||
$output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBeInstanceOf(ApplyPickTimeSlotOutput::class)
|
||||
->and($output->status)->toBe(ApplyPickTimeSlotStatus::MATCHED)
|
||||
->and($output->timeSlot)->not->toBeNull()
|
||||
->and($output->timeSlot?->getAt()->format('Y-m-d'))->toBe('2026-11-20');
|
||||
|
||||
$completed = $builderManager->get();
|
||||
expect($completed)->toBeInstanceOf(OrderBuilderCompleted::class)
|
||||
->and($completed?->getShopId()->equals($shop->getId()))->toBeTrue();
|
||||
});
|
||||
|
||||
it('returns UNAVAILABLE when the requested date is blocked by a shop PickupException', function (): void {
|
||||
// GIVEN
|
||||
[$customer, $shop, $_, $tunnelService] = makePickSlotEnvironment();
|
||||
|
||||
$blockedException = PickupException::factory()->create([
|
||||
'date' => '2026-11-20',
|
||||
'label' => 'Fermeture exceptionnelle',
|
||||
]);
|
||||
$shop->pickupExceptions()->attach($blockedException->id, [
|
||||
'replacement_date' => null,
|
||||
'order_deadline_at' => null,
|
||||
]);
|
||||
|
||||
$action = new ApplyPickTimeSlot($tunnelService);
|
||||
$targetFriday = CarbonImmutable::parse('2026-11-20', 'Europe/Paris');
|
||||
|
||||
// WHEN
|
||||
$output = $action(new ApplyPickTimeSlotInput($customer->getId(), $targetFriday));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(ApplyPickTimeSlotStatus::UNAVAILABLE)
|
||||
->and($output->timeSlot)->toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Orders\CancelOrder;
|
||||
use App\Cqs\Actions\Orders\CancelOrderInput;
|
||||
use App\Cqs\Actions\Orders\CancelOrderOutput;
|
||||
use App\Models\Order;
|
||||
use App\Models\Shop;
|
||||
use Domain\Enums\OrderStatus;
|
||||
use Domain\Models\ValueObjects\DeliveryAddress;
|
||||
use Domain\Models\ValueObjects\Matricule;
|
||||
use Domain\Models\ValueObjects\OrderEmployee;
|
||||
use Domain\Models\ValueObjects\OrderReference;
|
||||
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
|
||||
use Domain\Models\ValueObjects\ShopperServiceCode;
|
||||
use Domain\Models\ValueObjects\ShopperSiteCode;
|
||||
use Domain\Services\OrderService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Infrastructure\Adapters\Repositories\EloquentOrderRepository;
|
||||
use Money\Currency;
|
||||
use Money\Money;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makeCancelOrderFixture(OrderStatus $status = OrderStatus::VALIDATED): Order
|
||||
{
|
||||
$shop = Shop::factory()->create();
|
||||
|
||||
return Order::query()->forceCreate([
|
||||
'id' => Uuid::uuid7()->toString(),
|
||||
'shop_id' => $shop->id,
|
||||
'reference' => new OrderReference(Uuid::uuid7()),
|
||||
'status' => $status->value,
|
||||
'total' => new Money(2500, new Currency('EUR')),
|
||||
'employee' => new OrderEmployee(
|
||||
new Matricule('1000202'),
|
||||
'Alice',
|
||||
'Martin',
|
||||
new ShopperEstablishmentCode('01'),
|
||||
new ShopperSiteCode('SITE'),
|
||||
new ShopperServiceCode('01'),
|
||||
),
|
||||
'delivery_address' => new DeliveryAddress('Shop Test', '2 rue Test', '72300', 'Sablé'),
|
||||
'pickup_day' => '2026-11-20 14:00:00',
|
||||
]);
|
||||
}
|
||||
|
||||
describe('CancelOrder action', function (): void {
|
||||
it('cancels an existing persisted order and updates status in database', function (): void {
|
||||
// GIVEN
|
||||
$order = makeCancelOrderFixture(OrderStatus::VALIDATED);
|
||||
$action = new CancelOrder(new OrderService(new EloquentOrderRepository()));
|
||||
|
||||
// WHEN
|
||||
$output = $action(new CancelOrderInput($order));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBe(CancelOrderOutput::CANCELLED)
|
||||
->and($order->fresh()?->status)->toBe(OrderStatus::CANCELED);
|
||||
});
|
||||
|
||||
it('returns NOT_FOUND when the order does not exist in database', function (): void {
|
||||
// GIVEN
|
||||
$missingOrder = new Order();
|
||||
$missingOrder->id = Uuid::uuid7()->toString();
|
||||
|
||||
$action = new CancelOrder(new OrderService(new EloquentOrderRepository()));
|
||||
|
||||
// WHEN
|
||||
$output = $action(new CancelOrderInput($missingOrder));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBe(CancelOrderOutput::NOT_FOUND);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,409 @@
|
|||
<?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\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();
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$builderManager->save($builder);
|
||||
|
||||
$dispatcher = new LaravelDomainEventDispatcher();
|
||||
$shopRepo = new EloquentShopRepository();
|
||||
$shopperRepo = new EloquentShopperRepository();
|
||||
$orderRepo = new EloquentOrderRepository();
|
||||
|
||||
$tunnelService = new OrderTunnelService(
|
||||
$dispatcher,
|
||||
new ShopperService($shopRepo, $shopperRepo),
|
||||
$builderManager,
|
||||
new PickupSchedulingService(new EloquentPickupExceptionRepository()),
|
||||
$orderRepo,
|
||||
new EloquentProductRepository(),
|
||||
new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')),
|
||||
$shopRepo,
|
||||
$shopperRepo,
|
||||
new OrderService($orderRepo),
|
||||
new EloquentEmployeeStatisticsService(),
|
||||
$regateService ?? new MailRegateService(new CsvGeneratorImpl(), Mail::getFacadeRoot()),
|
||||
);
|
||||
|
||||
$executor = new ActionExecutorService(
|
||||
$lock ?? new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
$dispatcher,
|
||||
);
|
||||
|
||||
return [
|
||||
'customer' => $customer,
|
||||
'employee' => $employee,
|
||||
'shop' => $shop,
|
||||
'product' => $product,
|
||||
'builderManager' => $builderManager,
|
||||
'dispatcher' => $dispatcher,
|
||||
'tunnelService' => $tunnelService,
|
||||
'executor' => $executor,
|
||||
];
|
||||
}
|
||||
|
||||
it('persists order and lines, sends Regate mail synchronously, dispatches notifications, and returns SUCCESS', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$ctx = buildFinalizeOrderScenario(priceCents: 2000, qty: 2);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output)->toBeInstanceOf(FinalizeOrderOutput::class)
|
||||
->and($output->status)->toBe(FinalizeOrderStatus::SUCCESS)
|
||||
->and($output->orderReference)->not->toBeNull();
|
||||
|
||||
$persistedOrder = Order::query()->with('lines')->first();
|
||||
expect($persistedOrder)->not->toBeNull()
|
||||
->and($persistedOrder?->status)->toBe(OrderStatus::VALIDATED)
|
||||
->and($persistedOrder?->shop_id)->toBe($ctx['shop']->id)
|
||||
->and($persistedOrder?->lines)->toHaveCount(1);
|
||||
|
||||
Mail::assertSent(RegateOrderMail::class, 1);
|
||||
Mail::assertQueued(OrderConfirmAdminMail::class, 1);
|
||||
Notification::assertSentTo($ctx['employee'], OrderConfirmed::class);
|
||||
});
|
||||
|
||||
it('rolls back database order and rethrows when Regate export fails', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
/** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $failingRegate */
|
||||
$failingRegate = \Mockery::mock(RegateService::class);
|
||||
$failingRegate->shouldReceive('processOrder')
|
||||
->once()
|
||||
->andThrow(new RegateExportFailedException('SMTP transport failure'));
|
||||
|
||||
$ctx = buildFinalizeOrderScenario(regateService: $failingRegate);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN & THEN
|
||||
expect(fn () => $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId())))
|
||||
->toThrow(RegateExportFailedException::class);
|
||||
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
$this->assertDatabaseCount('order_lines', 0);
|
||||
Notification::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns ORDER_LIMIT_EXCEEDED and avoids persisting order when basket exceeds 200 EUR', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
// 210 EUR HT -> > 200 EUR TTC order limit
|
||||
$ctx = buildFinalizeOrderScenario(priceCents: 21000, qty: 1);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::ORDER_LIMIT_EXCEEDED)
|
||||
->and($output->orderReference)->toBeNull();
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
Mail::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns WEEKLY_LIMIT_EXCEEDED when cumulative weekly orders exceed 200 EUR', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$ctx = buildFinalizeOrderScenario(priceCents: 6000, qty: 1);
|
||||
|
||||
Order::query()->forceCreate([
|
||||
'id' => Uuid::uuid7()->toString(),
|
||||
'shop_id' => $ctx['shop']->id,
|
||||
'reference' => new OrderReference(Uuid::uuid7()),
|
||||
'status' => OrderStatus::VALIDATED->value,
|
||||
'total' => Money::EUR(16000),
|
||||
'employee' => new OrderEmployee(
|
||||
$ctx['employee']->matricule,
|
||||
$ctx['employee']->prenom,
|
||||
$ctx['employee']->nom,
|
||||
$ctx['employee']->etablissement,
|
||||
$ctx['employee']->site,
|
||||
$ctx['employee']->service,
|
||||
),
|
||||
'delivery_address' => new DeliveryAddress('Shop', '1 rue Test', '72300', 'Sablé'),
|
||||
'pickup_day' => '2026-11-20 14:00:00',
|
||||
]);
|
||||
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::WEEKLY_LIMIT_EXCEEDED);
|
||||
$this->assertDatabaseCount('orders', 1);
|
||||
Mail::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns INACTIVE_SHOPPER when linked employee end_date is in the past', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$ctx = buildFinalizeOrderScenario(activeEmployee: false);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::INACTIVE_SHOPPER);
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
Mail::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns UNORDERABLE_PRODUCT when a basket product was disabled before finalization', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$ctx = buildFinalizeOrderScenario();
|
||||
$ctx['product']->status = false;
|
||||
$ctx['product']->saveOrFail();
|
||||
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::UNORDERABLE_PRODUCT);
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
Mail::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns EXPIRED_TIME_SLOT when selected pickup date is no longer open', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
// Past Friday (2026-11-13) relative to test now (2026-11-16)
|
||||
$ctx = buildFinalizeOrderScenario(
|
||||
pickupAt: CarbonImmutable::parse('2026-11-13 14:00:00', 'Europe/Paris'),
|
||||
);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::EXPIRED_TIME_SLOT);
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
Mail::assertNothingSent();
|
||||
});
|
||||
|
||||
it('returns LOCK_TIMEOUT when lock acquisition times out inside ActionExecutorService', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
/** @var \Shared\Concurrency\Lock&\Mockery\MockInterface $lock */
|
||||
$lock = \Mockery::mock(Lock::class);
|
||||
$lock->shouldReceive('synchronize')
|
||||
->once()
|
||||
->andThrow(new LockTimeoutException('Lock timed out'));
|
||||
|
||||
$ctx = buildFinalizeOrderScenario(lock: $lock);
|
||||
$action = new FinalizeOrder($ctx['tunnelService']);
|
||||
|
||||
// WHEN
|
||||
$output = $ctx['executor']->execute($action, new FinalizeOrderInput($ctx['customer']->getId()));
|
||||
|
||||
// THEN
|
||||
expect($output->status)->toBe(FinalizeOrderStatus::LOCK_TIMEOUT)
|
||||
->and($output->orderReference)->toBeNull();
|
||||
$this->assertDatabaseCount('orders', 0);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Orders\InitializeOrderTunnel;
|
||||
use App\Cqs\Actions\Orders\InitializeOrderTunnelInput;
|
||||
use Domain\Builders\OrderBuilderWithBasket;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Domain\Models\Entities\Basket;
|
||||
use Domain\Models\ValueObjects\BasketProduct;
|
||||
use Domain\Models\ValueObjects\DiscountRate;
|
||||
use Domain\Models\ValueObjects\Entities\BasketId;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
use Domain\Models\ValueObjects\Entities\ShopperId;
|
||||
use Domain\Models\ValueObjects\IncoId;
|
||||
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\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
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\Services\EloquentEmployeeStatisticsService;
|
||||
use Infrastructure\Adapters\Services\SessionOrderBuilderManager;
|
||||
use Money\Currency;
|
||||
use Money\Money;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
describe('InitializeOrderTunnel action', function (): void {
|
||||
it('stores OrderBuilderWithBasket in session for the shopper and basket', function (): void {
|
||||
// GIVEN
|
||||
$session = Session::driver();
|
||||
$builderManager = new SessionOrderBuilderManager($session, 'order_tunnel_builder_session');
|
||||
$shopRepo = new EloquentShopRepository();
|
||||
$shopperRepo = new EloquentShopperRepository();
|
||||
$orderRepo = new EloquentOrderRepository();
|
||||
|
||||
/** @var \Domain\Ports\Services\RegateService&\Mockery\MockInterface $regateService */
|
||||
$regateService = \Mockery::mock(RegateService::class);
|
||||
|
||||
$tunnelService = new OrderTunnelService(
|
||||
new LaravelDomainEventDispatcher(),
|
||||
new ShopperService($shopRepo, $shopperRepo),
|
||||
$builderManager,
|
||||
new PickupSchedulingService(new EloquentPickupExceptionRepository()),
|
||||
$orderRepo,
|
||||
new EloquentProductRepository(),
|
||||
new CustomerOrderLimitPolicy(20000, 20000, new Currency('EUR')),
|
||||
$shopRepo,
|
||||
$shopperRepo,
|
||||
new OrderService($orderRepo),
|
||||
new EloquentEmployeeStatisticsService(),
|
||||
$regateService,
|
||||
);
|
||||
|
||||
$productId = new ProductId(Uuid::uuid7());
|
||||
$basket = new Basket(new BasketId(Uuid::uuid7()), [
|
||||
$productId->value->toString() => new BasketProduct(
|
||||
id: $productId,
|
||||
name: 'Poulet Rôti',
|
||||
qty: 2,
|
||||
unitPriceHt: Money::EUR(1200),
|
||||
unitDiscount: Money::EUR(0),
|
||||
taxRate: TaxRate::TVA_5_5,
|
||||
weightGrams: 1200,
|
||||
brand: ProductBrand::loue,
|
||||
incoId: new IncoId(123456),
|
||||
orderUnit: OrderUnit::PCE,
|
||||
slug: 'poulet-roti',
|
||||
picture: null,
|
||||
description: null,
|
||||
weightVariable: false,
|
||||
discountRate: DiscountRate::zero(),
|
||||
priceKgTtc: Money::EUR(1000),
|
||||
options: [],
|
||||
),
|
||||
]);
|
||||
$shopperId = new ShopperId(Uuid::uuid7());
|
||||
|
||||
$action = new InitializeOrderTunnel($tunnelService);
|
||||
|
||||
// WHEN
|
||||
$action(new InitializeOrderTunnelInput($basket, $shopperId));
|
||||
|
||||
// THEN
|
||||
$storedBuilder = $builderManager->get();
|
||||
expect($storedBuilder)->toBeInstanceOf(OrderBuilderWithBasket::class)
|
||||
->and($storedBuilder?->getShopperId()->equals($shopperId))->toBeTrue()
|
||||
->and($storedBuilder?->getBasket()->countItems())->toBe(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Cqs\Actions\Products\CreateProduct;
|
||||
use App\Cqs\Actions\Products\CreateProductInput;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Product;
|
||||
use App\Models\Range;
|
||||
use App\Models\Tag;
|
||||
use App\Services\ActionExecutorService;
|
||||
use App\Services\ImageOptimizerService;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Domain\Enums\ProductBrand;
|
||||
use Domain\Enums\SellUnit;
|
||||
use Domain\Enums\TaxRate;
|
||||
use Domain\Enums\Units\InvoicingUnit;
|
||||
use Domain\Enums\Units\OrderUnit;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
|
||||
use Infrastructure\Adapters\Locks\LaravelCacheLock;
|
||||
use Money\Money;
|
||||
use Psr\Log\NullLogger;
|
||||
use Shared\Filesystem\TemporaryFileFactory;
|
||||
use Uwil\Storage\Contracts\StorageService;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
function makeCreateProductRange(): Range
|
||||
{
|
||||
$range = new Range();
|
||||
$range->name = 'Gamme Produit ' . uniqid();
|
||||
$range->status = true;
|
||||
$range->order = 1;
|
||||
$range->picture_alt = 'alt';
|
||||
$range->picture_title = 'title';
|
||||
$range->saveOrFail();
|
||||
|
||||
return $range;
|
||||
}
|
||||
|
||||
describe('CreateProduct action', function (): void {
|
||||
it('creates a product with tags, associated products, and S3 pictures', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$range = makeCreateProductRange();
|
||||
|
||||
$existingTag = Tag::factory()->create([
|
||||
'label' => 'Déjà existant',
|
||||
'status' => true,
|
||||
]);
|
||||
|
||||
$associated1 = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => 'Associé 1 ' . uniqid(),
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_5_5,
|
||||
'description' => 'Desc 1',
|
||||
'status' => true,
|
||||
]);
|
||||
$associated1->price = Money::EUR(500);
|
||||
$associated1->picture_alt = 'a1';
|
||||
$associated1->picture_title = 't1';
|
||||
$associated1->picture_large_alt = 'al1';
|
||||
$associated1->picture_large_title = 'tl1';
|
||||
$associated1->saveOrFail();
|
||||
|
||||
$associated2 = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => 'Associé 2 ' . uniqid(),
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_5_5,
|
||||
'description' => 'Desc 2',
|
||||
'status' => true,
|
||||
]);
|
||||
$associated2->price = Money::EUR(700);
|
||||
$associated2->picture_alt = 'a2';
|
||||
$associated2->picture_title = 't2';
|
||||
$associated2->picture_large_alt = 'al2';
|
||||
$associated2->picture_large_title = 'tl2';
|
||||
$associated2->saveOrFail();
|
||||
|
||||
$disk = new PublicS3Disk('https://cdn.test');
|
||||
$picturePath = new StorageFilePath('products/create-pic.jpg');
|
||||
$largePath = new StorageFilePath('products/create-large.jpg');
|
||||
|
||||
/** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */
|
||||
$storage = \Mockery::mock(StorageService::class);
|
||||
$storage->shouldReceive('storeFileOntoDisk')
|
||||
->twice()
|
||||
->andReturn($picturePath, $largePath);
|
||||
$storage->shouldNotReceive('removeFromDisk');
|
||||
|
||||
$action = new CreateProduct(
|
||||
$storage,
|
||||
$disk,
|
||||
new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()),
|
||||
);
|
||||
|
||||
$orderableStart = CarbonImmutable::parse('2026-11-01 08:00:00');
|
||||
$orderableEnd = CarbonImmutable::parse('2026-12-31 20:00:00');
|
||||
|
||||
$input = new CreateProductInput(
|
||||
name: 'Poulet Fermier Bio',
|
||||
shortDescription: 'Courte description',
|
||||
description: '<p>Description complète</p>',
|
||||
price: Money::EUR(1990),
|
||||
invoicingUnit: InvoicingUnit::KGM,
|
||||
stock: 15,
|
||||
rangeId: $range->id,
|
||||
sellUnit: SellUnit::PCE,
|
||||
orderUnit: OrderUnit::COLIS,
|
||||
taxRate: TaxRate::TVA_5_5,
|
||||
brand: ProductBrand::loue,
|
||||
weight: 1400,
|
||||
weightVariable: true,
|
||||
orderableStart: $orderableStart,
|
||||
orderableEnd: $orderableEnd,
|
||||
star: true,
|
||||
status: true,
|
||||
picture: UploadedFile::fake()->image('pic.jpg', 300, 300),
|
||||
pictureAlt: 'Alt pic',
|
||||
pictureTitle: 'Title pic',
|
||||
pictureLarge: UploadedFile::fake()->image('large.jpg', 800, 800),
|
||||
pictureLargeAlt: 'Alt large',
|
||||
pictureLargeTitle: 'Title large',
|
||||
tags: [
|
||||
['id' => $existingTag->id, 'label' => $existingTag->label],
|
||||
['label' => 'Nouveau Tag Bio'],
|
||||
],
|
||||
associatedProductsIds: [$associated2->id, $associated1->id],
|
||||
);
|
||||
|
||||
$executor = new ActionExecutorService(
|
||||
new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
new LaravelDomainEventDispatcher(),
|
||||
);
|
||||
|
||||
// WHEN
|
||||
$product = $executor->execute($action, $input);
|
||||
|
||||
// THEN
|
||||
expect($product)->toBeInstanceOf(Product::class)
|
||||
->and($product->name)->toBe('Poulet Fermier Bio')
|
||||
->and($product->price->getAmount())->toBe('1990')
|
||||
->and($product->stock)->toBe(15)
|
||||
->and($product->weight)->toBe(1400)
|
||||
->and($product->weight_variable)->toBeTrue()
|
||||
->and($product->star)->toBeTrue()
|
||||
->and($product->status)->toBeTrue()
|
||||
->and($product->picture?->value)->toBe('products/create-pic.jpg')
|
||||
->and($product->picture_large?->value)->toBe('products/create-large.jpg')
|
||||
->and($product->tags()->pluck('label')->all())->toBe(['Déjà existant', 'Nouveau Tag Bio']);
|
||||
|
||||
$associatedOrder = $product->products
|
||||
->pluck('id')
|
||||
->all();
|
||||
expect($associatedOrder)->toBe([$associated2->id, $associated1->id]);
|
||||
|
||||
$this->assertDatabaseHas('products', [
|
||||
'id' => $product->id,
|
||||
'name' => 'Poulet Fermier Bio',
|
||||
'range_id' => $range->id,
|
||||
]);
|
||||
});
|
||||
|
||||
it('cleans up uploaded S3 files when persistence fails inside executor transaction', function (): void {
|
||||
/** @var \Tests\TestCase $this */
|
||||
// GIVEN
|
||||
$disk = new PublicS3Disk('https://cdn.test');
|
||||
$orphanPic = new StorageFilePath('products/orphan-pic.jpg');
|
||||
$orphanLarge = new StorageFilePath('products/orphan-large.jpg');
|
||||
|
||||
/** @var \Uwil\Storage\Contracts\StorageService&\Mockery\MockInterface $storage */
|
||||
$storage = \Mockery::mock(StorageService::class);
|
||||
$storage->shouldReceive('storeFileOntoDisk')
|
||||
->twice()
|
||||
->andReturn($orphanPic, $orphanLarge);
|
||||
$storage->shouldReceive('fileExistsOnDisk')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk)
|
||||
->andReturnTrue();
|
||||
$storage->shouldReceive('removeFromDisk')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-pic.jpg'), $disk->disk)
|
||||
->andReturnTrue();
|
||||
$storage->shouldReceive('fileExistsOnDisk')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk)
|
||||
->andReturnTrue();
|
||||
$storage->shouldReceive('removeFromDisk')
|
||||
->once()
|
||||
->with(\Mockery::on(static fn (mixed $p): bool => $p instanceof StorageFilePath && $p->value === 'products/orphan-large.jpg'), $disk->disk)
|
||||
->andReturnTrue();
|
||||
|
||||
$action = new CreateProduct(
|
||||
$storage,
|
||||
$disk,
|
||||
new ImageOptimizerService(new TemporaryFileFactory(), new NullLogger()),
|
||||
);
|
||||
|
||||
// Non-existent rangeId triggers FK constraint violation on saveOrFail()
|
||||
$input = new CreateProductInput(
|
||||
name: 'Produit Échec FK',
|
||||
shortDescription: 'Court',
|
||||
description: 'Description',
|
||||
price: Money::EUR(1000),
|
||||
invoicingUnit: InvoicingUnit::PCE,
|
||||
stock: 1,
|
||||
rangeId: 999999,
|
||||
sellUnit: SellUnit::PCE,
|
||||
orderUnit: OrderUnit::PCE,
|
||||
taxRate: TaxRate::TVA_20,
|
||||
brand: ProductBrand::loue,
|
||||
picture: UploadedFile::fake()->image('pic.jpg', 200, 200),
|
||||
pictureAlt: 'alt',
|
||||
pictureTitle: 'title',
|
||||
pictureLarge: UploadedFile::fake()->image('large.jpg', 400, 400),
|
||||
pictureLargeAlt: 'alt large',
|
||||
pictureLargeTitle: 'title large',
|
||||
);
|
||||
|
||||
$executor = new ActionExecutorService(
|
||||
new LaravelCacheLock(new Repository(new ArrayStore())),
|
||||
new NullLogger(),
|
||||
new LaravelDomainEventDispatcher(),
|
||||
);
|
||||
|
||||
// WHEN & THEN
|
||||
expect(fn () => $executor->execute($action, $input))
|
||||
->toThrow(QueryException::class);
|
||||
|
||||
$this->assertDatabaseMissing('products', [
|
||||
'name' => 'Produit Échec FK',
|
||||
]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue