Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * User Model class for Laravel MVC structure.
- * Includes multiple relations to other entities
- * Resolves following problems: roles, subusers(single account can be managed by several other users, each has own set of permissions)
- * Simplifies the way of getting CV's, Job Posts and applicants who applied for this job post
- * Provides methods to checks whether user has enough credits on his balance to perform not free actions
- * etc...
- */
- namespace App;
- use App\Mail\RegisterUser;
- use App\Mail\ResetPassword;
- use App\Traits\HasPermissions;
- use App\Traits\WorkExperienceTrait;
- use Carbon\Carbon;
- use Illuminate\Notifications\Notifiable;
- use Illuminate\Foundation\Auth\User as Authenticatable;
- use Illuminate\Support\Facades\Hash;
- use Mail;
- use Spatie\Newsletter\NewsletterFacade;
- /**
- * App\User
- *
- * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
- * @mixin \Eloquent
- * @property int $id
- * @property string $name
- * @property string $email
- * @property string $password
- * @property string $avatar
- * @property string $social_link
- * @property bool $confirmed
- * @property int $role
- * @property string $remember_token
- * @property \Carbon\Carbon $created_at
- * @property \Carbon\Carbon $updated_at
- * @method static \Illuminate\Database\Query\Builder|\App\User whereAvatar($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereConfirmed($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereCreatedAt($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereEmail($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereId($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereName($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User wherePassword($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereRememberToken($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereRole($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereSocialLink($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereUpdatedAt($value)
- * @property bool $disabled
- * @property string $ip
- * @method static \Illuminate\Database\Query\Builder|\App\User whereDisabled($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereIp($value)
- * @property string $last_login
- * @method static \Illuminate\Database\Query\Builder|\App\User whereLastLogin($value)
- * @property string $verification_code
- * @property-read \App\BlogSubscription $blogSubscription
- * @method static \Illuminate\Database\Query\Builder|\App\User whereVerificationCode($value)
- * @property string $first_name
- * @property string $last_name
- * @property string $phone
- * @property int $state_id
- * @property-read \App\Company $company
- * @property-read \App\FulcrumtestsAccount $fulcrumtestsAccount
- * @property-read \App\NotificationsSetting $notificationsSettings
- * @property-read \App\State $state
- * @method static \Illuminate\Database\Query\Builder|\App\User whereFirstName($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereLastName($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User wherePhone($value)
- * @method static \Illuminate\Database\Query\Builder|\App\User whereStateId($value)
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPost[] $jobPosts
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\Resume[] $resumes
- * @property-read \App\JobPostsSubscription $jobPostsSubscription
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\UploadedResume[] $uploadedResumes
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPost[] $savedJobPosts
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostApplication[] $jobPostsApplications
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostApplication[] $jobPostApplications
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostApplication[] $jobPostApplicationsForEmployer
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostApplication[] $newJobPostApplicationsForEmployer
- * @property int $balance
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\UserAssessment[] $assessments
- * @method static \Illuminate\Database\Query\Builder|\App\User whereBalance($value)
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $favouriteApplicants
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostBoost[] $jobPostBoosts
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\Resume[] $shortlistedResumes
- * @property-read \App\EmployerEmailMessage $emailMessage
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\JobPostAssessment[] $jobPostAssessments
- * @property bool $sending_email
- * @method static \Illuminate\Database\Query\Builder|\App\User whereSendingEmail($value)
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\Transaction[] $transactions
- * @property int $applications_unlocked
- * @method static \Illuminate\Database\Query\Builder|\App\User whereApplicationsUnlocked($value)
- * @property int $parent_id
- * @method static \Illuminate\Database\Query\Builder|\App\User whereParentId($value)
- * @property-read \App\User $parent
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $subUsers
- * @property-read \App\UserPermissions $permissions
- * @property int $actual_user_id
- * @method static \Illuminate\Database\Query\Builder|\App\User whereActualUserId($value)
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $subManaged
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $subManagedUsers
- * @property-read \App\User $actual
- * @property-read \Illuminate\Database\Eloquent\Collection|\App\Unsubscribe[] $unsubscribes
- */
- class User extends Authenticatable
- {
- use Notifiable, HasPermissions, WorkExperienceTrait;
- const ADMIN_ROLE = 0;
- const EMPLOYER_ROLE = 1;
- const APPLICANT_ROLE = 2;
- const CUSTOM_USER_ROLE = 3;
- const MAXIMUM_BALANCE = 100000000;
- const SUB_USERS_PER_PAGE = 10;
- static $rolesAllowedToBeRegistered = [self::EMPLOYER_ROLE => 'Employer', self::APPLICANT_ROLE => 'Applicant'];
- static $allRoles = [self::ADMIN_ROLE => 'Admin', self::EMPLOYER_ROLE => 'Employer', self::APPLICANT_ROLE => 'Applicant', self::CUSTOM_USER_ROLE => 'Sub User'];
- /**
- * The attributes that are mass assignable.
- *
- * @var array
- */
- protected $fillable = ['email', 'password', 'role', 'avatar', 'social_link', 'confirmed', 'disabled', 'first_name', 'last_name', 'phone', 'state_id', 'parent_id'];
- protected $dates = ['last_login'];
- /**
- * The attributes that should be hidden for arrays.
- *
- * @var array
- */
- protected $hidden = ['password', 'remember_token',];
- public function notificationsSettings()
- {
- return $this->hasOne(NotificationsSetting::class);
- }
- public function favouriteApplicants()
- {
- return $this->belongsToMany(User::class, 'favourite_applicants', 'employer_id', 'applicant_id')->withPivot('id', 'employer_id', 'applicant_id');
- }
- public function hasInFavourites($userId)
- {
- return $this->favouriteApplicants()->where('applicant_id', $userId)->exists();
- }
- public function getFavouriteApplicantEntityId($userId)
- {
- return $this->favouriteApplicants()->where('applicant_id', $userId)->first()->pivot->id;
- }
- public function blogSubscription()
- {
- if ($this->hasOne(BlogSubscription::class)->exists()) {
- return $this->hasOne(BlogSubscription::class);
- }
- return $this->hasOne(BlogSubscription::class, 'email', 'email');
- }
- public function state()
- {
- return $this->belongsTo(State::class);
- }
- public function jobPosts()
- {
- return $this->hasMany(JobPost::class);
- }
- public function savedJobPosts()
- {
- return $this->morphedByMany(JobPost::class, 'savable', 'saved_job_posts')->where('job_posts.draft', 0);
- }
- public function savedExternalJobPosts()
- {
- return $this->morphedByMany(ExternalJobPost::class, 'savable', 'saved_job_posts');
- }
- public function getSavingInstanceForJobPost($jobPost)
- {
- return SavedJobPost::where('user_id', $this->id)->where('savable_id', $jobPost->id)->where('savable_type', get_class($jobPost))->first();
- }
- public function hasSavedJobPost($jobPost)
- {
- if ($jobPost instanceof JobPost) {
- return $this->savedJobPosts()->where('job_posts.id', $jobPost->id)->exists();
- }
- return $this->savedExternalJobPosts()->where('external_job_posts.id', $jobPost->id)->exists();
- }
- public function hasSavedJobPosts()
- {
- return $this->savedJobPosts()->exists();
- }
- public function company()
- {
- return $this->hasOne(Company::class);
- }
- public function assessments()
- {
- return $this->hasMany(UserAssessment::class);
- }
- public function hasRequiredAssessmentsForApplying($jobPostId)
- {
- $jobPost = JobPost::find($jobPostId);
- $userAssessments = $this->assessments;
- foreach ($jobPost->requiredAssessments as $requiredAssessment) {
- if ($userAssessments->where('assessment_id', $requiredAssessment->assessment_id)->where('score', '>=', $requiredAssessment->score)->isEmpty()) {
- return false;
- }
- }
- return true;
- }
- public function hasPreferredAssessmentsForApplying($jobPostId)
- {
- $jobPost = JobPost::find($jobPostId);
- $userAssessments = $this->assessments;
- foreach ($jobPost->preferredAssessments as $preferredAssessment) {
- if ($userAssessments->where('assessment_id', $preferredAssessment->assessment_id)->where('score', '>=', $preferredAssessment->score)->isEmpty()) {
- return false;
- }
- }
- return true;
- }
- public function resumes()
- {
- return $this->hasMany(Resume::class);
- }
- public function hasResume($resumeId)
- {
- return $this->resumes()->where('resumes.id', $resumeId)->exists();
- }
- public function hasResumes()
- {
- return $this->resumes()->exists();
- }
- public function parent()
- {
- return $this->belongsTo(User::class, 'parent_id');
- }
- public function actual()
- {
- return $this->belongsTo(User::class, 'actual_user_id');
- }
- public function subUsers()
- {
- return $this->hasMany(User::class, 'parent_id');
- }
- public function subManagedUsers()
- {
- return $this->hasMany(User::class, 'actual_user_id');
- }
- public function transactions()
- {
- return $this->hasMany(Transaction::class);
- }
- public function sendRegistrationEmail($temporaryPassword = false)
- {
- \Mail::to($this->email)->send(new RegisterUser($this, $temporaryPassword));
- }
- public function jobPostsSubscription()
- {
- return $this->hasOne(JobPostsSubscription::class);
- }
- public function jobPostApplications()
- {
- return $this->hasManyThrough(JobPostApplication::class, Resume::class);
- }
- public function jobPostAssessments()
- {
- return $this->hasManyThrough(JobPostAssessment::class, JobPost::class);
- }
- public function jobPostApplicationsForEmployer()
- {
- return $this->hasManyThrough(JobPostApplication::class, JobPost::class);
- }
- public function newJobPostApplicationsForEmployer()
- {
- if ($this->isCustomUser() && $this->canReviewJobApplications()) {
- return $this->parent->hasManyThrough(JobPostApplication::class, JobPost::class)->where('job_post_applications.status', JobPostApplication::NEW_STATUS);
- }
- return $this->hasManyThrough(JobPostApplication::class, JobPost::class)->where('job_post_applications.status', JobPostApplication::NEW_STATUS);
- }
- public function emailMessage()
- {
- return $this->hasOne(EmployerEmailMessage::class);
- }
- public function hasJobPostsWithNewApplications()
- {
- if ($this->isCustomUser() && $this->canReviewJobApplications() && $this->parent->newJobPostApplicationsForEmployer()->exists()) {
- return true;
- }
- return $this->newJobPostApplicationsForEmployer()->exists();
- }
- public function getApplicationForJob($jobPostId)
- {
- if ($this->isCustomUser() && $this->canReviewJobApplications()) {
- return $this->parent->jobPostApplications()->where('job_post_applications.job_post_id', $jobPostId)->first();
- }
- return $this->jobPostApplications()->where('job_post_applications.job_post_id', $jobPostId)->first();
- }
- public function getAppliedJobPosts()
- {
- $appliedJobPostsIds = $this->jobPostApplications()->whereHas('jobPost', function ($query) {
- $query->where('draft', 0)->verified();
- })->pluck('job_post_id')->toArray();
- return JobPost::whereIn('id', $appliedJobPostsIds)->orderBy('id', 'DESC')->paginate(JobPost::POSTS_ON_ONE_PAGE_AMOUNT);
- }
- public function hasAppliedForAJob($jobPostId = null)
- {
- if (is_null($jobPostId)) {
- return $this->jobPostApplications()->exists();
- }
- return $this->jobPostApplications()->where('job_post_applications.job_post_id', $jobPostId)->exists();
- }
- public function fulcrumtestsAccount()
- {
- return $this->hasOne(FulcrumtestsAccount::class);
- }
- public function hasCompany()
- {
- if ($this->isCustomUser() && $this->parent->isEmployer() && $this->parent->company()->exists()) {
- return true;
- }
- return $this->company()->exists();
- }
- public function hasJobPosts()
- {
- return $this->jobPosts()->exists();
- }
- public function hasJobPost($jobPostId)
- {
- return $this->jobPosts()->where('job_posts.id', $jobPostId)->exists();
- }
- public function isAdmin()
- {
- if ($this->isCustomUser() && $this->parent->role == self::ADMIN_ROLE) {
- return true;
- }
- return $this->role == self::ADMIN_ROLE;
- }
- public function isApplicant()
- {
- return $this->role == self::APPLICANT_ROLE;
- }
- public function isEmployer()
- {
- if ($this->isCustomUser() && $this->parent->role == self::EMPLOYER_ROLE) {
- return true;
- }
- return $this->role == self::EMPLOYER_ROLE;
- }
- public function isCustomUser()
- {
- return $this->role == self::CUSTOM_USER_ROLE;
- }
- public function isActualUser()
- {
- return $this->actual_user_id == 0;
- }
- public function canBeSwitchedTo(User $userToSwitchTo)
- {
- if ($this->isActualUser() && $userToSwitchTo->actual_user_id == $this->id) {
- return true;
- }
- if ( ! $this->isActualUser()) {
- if ($userToSwitchTo->isActualUser() && $userToSwitchTo->id == $this->actual_user_id) {
- return true;
- }
- if ( ! $userToSwitchTo->isActualUser() && $userToSwitchTo->actual_user_id == $this->actual_user_id) {
- return true;
- }
- }
- return false;
- }
- public function permissions()
- {
- return $this->hasOne(UserPermissions::class);
- }
- public function sendPasswordResetNotification($token)
- {
- Mail::to($this->email)->send(new ResetPassword($this, $token));
- }
- public function disable()
- {
- $this->disabled = 1;
- }
- public function enable()
- {
- $this->disabled = 0;
- }
- public function isBanned()
- {
- return $this->hasBannedIp() || Helper::ipIsBanned(Helper::getUserIp()) || $this->disabled;
- }
- public function hasBannedIp()
- {
- return Helper::ipIsBanned($this->ip);
- }
- public function subscribeToPromotions()
- {
- $settings = $this->notificationsSettings()->firstOrNew([]);
- $settings->receive_promotions_notifications = 1;
- $settings->save();
- $mailChimpService = new MailChimpService();
- $mailChimpService->subscribeOrUpdate($this->email, ['FNAME'=>$this->first_name, 'LNAME'=>$this->last_name]);
- }
- public function updateAccessSettings($newEmail, $newPassword)
- {
- if ($newEmail) {
- $mailChimpService = new MailChimpService();
- $mailChimpService->updateEmailAddress($this->email, $newEmail);
- $this->email = $newEmail;
- }
- if ($newPassword) {
- $this->password = bcrypt($newPassword);
- }
- return $this;
- }
- public function passwordConfirmed($passwordToCheck)
- {
- $result = Hash::check($passwordToCheck, $this->password);
- return $result;
- }
- public function getRoleName()
- {
- return self::$allRoles[$this->role];
- }
- public function getFullName()
- {
- $fullName = '';
- $user = $this->isActualUser() ? $this : $this->actual;
- if ($user->first_name) {
- $fullName .= mb_convert_case(mb_strtolower($user->first_name), MB_CASE_TITLE, "UTF-8");
- }
- if ($user->last_name) {
- $fullName .= ' ' . mb_strtoupper(mb_substr($user->last_name, 0, 1, 'UTF8'));
- $fullName .= '.';
- }
- return trim($fullName);
- }
- public function setLastLogin()
- {
- $lastLoginTimeStamp = Carbon::now();
- $this->last_login = $lastLoginTimeStamp;
- $this->save();
- }
- public function getLastLogin()
- {
- if ($this->last_login) {
- $lastLogin = $this->last_login;
- } else {
- $lastLogin = $this->created_at;
- }
- $lastLogin->setTimezone('GMT');
- $lastLogin = $lastLogin->format('g:i A d-m-Y T');
- return $lastLogin;
- }
- public function subscribedToBlog()
- {
- return $this->blogSubscription()->exists();
- }
- public function receivesJobPostsNotification()
- {
- return $this->jobPostsSubscription()->exists();
- }
- public function receivesLearningCenterNotifications()
- {
- return $this->notificationsSettings ? $this->notificationsSettings->receive_learning_center_notifications : 0;
- }
- public function receivesJobPostApplicationsNotifications()
- {
- return $this->notificationsSettings ? $this->notificationsSettings->receive_job_post_applications_notifications : 0;
- }
- public function receivesPromotionsNotifications()
- {
- return $this->notificationsSettings ? $this->notificationsSettings->receive_promotions_notifications : 0;
- }
- public function receivesJobPostsVerificationNotifications()
- {
- return $this->notificationsSettings ? $this->notificationsSettings->receive_job_post_verification_notifications : 0;
- }
- public function getRegistrationDate()
- {
- return $this->created_at->format('d-m-Y');
- }
- public function hasLinkedFulcrumtestsAccount()
- {
- return $this->fulcrumtestsAccount()->exists();
- }
- public function getJobPostsSubscriptionPeriodicity()
- {
- if ( ! $this->receivesJobPostsNotification()) {
- return JobPostsSubscription::DISABLED_PERIODICITY;
- }
- return $this->jobPostsSubscription->periodicity;
- }
- public function createdResume()
- {
- return $this->resumes()->whereNull('path')->first();
- }
- public function canAddResume()
- {
- return ($this->resumes()->whereNull('path')->count()) < Resume::MAX_CREATED_RESUMES_PER_USER;
- }
- public function canUploadResume()
- {
- return ($this->resumes()->whereNotNull('path')->count()) < Resume::MAX_UPLOADED_RESUMES_PER_USER;
- }
- public function hasEnoughBalanceForJobPostBoosting($period = 1)
- {
- return $this->balance >= Setting::getValue('boosting_cost_per_day') * $period;
- }
- public function hasEnoughBalanceForPostingExternalUrlInJob()
- {
- return $this->balance >= JobPost::EXTERNAL_LINK_PRICE_TEMP_CONST;
- }
- public function jobPostBoosts()
- {
- return $this->hasManyThrough(JobPostBoost::class, JobPost::class);
- }
- public function getBalance()
- {
- return $this->balance / 100;
- }
- public function chargeFromBalance($amount, $description = '', $balanceIncreased = 0, $status = Transaction::STATUS_SUCCESS)
- {
- if ($this->balance - $amount < 0) {
- $amount = $this->balance;
- }
- $this->balance -= $amount;
- $this->transactions()->create([
- 'amount' => $amount,
- 'description' => $description,
- 'balance_increased' => $balanceIncreased,
- 'status' => $status,
- ]);
- return $this;
- }
- public function addToBalance($amount, $description = '', $balanceIncreased = 1, $status = Transaction::STATUS_SUCCESS)
- {
- if ($this->balance + $amount > self::MAXIMUM_BALANCE) {
- $amount = self::MAXIMUM_BALANCE - $this->balance;
- }
- $this->balance += $amount;
- $this->transactions()->create([
- 'amount' => $amount,
- 'description' => $description,
- 'balance_increased' => $balanceIncreased,
- 'status' => $status,
- ]);
- return $this;
- }
- public function hasUnlockedApplications()
- {
- if ($this->isCustomUser()) {
- return $this->parent->applications_unlocked;
- }
- return $this->applications_unlocked;
- }
- public function hasEnoughMoneyForUnlockingApplications()
- {
- return $this->balance >= Setting::getValue('unlock_applications_cost');
- }
- public function getEmployerEmailData()
- {
- $emailData = $this->emailMessage ?? $this->emailMessage()->create(['subject' => 'Topreqs: Your CV was viewed', 'message' => 'Hello, I viewed your CV...']);
- return $emailData;
- }
- public function unlockJobPostsApplications()
- {
- foreach ($this->getLockedJobPostsWithApplications() as $jobPost) {
- $jobPost->unlockApplications()->save();
- }
- return $this;
- }
- public function getCompany()
- {
- if ($this->isCustomUser() && $this->parent->isEmployer() && $this->parent->company()->exists()) {
- return $this->parent->company;
- }
- return $this->company;
- }
- public function getApplicationsToUnlockCount()
- {
- return JobPostApplication::whereIn('job_post_id', $this->getLockedJobPostsWithApplications()->pluck('id')->toArray())->count();
- }
- public function getJobPostsToUnlockCount()
- {
- return $this->getLockedJobPostsWithApplications()->count();
- }
- public function getLockedJobPostsWithApplications()
- {
- return $this->jobPosts()->where('applications_unlocked', 0)->whereHas('applications')->get();
- }
- public function wasLastCommunicatedAt()
- {
- $contact = ContactWithApplicant::where('employer_id', Helper::getParentUserIfExists()->id)->where('applicant_id', $this->id)->first();
- if ($contact) {
- return $contact->updated_at->diffForHumans();
- }
- return '';
- }
- public function updateFulcrumtestsAssessments($assessments)
- {
- $this->assessments()->delete();
- foreach ($assessments as $assessment) {
- $this->assessments()->create($assessment);
- }
- return $this;
- }
- }
Add Comment
Please, Sign In to add comment