*/ protected $casts = [ 'last_connection' => 'datetime', 'email_verified_at' => 'datetime', ]; /** * 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); // * Sync with stripe if already known by stripe. if ($model->stripe_id) { $model->syncStripeCustomerDetails(); } }); 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 /** * HasMany orders relation * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function orders() { return $this->hasMany(Order::class); } // * 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() { 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($id, $email) { self::assertFieldIsUnique($id, 'email', $email); } // * --- AUTH --- /** * Send the email verification notification. * * @return void */ public function sendEmailVerificationNotification() { $this->deleteIfDoesNotExistsInCrm(); $this->notify(new NotificationVerifyEmail()); } /** * 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($token) { $this->deleteIfDoesNotExistsInCrm(); /** @var string $token */ $this->notify(new NotificationResetPassword($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 --- /** * 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($id, string $field, $value) { 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(); } /** * Get the crm Data of a customer * * @return \LDC\LDCCRM\Models\Customer * @throws \LDC\LDCCRM\Exceptions\CrmException If cannot fetch data from crm. * @author Jérémy Munsch */ public function getApiDataAttribute(): CrmCustomer { /** @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 CustomerCrmResource $resource * * @return CrmCustomer * * @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. * @author Jérémy Munsch * @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber */ public function updateApiData(CustomerCrmResource $resource): CrmCustomer { $data = $resource->toArray(null); /** @var \LDC\LDCCRM\CrmApiV2 */ $crm = app('crmAPI'); $crmCustomer = $crm->getCustomer($data['hashcode']); if (!$crmCustomer) { throw new CrmException('CRM get Customer returned null'); } $crmCustomer->fill($data); $crmCustomer->save(); return $crmCustomer; } /** * 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(); } } }