UserService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\UserTypeEnum;
  4. use App\Models\Address;
  5. use App\Models\Client;
  6. use App\Models\User;
  7. use Illuminate\Database\Eloquent\Collection;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. class UserService
  12. {
  13. public function me(): ?User
  14. {
  15. return User::with(['provider', 'client'])->find(Auth::id());
  16. }
  17. public function getAll(): Collection
  18. {
  19. return User::query()->orderBy("created_at", "desc")->get();
  20. }
  21. public function findById(int $id): ?User
  22. {
  23. return User::find($id);
  24. }
  25. public function create(array $data): User
  26. {
  27. return User::create($data);
  28. }
  29. public function update(int $id, array $data): ?User
  30. {
  31. $model = $this->findById($id);
  32. if (!$model) {
  33. return null;
  34. }
  35. $model->update($data);
  36. return $model->fresh();
  37. }
  38. public function delete(int $id): bool
  39. {
  40. $model = $this->findById($id);
  41. if (!$model) {
  42. return false;
  43. }
  44. return $model->delete();
  45. }
  46. public function updateMe(array $data): User
  47. {
  48. try {
  49. DB::beginTransaction();
  50. $user = User::with(['client'])->findOrFail(Auth::id());
  51. $userFields = array_filter(
  52. array_intersect_key($data, array_flip(['name', 'email', 'phone', 'language'])),
  53. fn($v) => $v !== null,
  54. );
  55. if (!empty($userFields)) {
  56. $user->update($userFields);
  57. }
  58. if (array_key_exists('document', $data)) {
  59. $client = $user->client ?? Client::create(['user_id' => $user->id]);
  60. $client->document = $data['document'];
  61. $client->save();
  62. }
  63. $user->load('client');
  64. $registrationComplete = !empty($user->name)
  65. && !empty($user->client?->document)
  66. && Address::where('source', 'client')->where('source_id', $user->client->id)->exists();
  67. if ($user->registration_complete !== $registrationComplete) {
  68. $user->registration_complete = $registrationComplete;
  69. $user->save();
  70. }
  71. DB::commit();
  72. return $user->fresh(['client']);
  73. } catch (\Exception $e) {
  74. DB::rollBack();
  75. Log::error('Erro ao atualizar perfil.', ['error' => $e->getMessage()]);
  76. throw $e;
  77. }
  78. }
  79. public function getUserTypes(): array
  80. {
  81. return UserTypeEnum::toArray();
  82. }
  83. }