UserService.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\UserStatusEnum;
  4. use App\Enums\UserTypeEnum;
  5. use App\Models\User;
  6. use App\Support\Cpf;
  7. use Illuminate\Database\Eloquent\Collection;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Str;
  10. class UserService
  11. {
  12. public function authUser(): ?User
  13. {
  14. $user = Auth::user();
  15. if (!$user) {
  16. return null;
  17. }
  18. if ($user->isParceiro()) {
  19. $user->loadMissing('partnerAgreement');
  20. }
  21. return $user->load(['position', 'sector', 'dependents',])->loadCount(['notificationSends as unread_notifications_count' => fn($q) => $q->where('read', false),]);
  22. }
  23. public function getAll(): Collection
  24. {
  25. return User::with(['position', 'sector'])->orderBy("created_at", "desc")->get();
  26. }
  27. public function getAssociadosForSelect(?string $search, int $perPage): \Illuminate\Pagination\LengthAwarePaginator
  28. {
  29. return $this->baseQuery([
  30. 'type' => UserTypeEnum::ASSOCIADO->value,
  31. 'search' => $search,
  32. ])
  33. ->where('status', UserStatusEnum::ACTIVE)
  34. ->orderBy('name')
  35. ->paginate($perPage, ['id', 'name', 'registration']);
  36. }
  37. public function getAllPaginated(array $filters = [], int $perPage = 10): \Illuminate\Pagination\LengthAwarePaginator
  38. {
  39. $query = $this->baseQuery($filters)
  40. ->with(['position', 'sector'])
  41. ->withMin('accessLogs', 'accessed_at')
  42. ->orderBy('name', 'asc');
  43. if (!empty($filters['status'])) {
  44. $query->where('status', $filters['status']);
  45. }
  46. return $query->paginate($perPage);
  47. }
  48. /**
  49. * Status existentes no conjunto filtrado, desconsiderando o próprio filtro de status.
  50. *
  51. * @return array<int, string>
  52. */
  53. public function getStatusOptions(array $filters = []): array
  54. {
  55. return $this->baseQuery($filters)
  56. ->toBase()
  57. ->distinct()
  58. ->pluck('status')
  59. ->filter()
  60. ->values()
  61. ->all();
  62. }
  63. private function baseQuery(array $filters): \Illuminate\Database\Eloquent\Builder
  64. {
  65. $query = User::query();
  66. if (!empty($filters['type'])) {
  67. $query->where('type', $filters['type']);
  68. }
  69. if (!empty($filters['position_id'])) {
  70. $query->where('position_id', $filters['position_id']);
  71. }
  72. if (!empty($filters['sector_id'])) {
  73. $query->where('sector_id', $filters['sector_id']);
  74. }
  75. if (!empty($filters['search'])) {
  76. $term = '%' . mb_strtolower($filters['search']) . '%';
  77. $cpfTerm = ($digits = Cpf::digits($filters['search'])) ? '%' . $digits . '%' : null;
  78. $query->where(function ($q) use ($term, $cpfTerm) {
  79. $q->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term])
  80. ->orWhereRaw('UNACCENT(LOWER(email)) LIKE UNACCENT(?)', [$term])
  81. ->orWhereRaw('UNACCENT(LOWER(COALESCE(registration, \'\'))) LIKE UNACCENT(?)', [$term])
  82. ->orWhereRaw("TO_CHAR(admission_date, 'DD/MM/YYYY') LIKE ?", [$term])
  83. ->orWhereRaw("TO_CHAR(expiry_date, 'DD/MM/YYYY') LIKE ?", [$term])
  84. ->orWhereHas('position', function ($p) use ($term) {
  85. $p->whereRaw('UNACCENT(LOWER(positions.name)) LIKE UNACCENT(?)', [$term]);
  86. });
  87. if ($cpfTerm) {
  88. $q->orWhere('cpf', 'LIKE', $cpfTerm);
  89. }
  90. });
  91. }
  92. if (isset($filters['first_access']) && $filters['first_access'] !== '') {
  93. $accessed = filter_var($filters['first_access'], FILTER_VALIDATE_BOOLEAN);
  94. $accessed ? $query->whereHas('accessLogs') : $query->whereDoesntHave('accessLogs');
  95. }
  96. return $query;
  97. }
  98. public function findById(int $id): ?User
  99. {
  100. return User::find($id);
  101. }
  102. public function create(array $data): User
  103. {
  104. if (empty($data['password'])) {
  105. $data['password'] = Str::random(32);
  106. }
  107. return User::create($data);
  108. }
  109. public function update(int $id, array $data): ?User
  110. {
  111. $model = $this->findById($id);
  112. if (!$model) {
  113. return null;
  114. }
  115. if (array_key_exists('password', $data) && empty($data['password'])) {
  116. unset($data['password']);
  117. }
  118. if (isset($data['status'])) {
  119. $newStatus = $data['status'] instanceof UserStatusEnum
  120. ? $data['status']
  121. : UserStatusEnum::from($data['status']);
  122. if ($newStatus === UserStatusEnum::INACTIVE && $model->status !== UserStatusEnum::INACTIVE) {
  123. $data['excluded_at'] = now();
  124. } elseif ($newStatus !== UserStatusEnum::INACTIVE) {
  125. $data['excluded_at'] = null;
  126. }
  127. }
  128. $model->update($data);
  129. return $model->fresh();
  130. }
  131. public function delete(int $id): bool
  132. {
  133. $model = $this->findById($id);
  134. if (!$model) {
  135. return false;
  136. }
  137. return $model->delete();
  138. }
  139. public function setOnLeave(int $id, int $byUserId): ?User
  140. {
  141. $model = $this->findById($id);
  142. if (!$model) return null;
  143. $model->update([
  144. 'status' => UserStatusEnum::ON_LEAVE,
  145. 'on_leave_at' => now(),
  146. 'on_leave_by_user_id' => $byUserId,
  147. ]);
  148. return $model->fresh();
  149. }
  150. public function approve(int $id): ?User
  151. {
  152. $model = $this->findById($id);
  153. if (!$model) return null;
  154. $model->update([
  155. 'status' => UserStatusEnum::ACTIVE,
  156. ]);
  157. return $model->fresh();
  158. }
  159. public function refuse(int $id): ?User
  160. {
  161. $model = $this->findById($id);
  162. if (!$model) return null;
  163. $model->update([
  164. 'status' => UserStatusEnum::REFUSED,
  165. ]);
  166. return $model->fresh();
  167. }
  168. public function getUserTypes(): array
  169. {
  170. return UserTypeEnum::toArray();
  171. }
  172. }