ldc-gen-game-web/app/Models/Customer.php
2023-12-12 12:25:45 +01:00

359 lines
11 KiB
PHP

<?php
namespace App\Models;
use App\Notifications\Customer\DestroyCustomer;
use App\Notifications\Customer\DestroyedCustomer;
use App\Notifications\Customer\ResetPassword;
use App\Notifications\Customer\VerifyEmail;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use LDC\LDCCRM\Enums\ApiError;
use LDC\LDCCRM\Exceptions\ApiErrorException;
use LDC\LDCCRM\Exceptions\CrmException;
use LDC\LDCCRM\Models\Customer as CrmCustomer;
/**
* @property string $email Email.
* @property string $hashcode Hashcode.
* @property string $remember_token Remember token.
* @property \LDC\LDCCRM\Models\Customer api_data
* @property \Carbon\Carbon|null $email_verified_at
* @property \Carbon\Carbon|null $last_connection Date de derniere connexion, (pour les questions oblig CRM).
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
*/
class Customer extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use Prunable;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'email',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'last_connection' => 'datetime',
'email_verified_at' => 'datetime',
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
static::assertEmailIsUnique($model->id, $model->email);
});
static::updating(function (self $model) {
static::assertEmailIsUnique($model->id, $model->email);
});
static::deleting(function () {
throw new \RuntimeException('This cannot be done à cause de MesBr');
});
static::deleted(function (self $model) {
if ($model->forceDeleting) {
if ($model->existsInCrm()) {
$model->api_data->delete();
}
$model->notify(new DestroyedCustomer());
} else {
$model->notify(new DestroyCustomer());
}
});
static::restored(function () {
\session()->flash(
'warning',
\trans('Votre compte à été réactivé.')
);
});
}
// * RELATIONSHIPS
/**
* Has Many Participation relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function participations()
{
return $this->hasMany(Participation::class, 'user_id');
}
// * METHODS
/**
* Supprimer les comptes inactivés depuis plus d'une semaine
* de manière permanente.
*
* ! Les comptes non activés depuis une semaine ou les comptes supprimés depuis une semaine.
*
* @return \Illuminate\Database\Query\Builder
*/
public function prunable(): Builder
{
return static::query()->where(function (Builder $q) {
$q->where('updated_at', '<=', now()->subWeek())
->whereNull('email_verified_at');
})->orWhere(function (Builder $q) {
$q->where('deleted_at', '<=', now()->subWeek());
});
}
/**
* Asserts using validation that the email is unique
*
* @param mixed $id
* @param mixed $email
* @return void
* @throws \Illuminate\Validation\ValidationException If user email as already used.
*/
private static function assertEmailIsUnique(mixed $id, mixed $email): void
{
self::assertFieldIsUnique($id, 'email', $email);
}
/**
* Asserts that the field is unique
*
* @param mixed $id
* @param string $field
* @param mixed $value
* @return void
* @throws \Illuminate\Validation\ValidationException If the field is not unique.
*/
private static function assertFieldIsUnique(mixed $id, string $field, mixed $value): void
{
Validator::make([$field => $value], [
$field => Rule::unique('customers', $field)->ignore($id),
], [
$field . '.unique' => trans('La valeur :value pour le champ :attribute est déjà utilisé', [
'attribute' => $field,
'value' => $value
])
])->validate();
}
// * --- AUTH ---
/**
* Send the email verification notification.
*
* @return void
*/
public function sendEmailVerificationNotification()
{
$this->deleteIfDoesNotExistsInCrm();
$this->notify(new VerifyEmail());
}
/**
* Mark the given user's email as verified.
*
* @return boolean
* @throws \LDC\LDCCRM\Exceptions\CrmException If an error occurs on server side or on getting response.
* @throws \LDC\LDCCRM\Exceptions\ApiErrorException If any error or \LDC\LDCCRM\Enums\ApiError occurs.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public function markEmailAsVerified()
{
$this->deleteIfDoesNotExistsInCrm();
try {
return $this->api_data->activate() && parent::markEmailAsVerified();
} catch (ApiErrorException $e) {
if ($e->getApiError()->equals(ApiError::customerAlreadyActive())) {
return true && parent::markEmailAsVerified();
}
throw $e;
}
}
/**
* Send the password reset notification.
*
* @param mixed $token
* @return void
*/
public function sendPasswordResetNotification(mixed $token)
{
$this->deleteIfDoesNotExistsInCrm();
/** @var string $token */
$this->notify(new ResetPassword($token));
}
/**
* Check if the customer exists in CRM.
*
* @return boolean
*/
public function existsInCrm(): bool
{
return $this->hashcode and CrmCustomer::find($this->hashcode);
}
/**
* Force delete and logout if is logged in case the customer
* does not exists in CRM.
*
* @return void
* @throws \Illuminate\Validation\ValidationException If the account is deleted because does not exists in CRM.
*/
private function deleteIfDoesNotExistsInCrm(): void
{
if ($this->existsInCrm()) {
return;
}
/** @var static|null $loggedCustomer */
$loggedCustomer = \auth('frontend')->user();
$isLogged = \optional($loggedCustomer)->id === $this->id and !\is_null($this->id);
if ($isLogged) {
\auth('frontend')->logout();
}
$this->forceDelete();
throw ValidationException::withMessages([
'error' => trans('Le compte \'existe pas.')
]);
}
// * --- END AUTH ---
/**
* Get api_data attribute, the crm Data of a customer
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
public function apiData(): Attribute
{
return Attribute::make(
get: fn (): CrmCustomer => self::cacheCrm($this->hashcode, "apiData", function () {
/** @var \LDC\LDCCRM\CrmApiV2 */
$crm = app('crmAPI');
$crmCustomer = $crm->getCustomer($this->hashcode);
if (!$crmCustomer) {
throw new CrmException('CRM get Customer returned null');
}
return $crmCustomer;
})
);
}
/**
* Set the crm Data of a customer
*
* @param array $data
* @return boolean
*
* @throws \LDC\LDCCRM\Exceptions\CrmException If an error occurs on server side or on getting response.
* @throws \LDC\LDCCRM\Exceptions\ApiErrorException If any error or \LDC\LDCCRM\Enums\ApiError occurs.
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public function updateApiData(array $data): bool
{
// phpcs:enable
/** @var \LDC\LDCCRM\Models\Customer */
$crmCustomer = $this->apiData;
if (!$crmCustomer) {
throw new CrmException('CRM get Customer returned null');
}
$crmCustomer->fill($data);
$result = $crmCustomer->save();
self::clearCrmCached($crmCustomer->hashcode, 'apiData');
return $result;
}
// * CRM CACHE
/**
* Put customer crm part in cache
*
* @template T
* @param string $uuid The customer uuid.
* @param string $part_name The part name for the cache path.
* @param \Closure(void):T $part The part to cache.
* @param integer $ttl Time to live in seconds for the cache part.
* @return T
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
*/
public static function cacheCrm(string $uuid, string $part_name, \Closure $part, int $ttl = 60 * 60)
{
// phpcs:enable
return Cache::remember("customers.{$uuid}.{$part_name}", $ttl, $part);
}
/**
* Clear customer crm cache part or totally
*
* @param string $uuid
* @param string $part_name
* @return void
*/
public static function clearCrmCached(string $uuid, string $part_name): void
{
$cache = "customers.{$uuid}";
if ($part_name) {
$cache .= ".{$part_name}";
}
Cache::forget($cache);
}
// * --- END CRM CACHE
/**
* This mutate Customer attributes to array
* including only non critical properties and crm values
* (One that can be send to front office without security breach)
*
* @return array
*/
public function toArray()
{
if ($this->hashcode) {
return collect(array_merge(
parent::toArray(),
(array)$this->apiData
))->intersectByKeys([
'email' => '',
'firstname' => '',
'lastname' => '',
'address' => '',
'address2' => '',
'postcode' => '',
'birth_date' => '',
'city' => '',
'country' => '',
'opt_in' => '',
'phone' => ''
])->toArray();
} else {
return parent::toArray();
}
}
}