From 2aa4fa8aed3f675acf5239982317348fdf64b7e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 29 Sep 2026 17:36:41 +0200 Subject: [PATCH] feat(crm): implement unsubscribe from newsletter functionality - Added UnsubscribeFromNewsletter action and input/output classes. - Introduced CrmHashcode value object and its cast. - Updated NewsletterController to use the new unsubscribe action. - Enhanced validation in UnsubscribeNewsletterRequest. --- app/Actions/Crm/UnsubscribeFromNewsletter.php | 39 ++++++++++++++++++ .../Crm/UnsubscribeFromNewsletterInput.php | 16 ++++++++ .../Crm/UnsubscribeFromNewsletterOutput.php | 12 ++++++ app/Casts/CrmHashcodeCast.php | 41 +++++++++++++++++++ .../Controllers/Fo/NewsletterController.php | 37 +++++++++-------- .../Fo/UnsubscribeNewsletterRequest.php | 25 +++++------ app/Models/Customer.php | 6 ++- app/Services/CrmService.php | 17 ++++---- app/Services/CustomerRegistrationService.php | 7 ++-- shared/Exceptions/InvalidUuidException.php | 13 ++++++ shared/Helpers/UuidHelper.php | 37 +++++++++++++++++ shared/ValueObjects/CrmHashcode.php | 29 +++++++++++++ 12 files changed, 234 insertions(+), 45 deletions(-) create mode 100644 app/Actions/Crm/UnsubscribeFromNewsletter.php create mode 100644 app/Actions/Crm/UnsubscribeFromNewsletterInput.php create mode 100644 app/Actions/Crm/UnsubscribeFromNewsletterOutput.php create mode 100644 app/Casts/CrmHashcodeCast.php create mode 100644 shared/Exceptions/InvalidUuidException.php create mode 100644 shared/ValueObjects/CrmHashcode.php diff --git a/app/Actions/Crm/UnsubscribeFromNewsletter.php b/app/Actions/Crm/UnsubscribeFromNewsletter.php new file mode 100644 index 00000000..a317ba90 --- /dev/null +++ b/app/Actions/Crm/UnsubscribeFromNewsletter.php @@ -0,0 +1,39 @@ + + */ +final class UnsubscribeFromNewsletter implements Action +{ + public function __construct( + private readonly CrmService $crmService + ) { + } + + #[\Override] + public function __invoke(ActionInput $input): UnsubscribeFromNewsletterOutput + { + Assert::isInstanceOf($input, UnsubscribeFromNewsletterInput::class); + + try { + $isUnsubscribed = $this->crmService->unsubscribeCustomer( + $input->hashcode + ); + + return $isUnsubscribed ? UnsubscribeFromNewsletterOutput::SUCCESS : UnsubscribeFromNewsletterOutput::FAILURE; + } catch (\Throwable $e) { + report($e); + + return UnsubscribeFromNewsletterOutput::FAILURE; + } + } +} diff --git a/app/Actions/Crm/UnsubscribeFromNewsletterInput.php b/app/Actions/Crm/UnsubscribeFromNewsletterInput.php new file mode 100644 index 00000000..00f2d1e8 --- /dev/null +++ b/app/Actions/Crm/UnsubscribeFromNewsletterInput.php @@ -0,0 +1,16 @@ + */ +class CrmHashcodeCast implements CastsAttributes +{ + /** @param array $attributes */ + public function get(Model $model, string $key, $value, array $attributes): CrmHashcode + { + + if ($value === null || ! is_string($value)) { + throw new \UnexpectedValueException('CrmHashcode must be a string.'); + } + + $uuid = Uuid::fromString($value); + + return new CrmHashcode($uuid); + } + + /** @param array $attributes */ + public function set(Model $model, string $key, $value, array $attributes): string + { + if ($value === null) { + throw new \InvalidArgumentException('CrmHashcode cannot be null.'); + } + + if (! ($value instanceof CrmHashcode)) { + throw new \InvalidArgumentException('The given value is not an instance of CrmHashcode.'); + } + + return $value->value; + } +} diff --git a/app/Http/Controllers/Fo/NewsletterController.php b/app/Http/Controllers/Fo/NewsletterController.php index c9bc2336..b302ca0f 100644 --- a/app/Http/Controllers/Fo/NewsletterController.php +++ b/app/Http/Controllers/Fo/NewsletterController.php @@ -4,36 +4,39 @@ declare(strict_types=1); namespace App\Http\Controllers\Fo; +use App\Actions\Crm\UnsubscribeFromNewsletter; +use App\Actions\Crm\UnsubscribeFromNewsletterInput; +use App\Actions\Crm\UnsubscribeFromNewsletterOutput; +use App\Contracts\Executor; use App\Http\Requests\Fo\UnsubscribeNewsletterRequest; -use App\Services\CrmService; use Illuminate\Contracts\View\View; class NewsletterController { public function __construct( - private readonly CrmService $crmService + private readonly Executor $executor, ) { } - public function unsubscribe(UnsubscribeNewsletterRequest $request): View + public function unsubscribe(UnsubscribeNewsletterRequest $request, UnsubscribeFromNewsletter $action): View { - try { - $isUnsubscribed = false; + $isUnsubscribed = UnsubscribeFromNewsletterOutput::INVALIDLINK; - if ($request->getHashcode()) { - $isUnsubscribed = $this->crmService->unsubscribeCustomer( - $request->getHashcode() - ); - } - - $message = $isUnsubscribed - ? trans('Your newsletter unsubscription has been taken into account.') - : trans('The unsubscription link is invalid.'); - } catch (\Throwable $e) { - report($e); - $message = trans('An error occurred, please try again later.'); + if ($request->getHashcode()) { + $isUnsubscribed = $this->executor->execute( + $action, + new UnsubscribeFromNewsletterInput( + hashcode: $request->getHashcode() + ) + ); } + $message = match ($isUnsubscribed) { + UnsubscribeFromNewsletterOutput::SUCCESS => trans('Your newsletter unsubscription has been taken into account.'), + UnsubscribeFromNewsletterOutput::FAILURE => trans('An error occurred, please try again later.'), + UnsubscribeFromNewsletterOutput::INVALIDLINK => trans('The unsubscription link is invalid.'), + }; + return view('fo.news.singleoptin-unsubscribe', compact('message')); } } diff --git a/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php b/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php index d1daa782..c44703c6 100644 --- a/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php +++ b/app/Http/Requests/Fo/UnsubscribeNewsletterRequest.php @@ -4,13 +4,12 @@ declare(strict_types=1); namespace App\Http\Requests\Fo; -use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; +use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; class UnsubscribeNewsletterRequest extends FormRequest { - private bool $validated = false; - /** @return array */ public function rules(): array { @@ -19,20 +18,16 @@ class UnsubscribeNewsletterRequest extends FormRequest ]; } - public function getHashcode(): ?string + public function getHashcode(): ?CrmHashcode { - return $this->validated ? $this->string('hashcode')->value() : null; - } + $hashcode = null; - #[\Override] - protected function passedValidation() - { - $this->validated = true; - } + $this->string('hashcode')->whenIsUuid( + function (string $value) use (&$hashcode) { + $hashcode = new CrmHashcode(Uuid::fromString($value)); + } + ); - #[\Override] - protected function failedValidation(Validator $validator) - { - $this->validated = false; + return $hashcode; } } diff --git a/app/Models/Customer.php b/app/Models/Customer.php index d8d109f6..591fd0bb 100644 --- a/app/Models/Customer.php +++ b/app/Models/Customer.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Models; +use App\Casts\CrmHashcodeCast; use App\Casts\EmailCast; use App\Traits\Models\HasUuidV7AsPrimaryKey; use Domain\Contracts\CustomerDetails; @@ -18,7 +19,7 @@ use Ramsey\Uuid\Uuid; /** * @property string $id * @property \Domain\Models\ValueObjects\Email $email - * @property string $hashcode + * @property \Shared\ValueObjects\CrmHashcode $hashcode * @property string|null $remember_token * @property \Carbon\CarbonInterface|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at @@ -43,6 +44,7 @@ class Customer extends Authenticatable implements CustomerDetails, MustVerifyEma { return [ 'email' => EmailCast::class, + 'hashcode' => CrmHashcodeCast::class, 'last_login_at' => 'datetime', ]; } @@ -50,7 +52,7 @@ class Customer extends Authenticatable implements CustomerDetails, MustVerifyEma #[\Override] public function getAuthPassword(): string { - return $this->hashcode; + return $this->hashcode->value; } #[\Override] diff --git a/app/Services/CrmService.php b/app/Services/CrmService.php index d66ba17c..0572f7d4 100644 --- a/app/Services/CrmService.php +++ b/app/Services/CrmService.php @@ -23,6 +23,7 @@ use LDC\LDCCRM\Exceptions\ApiErrorException; use LDC\LDCCRM\Exceptions\CrmException; use LDC\LDCCRM\Exceptions\ValidationException; use LDC\LDCCRM\Models\Customer; +use Shared\ValueObjects\CrmHashcode; use UnexpectedValueException; class CrmService @@ -169,7 +170,7 @@ class CrmService if (! $crmCustomer instanceof CrmCustomer) { throw $crmCustomer instanceof \Throwable ? $crmCustomer - : new UnexpectedValueException('CRM customer not found for hashcode: ' . $customer->hashcode); + : new UnexpectedValueException('CRM customer not found for hashcode: ' . (string) $customer->hashcode); } $updatedData = [ @@ -197,7 +198,7 @@ class CrmService } } - public function unsubscribeCustomer(string $hashcode): bool + public function unsubscribeCustomer(CrmHashcode $hashcode): bool { $crmCustomer = $this->getCustomerFromHashCode($hashcode); @@ -221,13 +222,13 @@ class CrmService } } - public function getCustomerFromHashCode(string $hashcode): null | CrmCustomer | CrmServiceException + public function getCustomerFromHashCode(CrmHashcode $hashcode): null | CrmCustomer | CrmServiceException { - if (array_key_exists($hashcode, $this->customerByHashcodeCache)) { - return $this->customerByHashcodeCache[$hashcode]; + if (array_key_exists($hashcode->value, $this->customerByHashcodeCache)) { + return $this->customerByHashcodeCache[$hashcode->value]; } - $cacheKey = $this->getCustomerHashcodeCacheKey($hashcode); + $cacheKey = $this->getCustomerHashcodeCacheKey($hashcode->value); /** @var null|CrmCustomer|CrmServiceException $result */ $result = $this->cacheRepository->remember( @@ -235,7 +236,7 @@ class CrmService now()->addMinutes(15), function () use ($hashcode): null | CrmCustomer | CrmServiceException { try { - $customer = $this->crmApi->getCustomer($hashcode); + $customer = $this->crmApi->getCustomer($hashcode->value); return $customer ? $this->toAppCrmCustomer($customer) : @@ -250,7 +251,7 @@ class CrmService } ); - $this->customerByHashcodeCache[$hashcode] = $result; + $this->customerByHashcodeCache[$hashcode->value] = $result; return $result; } diff --git a/app/Services/CustomerRegistrationService.php b/app/Services/CustomerRegistrationService.php index a79e3ba0..0657c890 100644 --- a/app/Services/CustomerRegistrationService.php +++ b/app/Services/CustomerRegistrationService.php @@ -16,9 +16,10 @@ use Domain\Models\ValueObjects\Matricule; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Infrastructure\Adapters\Services\AppCustomerAuthService; +use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; use UnexpectedValueException; class CustomerRegistrationService @@ -60,7 +61,7 @@ class CustomerRegistrationService 'email' => new Email($data['email']), ]); // * Temp hashcode to satisfy constraint - $customer->hashcode = Str::uuid()->toString(); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); $customer->saveOrFail(); $employee = $this->employeeRepository @@ -105,7 +106,7 @@ class CustomerRegistrationService 'CRM did not return a hashcode for the created customer' ); } - $customer->hashcode = $result->hashcode; + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); $customer->saveOrFail(); $customer->sendEmailVerificationNotification(); diff --git a/shared/Exceptions/InvalidUuidException.php b/shared/Exceptions/InvalidUuidException.php new file mode 100644 index 00000000..80317449 --- /dev/null +++ b/shared/Exceptions/InvalidUuidException.php @@ -0,0 +1,13 @@ +toString())) { + throw InvalidUuidException::forValue($uuid->toString()); + } + } + + public static function toDateTime(UuidInterface $uuid): \DateTimeImmutable + { + if (! self::isV7($uuid)) { + throw new InvalidUuidException("Cannot extract datetime from non-V7 UUID: {$uuid->toString()}"); + } + + $fields = $uuid->getFields(); + + if ($fields instanceof Rfc4122FieldsInterface) { + $timeMsHex = $fields->getTimeLow()->toString() . $fields->getTimeMid()->toString(); + } else { + $hex = str_replace('-', '', $uuid->toString()); + $timeMsHex = substr($hex, 0, 12); + } + + $timeMs = (int) hexdec($timeMsHex); + $sec = intdiv($timeMs, 1000); + $ms = $timeMs % 1000; + + $dateTime = \DateTimeImmutable::createFromFormat('U.u', sprintf('%d.%06d', $sec, $ms * 1000)); + + if ($dateTime === false) { + throw new InvalidUuidException("Failed to extract datetime from UUID: {$uuid->toString()}"); + } + + return $dateTime->setTimezone(new \DateTimeZone('UTC')); + } } diff --git a/shared/ValueObjects/CrmHashcode.php b/shared/ValueObjects/CrmHashcode.php new file mode 100644 index 00000000..828e4bd5 --- /dev/null +++ b/shared/ValueObjects/CrmHashcode.php @@ -0,0 +1,29 @@ +value = $value->toString(); + } + + public function __toString(): string + { + return $this->value; + } +}