ldc-cocotte/app/Cqs/Actions/Customers/RegisterCustomer.php

219 lines
7.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Cqs\Actions\Customers;
use App\Attributes\Locked;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Contracts\HandlesFailure;
use App\Contracts\HandlesLockTimeout;
use App\Contracts\HandlesSuccess;
use App\Contracts\ProvidesLockKey;
use App\Enums\RegisterCustomerStatus;
use App\Exceptions\Crm\CrmCustomerExistsException;
use App\Exceptions\CrmServiceException;
use App\Models\Customer;
use App\Models\Employee;
use App\Services\CrmService;
use Domain\Enums\Country;
use Domain\Models\ValueObjects\CrmCustomer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
use Ramsey\Uuid\Uuid;
use Shared\ValueObjects\CrmHashcode;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
* >
* @implements \App\Contracts\ProvidesLockKey<\App\Cqs\Actions\Customers\RegisterCustomerInput>
* @implements \App\Contracts\HandlesLockTimeout<
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
* >
* @implements \App\Contracts\HandlesSuccess<
* \App\Cqs\Actions\Customers\RegisterCustomerInput,
* \App\Cqs\Actions\Customers\RegisterCustomerOutput
* >
* @implements \App\Contracts\HandlesFailure<\App\Cqs\Actions\Customers\RegisterCustomerInput>
*/
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey
{
/** @var array<int, array{hashcode: \Shared\ValueObjects\CrmHashcode, email: \Domain\Models\ValueObjects\Email}> */
private array $createdCrmCustomers = [];
public function __construct(
private readonly AppCustomerAuthService $authService,
private readonly CrmService $crmService,
) {
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function lockKey(ActionInput $input): string
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
return "customer:register:employee:{$input->matricule->value}";
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function onLockTimeout(ActionInput $input): RegisterCustomerOutput
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
return RegisterCustomerOutput::lockTimeout();
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*
* @throws ValidationException
* @throws \UnexpectedValueException
* @throws ModelNotFoundException
*/
#[\Override]
public function __invoke(ActionInput $input): RegisterCustomerOutput
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
$inputKey = spl_object_id($input);
unset($this->createdCrmCustomers[$inputKey]);
$employee = Employee::query()
->where('matricule', $input->matricule->value)
->where('code', $input->code->value)
->lockForUpdate()
->first();
if (! $employee) {
throw new ModelNotFoundException('Employee not found');
}
if ($employee->customer_id !== null) {
return RegisterCustomerOutput::employeeAlreadyRegistered();
}
if (! $employee->is_active) {
return RegisterCustomerOutput::employeeInactive();
}
// * Persist and associate Customer + Employee
$customer = new Customer([
'email' => $input->email,
]);
// * Temp hashcode to satisfy constraint
$customer->hashcode = new CrmHashcode(Uuid::uuid4());
$customer->saveOrFail();
$employee->customer()->associate($customer);
$employee->saveOrFail();
$crmCustomer = new CrmCustomer(
hashcode: null,
email: $input->email->value,
password: $input->password,
firstname: $input->firstname,
lastname: $input->lastname,
birthDate: $input->birthDate->format('Y-m-d'),
phone: $input->phone?->value,
address: $input->address,
address2: null,
city: $input->city,
postcode: $input->postcode,
country: Country::france,
optIn: $input->optIn,
status: false,
lastConnection: null,
);
try {
$result = $this->crmService->persist($crmCustomer);
} catch (CrmCustomerExistsException) {
throw ValidationException::withMessages([
'error' => trans('An account is already associated with this email address'),
]);
} catch (CrmServiceException $e) {
report($e);
throw ValidationException::withMessages([
'error' => trans('An error has occurred. Please try again later'),
]);
}
if (! $result->hashcode) {
throw new \UnexpectedValueException(
'CRM did not return a hashcode for the created customer'
);
}
$crmHashcode = CrmHashcode::fromString($result->hashcode);
$this->createdCrmCustomers[$inputKey] = [
'hashcode' => $crmHashcode,
'email' => $input->email,
];
$customer->hashcode = $crmHashcode;
$customer->saveOrFail();
return RegisterCustomerOutput::success($customer);
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
* @param \App\Cqs\Actions\Customers\RegisterCustomerOutput $result
*/
#[\Override]
public function onSuccess(ActionInput $input, mixed $result): void
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
Assert::isInstanceOf($result, RegisterCustomerOutput::class);
unset($this->createdCrmCustomers[spl_object_id($input)]);
if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) {
return;
}
$this->authService->logIn($result->customer);
try {
$result->customer->sendEmailVerificationNotification();
} catch (\Throwable $e) {
report($e);
}
}
/**
* @param \App\Cqs\Actions\Customers\RegisterCustomerInput $input
*/
#[\Override]
public function onFailure(ActionInput $input, \Throwable $exception): void
{
Assert::isInstanceOf($input, RegisterCustomerInput::class);
$inputKey = spl_object_id($input);
$createdCrm = $this->createdCrmCustomers[$inputKey] ?? null;
unset($this->createdCrmCustomers[$inputKey]);
if ($createdCrm === null) {
return;
}
try {
$this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']);
} catch (\Throwable $e) {
report($e);
}
}
}