User.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <?php
  2. namespace App\Models;
  3. use App\Enums\LanguageEnum;
  4. use App\Enums\UserStatusEnum;
  5. use App\Enums\UserTypeEnum;
  6. use App\Support\Cpf;
  7. use App\Traits\HasPermissions;
  8. use Illuminate\Database\Eloquent\Casts\Attribute;
  9. use Illuminate\Database\Eloquent\Factories\HasFactory;
  10. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  11. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  12. use Illuminate\Database\Eloquent\Relations\HasMany;
  13. use Illuminate\Foundation\Auth\User as Authenticatable;
  14. use Illuminate\Notifications\Notifiable;
  15. use Laravel\Sanctum\HasApiTokens;
  16. use Carbon\Carbon;
  17. /**
  18. * @property int $id
  19. * @property string $name
  20. * @property string $email
  21. * @property string|null $phone
  22. * @property string|null $position_label
  23. * @property string|null $sector_label
  24. * @property \Illuminate\Support\Carbon|null $email_verified_at
  25. * @property string $password
  26. * @property UserTypeEnum $type
  27. * @property LanguageEnum $language
  28. * @property \Illuminate\Support\Carbon|null $created_at
  29. * @property \Illuminate\Support\Carbon|null $updated_at
  30. * @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
  31. * @property-read int|null $notifications_count
  32. * @property-read \Kalnoy\Nestedset\Collection<int, \App\Models\Permission> $permissions
  33. * @property-read int|null $permissions_count
  34. * @property-read \Illuminate\Database\Eloquent\Collection<int, \Laravel\Sanctum\PersonalAccessToken> $tokens
  35. * @property-read int|null $tokens_count
  36. * @method static \Database\Factories\UserFactory factory($count = null, $state = [])
  37. * @method static \Illuminate\Database\Eloquent\Builder<static>|User newModelQuery()
  38. * @method static \Illuminate\Database\Eloquent\Builder<static>|User newQuery()
  39. * @method static \Illuminate\Database\Eloquent\Builder<static>|User query()
  40. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereCreatedAt($value)
  41. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereEmail($value)
  42. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereEmailVerifiedAt($value)
  43. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereId($value)
  44. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereLanguage($value)
  45. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereName($value)
  46. * @method static \Illuminate\Database\Eloquent\Builder<static>|User wherePassword($value)
  47. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereType($value)
  48. * @method static \Illuminate\Database\Eloquent\Builder<static>|User whereUpdatedAt($value)
  49. * @property string|null $photo_path
  50. * @mixin \Eloquent
  51. */
  52. class User extends Authenticatable
  53. {
  54. use HasFactory, Notifiable, HasApiTokens, HasPermissions;
  55. protected $guarded = ["id"];
  56. /**
  57. * The attributes that should be hidden for serialization.
  58. *
  59. * @var array<int, string>
  60. */
  61. protected $hidden = ["password", "remember_token"];
  62. /**
  63. * Get the attributes that should be cast.
  64. *
  65. * @return array<string, string>
  66. */
  67. protected function casts(): array
  68. {
  69. return [
  70. "email_verified_at" => "datetime",
  71. "password" => "hashed",
  72. "type" => UserTypeEnum::class,
  73. "language" => LanguageEnum::class,
  74. "status" => UserStatusEnum::class,
  75. "admission_date" => "date",
  76. "first_access_completed_at" => "datetime",
  77. "terms_accepted_at" => "datetime",
  78. "expiry_date" => "date",
  79. "excluded_at" => "datetime",
  80. "on_leave_at" => "datetime",
  81. ];
  82. }
  83. protected function cpf(): Attribute
  84. {
  85. return Attribute::make(
  86. get: fn(?string $value): ?string => Cpf::format($value),
  87. set: fn(?string $value): ?string => Cpf::digits($value),
  88. );
  89. }
  90. public function isAdministrador(): bool
  91. {
  92. return $this->type === UserTypeEnum::ADMINISTRADOR;
  93. }
  94. public function isAssociado(): bool
  95. {
  96. return $this->type === UserTypeEnum::ASSOCIADO;
  97. }
  98. public function isParceiro(): bool
  99. {
  100. return $this->type === UserTypeEnum::PARCEIRO;
  101. }
  102. public function loginBlockReason(): ?string
  103. {
  104. if ($this->isAssociado()) {
  105. return match (true) {
  106. $this->status === UserStatusEnum::REFUSED => 'refused',
  107. is_null($this->first_access_completed_at) => 'first_access_required',
  108. $this->status === UserStatusEnum::PENDING => 'pending_approval',
  109. default => null,
  110. };
  111. }
  112. if ($this->isParceiro() && $this->status === UserStatusEnum::INACTIVE) {
  113. return 'inactive';
  114. }
  115. return null;
  116. }
  117. /**
  118. * Indica se o usuário já pode ser autenticado (usado ao concluir o primeiro acesso).
  119. */
  120. public function canLogin(): bool
  121. {
  122. return $this->loginBlockReason() === null;
  123. }
  124. /**
  125. * Create a new access token for the user.
  126. */
  127. public function createAccessToken(string $deviceId): string
  128. {
  129. return $this->createToken(
  130. name: "access_token_{$deviceId}",
  131. abilities: ["access"],
  132. expiresAt: Carbon::now()->addMinutes(15),
  133. )->plainTextToken;
  134. }
  135. /**
  136. * Create a new refresh token for the user.
  137. */
  138. public function createRefreshToken(string $deviceId): string
  139. {
  140. return $this->createToken(
  141. name: "refresh_token_{$deviceId}",
  142. abilities: ["refresh"],
  143. expiresAt: Carbon::now()->addDays(30),
  144. )->plainTextToken;
  145. }
  146. /**
  147. * Delete all tokens (access and refresh) for a specific device.
  148. */
  149. public function deleteTokensByDevice(string $deviceId): void
  150. {
  151. $this->tokens()
  152. ->where("name", "like", "%_{$deviceId}")
  153. ->delete();
  154. }
  155. public function position(): BelongsTo
  156. {
  157. return $this->belongsTo(Position::class);
  158. }
  159. public function sector(): BelongsTo
  160. {
  161. return $this->belongsTo(Sector::class);
  162. }
  163. public function dependents(): HasMany
  164. {
  165. return $this->hasMany(UserDependent::class, 'responsible_user_id');
  166. }
  167. public function appointments(): HasMany
  168. {
  169. return $this->hasMany(Appointment::class);
  170. }
  171. public function notificationSends(): HasMany
  172. {
  173. return $this->hasMany(NotificationSend::class);
  174. }
  175. public function storeItemInterests(): HasMany
  176. {
  177. return $this->hasMany(StoreItemInterest::class);
  178. }
  179. public function accessLogs(): HasMany
  180. {
  181. return $this->hasMany(UserAccessLog::class);
  182. }
  183. public function evaluations(): HasMany
  184. {
  185. return $this->hasMany(Evaluation::class);
  186. }
  187. /**
  188. * @return BelongsToMany
  189. */
  190. public function permissions(): BelongsToMany
  191. {
  192. return $this->belongsToMany(
  193. Permission::class,
  194. "user_type_permissions",
  195. "user_type",
  196. "permission_id",
  197. );
  198. }
  199. }