User.php 7.5 KB

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