ldc-cocotte/tests/Integration/WithApp/App/Cqs/Actions/Customers/RegisterCustomerTest.php

761 lines
27 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Cqs\Actions\Customers;
use App\Contracts\ActionInput;
use App\Contracts\Executor;
use App\Cqs\Actions\Customers\RegisterCustomer;
use App\Cqs\Actions\Customers\RegisterCustomerInput;
use App\Enums\RegisterCustomerStatus;
use App\Exceptions\Crm\CrmCustomerExistsException;
use App\Exceptions\CrmServiceException;
use App\Models\Customer;
use App\Models\Employee;
use App\Services\ActionExecutorService;
use App\Services\CrmService;
use Domain\Enums\Country;
use Domain\Models\ValueObjects\Code;
use Domain\Models\ValueObjects\CrmCustomer;
use Domain\Models\ValueObjects\Email;
use Domain\Models\ValueObjects\Matricule;
use Domain\Models\ValueObjects\PhoneNumber;
use Domain\Models\ValueObjects\ShopperEstablishmentCode;
use Domain\Models\ValueObjects\ShopperServiceCode;
use Domain\Models\ValueObjects\ShopperSiteCode;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Validation\ValidationException;
use Infrastructure\Adapters\Events\LaravelDomainEventDispatcher;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
use Psr\Log\NullLogger;
use Shared\Concurrency\Lock;
use Shared\Concurrency\LockTimeoutException;
use Shared\Helpers\UuidHelper;
use Shared\ValueObjects\CrmHashcode;
describe('RegisterCustomer action', function (): void {
beforeEach(function (): void {
Notification::fake();
});
it('registers and associates a customer successfully', function (): void {
// GIVEN
$matricule = new Matricule('1234567');
$code = new Code('ABCDEF');
$email = new Email('john.doe@example.com');
$birthDate = new \DateTimeImmutable('1990-01-01');
$phone = new PhoneNumber('+33612345678');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Doe';
$employee->prenom = 'John';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmReturnedHashcode = UuidHelper::v4()->toString();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')
->once()
->withArgs(function (CrmCustomer $crmCust) use ($email): bool {
return $crmCust->email === $email->value
&& $crmCust->firstname === 'John'
&& $crmCust->lastname === 'Doe'
&& $crmCust->city === 'Paris'
&& $crmCust->country === Country::france;
})
->andReturn(new CrmCustomer(
hashcode: $crmReturnedHashcode,
email: $email->value,
password: null,
firstname: 'John',
lastname: 'Doe',
birthDate: '1990-01-01',
phone: '+33612345678',
address: '10 rue de Paris',
address2: null,
city: 'Paris',
postcode: '75001',
country: Country::france,
optIn: true,
status: false,
lastConnection: null,
));
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldReceive('logIn')
->once()
->withArgs(fn (Customer $c) => $c->email->value === $email->value);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'John',
lastname: 'Doe',
email: $email,
password: 'secretPassword123!',
birthDate: $birthDate,
phone: $phone,
address: '10 rue de Paris',
postcode: '75001',
city: 'Paris',
optIn: true,
);
// WHEN
$result = $action($input);
// THEN: __invoke defers email verification and login to onSuccess()
expect($result->status)->toBe(RegisterCustomerStatus::SUCCESS)
->and($result->customer)->toBeInstanceOf(Customer::class)
->and($result->customer?->email->value)->toBe('john.doe@example.com')
->and($result->customer?->hashcode->value)->toBe($crmReturnedHashcode);
Notification::assertNothingSent();
$action->onSuccess($input, $result);
Notification::assertSentTo($result->customer, VerifyEmail::class);
$freshEmployee = Employee::query()->find($employee->id);
expect($freshEmployee?->customer_id)->toBe($result->customer?->id);
});
it('returns EMPLOYEE_ALREADY_REGISTERED when employee already has a customer_id', function (): void {
// GIVEN
$existingCustomer = new Customer(['email' => new Email('already@example.com')]);
$existingCustomer->hashcode = new CrmHashcode(UuidHelper::v4());
$existingCustomer->saveOrFail();
$matricule = new Matricule('5678901');
$code = new Code('FGHJKM');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Already';
$employee->prenom = 'Registered';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->customer()->associate($existingCustomer);
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldNotReceive('persist');
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldNotReceive('logIn');
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'New',
lastname: 'User',
email: new Email('new.user@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN
$result = $action($input);
// THEN
expect($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_ALREADY_REGISTERED)
->and($result->customer)->toBeNull()
->and(Customer::query()->count())->toBe(1);
$freshEmployee = Employee::query()->find($employee->id);
expect($freshEmployee?->customer_id)->toBe($existingCustomer->id);
});
it('returns EMPLOYEE_INACTIVE when employee contract has ended', function (): void {
// GIVEN
Date::setTestNow(Date::parse('2026-06-15 10:00:00', 'Europe/Paris'));
try {
$matricule = new Matricule('5678902');
$code = new Code('FGHJK2');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Inactive';
$employee->prenom = 'User';
$employee->end_date = Carbon::parse('2026-06-15');
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldNotReceive('persist');
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldNotReceive('logIn');
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Inactive',
lastname: 'User',
email: new Email('inactive.user@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN
$result = $action($input);
// THEN
expect($result)
->and($result->status)->toBe(RegisterCustomerStatus::EMPLOYEE_INACTIVE)
->and($result->customer)->toBeNull()
->and(Customer::query()->count())->toBe(0);
} finally {
Date::setTestNow();
}
});
it('throws ModelNotFoundException when employee does not exist', function (): void {
// GIVEN
$crmService = \Mockery::mock(CrmService::class);
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: new Matricule('9999999'),
code: new Code('ABCDYZ'), // no I, L, O, V in Code VO
firstname: 'John',
lastname: 'Doe',
email: new Email('ghost@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN & THEN
expect(fn () => $action($input))->toThrow(ModelNotFoundException::class);
});
it('throws ValidationException when CRM indicates customer already exists', function (): void {
// GIVEN
$matricule = new Matricule('2345678');
$code = new Code('BCDEFG');
$email = new Email('existing@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Existing';
$employee->prenom = 'User';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')
->once()
->andThrow(new CrmCustomerExistsException());
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'User',
lastname: 'Existing',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN & THEN
expect(fn () => $action($input))->toThrow(ValidationException::class);
});
it('throws ValidationException when CRM fails with CrmServiceException', function (): void {
// GIVEN
$matricule = new Matricule('3456789');
$code = new Code('CDEFGH');
$email = new Email('crmerror@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Error';
$employee->prenom = 'Crm';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')
->once()
->andThrow(CrmServiceException::of('CRM service offline'));
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Crm',
lastname: 'Error',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN & THEN
expect(fn () => $action($input))->toThrow(ValidationException::class);
});
it('throws UnexpectedValueException when CRM returns no hashcode', function (): void {
// GIVEN
$matricule = new Matricule('4567890');
$code = new Code('DEFGHJ');
$email = new Email('nohash@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'No';
$employee->prenom = 'Hash';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')
->once()
->andReturn(new CrmCustomer(
hashcode: null,
email: $email->value,
password: null,
firstname: 'Hash',
lastname: 'No',
birthDate: '1990-01-01',
phone: null,
address: null,
address2: null,
city: 'Paris',
postcode: '75001',
country: Country::france,
optIn: false,
status: false,
lastConnection: null,
));
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Hash',
lastname: 'No',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN & THEN
expect(fn () => $action($input))->toThrow(\UnexpectedValueException::class);
});
it('throws when invalid ActionInput is passed', function (): void {
// GIVEN
$crmService = \Mockery::mock(CrmService::class);
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$invalidInput = new class () implements ActionInput
{
};
/** @var \Closure(\App\Contracts\ActionInput): mixed $callable */
$callable = \Closure::fromCallable($action);
// WHEN & THEN
expect(fn () => $callable($invalidInput))->toThrow(\InvalidArgumentException::class);
});
it('acquires matricule lock via ActionExecutorService and returns LOCK_TIMEOUT when lock fails', function (): void {
// GIVEN
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldNotReceive('persist');
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: new Matricule('1234567'),
code: new Code('ABCDEF'),
firstname: 'John',
lastname: 'Doe',
email: new Email('john.doe@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
/** @var Lock&\Mockery\MockInterface $lock */
$lock = \Mockery::mock(Lock::class);
$lock->shouldReceive('synchronize')
->once()
->with('customer:register:employee:1234567', \Mockery::type(\Closure::class), 30, 10)
->andThrow(new LockTimeoutException('Lock timed out'));
$executor = new ActionExecutorService(
$lock,
new NullLogger(),
new LaravelDomainEventDispatcher(),
);
// WHEN
$output = $executor->execute($action, $input);
// THEN
expect($output)
->and($output->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT);
});
it('builds lockKey from input matricule', function (): void {
// GIVEN
$crmService = \Mockery::mock(CrmService::class);
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: new Matricule('1234567'),
code: new Code('ABCDEF'),
firstname: 'John',
lastname: 'Doe',
email: new Email('john.doe@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN
$key = $action->lockKey($input);
// THEN
expect($key)->toBe('customer:register:employee:1234567');
});
it('returns lockTimeout output on lock timeout', function (): void {
// GIVEN
$crmService = \Mockery::mock(CrmService::class);
$authService = \Mockery::mock(AppCustomerAuthService::class);
$action = new RegisterCustomer(
authService: $authService,
crmService: $crmService,
);
$input = new RegisterCustomerInput(
matricule: new Matricule('1234567'),
code: new Code('ABCDEF'),
firstname: 'John',
lastname: 'Doe',
email: new Email('john.doe@example.com'),
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN
$result = $action->onLockTimeout($input);
// THEN
expect($result)
->and($result->status)->toBe(RegisterCustomerStatus::LOCK_TIMEOUT)
->and($result->customer)->toBeNull()
->and($result->errorMessage)->toBeNull();
});
it('executes post-commit verification email and login only after commit via Executor', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$matricule = new Matricule('6789012');
$code = new Code('MNPQRS');
$email = new Email('postcommit@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Commit';
$employee->prenom = 'Post';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmReturnedHashcode = UuidHelper::v4()->toString();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')->once()->andReturn(new CrmCustomer(
hashcode: $crmReturnedHashcode,
email: $email->value,
password: null,
firstname: 'Post',
lastname: 'Commit',
birthDate: '1990-01-01',
phone: null,
address: null,
address2: null,
city: 'Paris',
postcode: '75001',
country: Country::france,
optIn: false,
status: false,
lastConnection: null,
));
$crmService->shouldNotReceive('deleteByHashcode');
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldReceive('logIn')
->once()
->withArgs(fn (Customer $c): bool => $c->email->value === $email->value);
$action = new RegisterCustomer($authService, $crmService);
$executor = $this->app->make(Executor::class);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Post',
lastname: 'Commit',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN
$result = $executor->execute($action, $input);
// THEN
expect($result->status)->toBe(RegisterCustomerStatus::SUCCESS)
->and($result->customer)->toBeInstanceOf(Customer::class);
Notification::assertSentTo($result->customer, VerifyEmail::class);
});
it('compensates CRM customer via deleteByHashcode when local persistence fails after CRM creation', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$matricule = new Matricule('7890123');
$code = new Code('NPQRST');
$email = new Email('splitbrain@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Brain';
$employee->prenom = 'Split';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmUuid = UuidHelper::v4();
$crmReturnedHashcode = $crmUuid->toString();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')->once()->andReturn(new CrmCustomer(
hashcode: $crmReturnedHashcode,
email: $email->value,
password: null,
firstname: 'Split',
lastname: 'Brain',
birthDate: '1990-01-01',
phone: null,
address: null,
address2: null,
city: 'Paris',
postcode: '75001',
country: Country::france,
optIn: false,
status: false,
lastConnection: null,
));
$crmService->shouldReceive('deleteByHashcode')
->once()
->withArgs(
fn (CrmHashcode $hash, ?Email $deletedEmail): bool => $hash->value === $crmReturnedHashcode
&& $deletedEmail?->value === $email->value
)
->andReturnTrue();
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldNotReceive('logIn');
$action = new RegisterCustomer($authService, $crmService);
$executor = $this->app->make(Executor::class);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Split',
lastname: 'Brain',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
Event::listen('eloquent.updating: ' . Customer::class, static function (): void {
throw new \RuntimeException('Simulated DB error after CRM persist');
});
// WHEN & THEN
try {
expect(fn () => $executor->execute($action, $input))
->toThrow(\RuntimeException::class, 'Simulated DB error after CRM persist');
} finally {
Event::forget('eloquent.updating: ' . Customer::class);
}
expect(Customer::query()->count())->toBe(0)
->and($employee->fresh()?->customer_id)->toBeNull();
Notification::assertNothingSent();
});
it('does not call deleteByHashcode on failure when CRM creation did not succeed', function (): void {
/** @var \Tests\TestCase $this */
// GIVEN
$matricule = new Matricule('8901234');
$code = new Code('PQRSTU');
$email = new Email('already-crm@example.com');
$employee = new Employee();
$employee->matricule = $matricule;
$employee->code = $code;
$employee->nom = 'Exists';
$employee->prenom = 'Crm';
$employee->etablissement = new ShopperEstablishmentCode('ETAB01');
$employee->site = new ShopperSiteCode('SITE');
$employee->service = new ShopperServiceCode('1');
$employee->saveOrFail();
$crmService = \Mockery::mock(CrmService::class);
$crmService->shouldReceive('persist')->once()->andThrow(new CrmCustomerExistsException());
$crmService->shouldNotReceive('deleteByHashcode');
$authService = \Mockery::mock(AppCustomerAuthService::class);
$authService->shouldNotReceive('logIn');
$action = new RegisterCustomer($authService, $crmService);
$executor = $this->app->make(Executor::class);
$input = new RegisterCustomerInput(
matricule: $matricule,
code: $code,
firstname: 'Crm',
lastname: 'Exists',
email: $email,
password: 'secretPassword123!',
birthDate: new \DateTimeImmutable('1990-01-01'),
phone: null,
address: null,
postcode: '75001',
city: 'Paris',
);
// WHEN & THEN
expect(fn () => $executor->execute($action, $input))
->toThrow(ValidationException::class);
expect(Customer::query()->count())->toBe(0)
->and($employee->fresh()?->customer_id)->toBeNull();
Notification::assertNothingSent();
});
});