User.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. "expiry_date" => "date",
  78. "excluded_at" => "datetime",
  79. "on_leave_at" => "datetime",
  80. ];
  81. }
  82. protected function cpf(): Attribute
  83. {
  84. return Attribute::make(
  85. get: fn(?string $value): ?string => Cpf::format($value),
  86. set: fn(?string $value): ?string => Cpf::digits($value),
  87. );
  88. }
  89. public function isAdministrador(): bool
  90. {
  91. return $this->type === UserTypeEnum::ADMINISTRADOR;
  92. }
  93. public function isAssociado(): bool
  94. {
  95. return $this->type === UserTypeEnum::ASSOCIADO;
  96. }
  97. public function isParceiro(): bool
  98. {
  99. return $this->type === UserTypeEnum::PARCEIRO;
  100. }
  101. public function loginBlockReason(): ?string
  102. {
  103. if ($this->isAssociado()) {
  104. return match (true) {
  105. $this->status === UserStatusEnum::REFUSED => 'refused',
  106. is_null($this->first_access_completed_at) => 'first_access_required',
  107. $this->status === UserStatusEnum::PENDING => 'pending_approval',
  108. default => null,
  109. };
  110. }
  111. if ($this->isParceiro() && $this->status === UserStatusEnum::INACTIVE) {
  112. return 'inactive';
  113. }
  114. return null;
  115. }
  116. /**
  117. * Indica se o usuário já pode ser autenticado (usado ao concluir o primeiro acesso).
  118. */
  119. public function canLogin(): bool
  120. {
  121. return $this->loginBlockReason() === null;
  122. }
  123. /**
  124. * Create a new access token for the user.
  125. */
  126. public function createAccessToken(string $deviceId): string
  127. {
  128. return $this->createToken(
  129. name: "access_token_{$deviceId}",
  130. abilities: ["access"],
  131. expiresAt: Carbon::now()->addMinutes(15),
  132. )->plainTextToken;
  133. }
  134. /**
  135. * Create a new refresh token for the user.
  136. */
  137. public function createRefreshToken(string $deviceId): string
  138. {
  139. return $this->createToken(
  140. name: "refresh_token_{$deviceId}",
  141. abilities: ["refresh"],
  142. expiresAt: Carbon::now()->addDays(30),
  143. )->plainTextToken;
  144. }
  145. /**
  146. * Delete all tokens (access and refresh) for a specific device.
  147. */
  148. public function deleteTokensByDevice(string $deviceId): void
  149. {
  150. $this->tokens()
  151. ->where("name", "like", "%_{$deviceId}")
  152. ->delete();
  153. }
  154. public function position(): BelongsTo
  155. {
  156. return $this->belongsTo(Position::class);
  157. }
  158. public function sector(): BelongsTo
  159. {
  160. return $this->belongsTo(Sector::class);
  161. }
  162. public function dependents(): HasMany
  163. {
  164. return $this->hasMany(UserDependent::class, 'responsible_user_id');
  165. }
  166. public function appointments(): HasMany
  167. {
  168. return $this->hasMany(Appointment::class);
  169. }
  170. public function notificationSends(): HasMany
  171. {
  172. return $this->hasMany(NotificationSend::class);
  173. }
  174. public function storeItemInterests(): HasMany
  175. {
  176. return $this->hasMany(StoreItemInterest::class);
  177. }
  178. public function accessLogs(): HasMany
  179. {
  180. return $this->hasMany(UserAccessLog::class);
  181. }
  182. public function evaluations(): HasMany
  183. {
  184. return $this->hasMany(Evaluation::class);
  185. }
  186. /**
  187. * @return BelongsToMany
  188. */
  189. public function permissions(): BelongsToMany
  190. {
  191. return $this->belongsToMany(
  192. Permission::class,
  193. "user_type_permissions",
  194. "user_type",
  195. "permission_id",
  196. );
  197. }
  198. }