UserService.php 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. <?php
  2. namespace App\Services;
  3. use App\Models\UnitUser;
  4. use App\Models\User;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Http\UploadedFile;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Storage;
  9. class UserService
  10. {
  11. public function authUser(): ?User
  12. {
  13. return Auth::user()->load('units');
  14. }
  15. public function getAll(): Collection
  16. {
  17. return User::with(['state', 'units', 'userType'])->orderBy('name')->get();
  18. }
  19. public function getAllByUnit(): Collection
  20. {
  21. $unitId = request()->input('active_unit_id') ?? Auth::user()->units->first()?->id;
  22. if (!$unitId) {
  23. return User::with(['state', 'units', 'userType'])->whereNull('id')->get();
  24. }
  25. return User::with(['state', 'units', 'userType'])
  26. ->whereHas('units', fn($q) => $q->where('units.id', $unitId))
  27. ->orderBy('name')
  28. ->get();
  29. }
  30. public function findById(int $id): ?User
  31. {
  32. return User::with(['state', 'units', 'userType'])->find($id);
  33. }
  34. public function create(array $data): User
  35. {
  36. $this->assertMatchingAccessScope($data);
  37. // Suporta unit_ids[] (múltiplas) ou unit_id (retrocompatibilidade)
  38. $unitIds = $data['unit_ids'] ?? null;
  39. if (empty($unitIds) && isset($data['unit_id'])) {
  40. $unitIds = array_filter([$data['unit_id']]);
  41. }
  42. if (empty($unitIds) && ($data['access_scope'] ?? 'unit') === 'unit') {
  43. $fallback = Auth::user()->units->first()?->id;
  44. $unitIds = $fallback ? [$fallback] : [];
  45. }
  46. unset($data['unit_ids'], $data['unit_id']);
  47. $data = $this->handleAvatar($data);
  48. $user = User::create($data);
  49. if (!empty($unitIds)) {
  50. $user->units()->sync($unitIds);
  51. }
  52. return $user->load('state', 'units');
  53. }
  54. public function update(int $id, array $data): ?User
  55. {
  56. $model = $this->findById($id);
  57. if (!$model) {
  58. return null;
  59. }
  60. $this->assertMatchingAccessScope($data, $model);
  61. // Suporta unit_ids[] (múltiplas) com fallback para unit_id (retrocompatibilidade)
  62. $hasUnitIds = array_key_exists('unit_ids', $data);
  63. $unitIds = $data['unit_ids'] ?? null;
  64. $hasUnitId = array_key_exists('unit_id', $data);
  65. $unitId = $data['unit_id'] ?? null;
  66. unset($data['unit_ids'], $data['unit_id']);
  67. $data = $this->handleAvatar($data, $model->avatar_url);
  68. $model->update($data);
  69. if (($data['access_scope'] ?? $model->access_scope) === 'franchisor') {
  70. $model->units()->sync([]);
  71. } elseif ($hasUnitIds) {
  72. $model->units()->sync(array_filter($unitIds ?? []));
  73. } elseif ($hasUnitId) {
  74. $model->units()->sync($unitId ? [$unitId] : []);
  75. }
  76. return $model->fresh(['state', 'units']);
  77. }
  78. public function delete(int $id): bool
  79. {
  80. $model = $this->findById($id);
  81. if (!$model) {
  82. return false;
  83. }
  84. if ($model->avatar_url) {
  85. Storage::delete($model->avatar_url);
  86. }
  87. return $model->delete();
  88. }
  89. public function getUserTypes(): \Illuminate\Database\Eloquent\Collection
  90. {
  91. return \App\Models\UserType::query()
  92. ->when(request()->input('access_scope'), fn ($query, $scope) => $query->where('access_scope', $scope))
  93. ->orderBy('label')
  94. ->get();
  95. }
  96. private function handleAvatar(array $data, ?string $oldAvatarPath = null): array
  97. {
  98. if (!isset($data['avatar'])) {
  99. return $data;
  100. }
  101. if ($data['avatar'] instanceof UploadedFile) {
  102. if ($oldAvatarPath) {
  103. Storage::delete($oldAvatarPath);
  104. }
  105. $data['avatar_url'] = $data['avatar']->store('users/avatars');
  106. } elseif (is_null($data['avatar'])) {
  107. if ($oldAvatarPath) {
  108. Storage::delete($oldAvatarPath);
  109. }
  110. $data['avatar_url'] = null;
  111. }
  112. unset($data['avatar']);
  113. return $data;
  114. }
  115. private function assertMatchingAccessScope(array $data, ?User $user = null): void
  116. {
  117. $slug = $data['user_type'] ?? $user?->user_type;
  118. $scope = $data['access_scope'] ?? $user?->access_scope;
  119. $type = \App\Models\UserType::where('slug', $slug)->first();
  120. abort_if($type && $scope && $type->access_scope !== $scope, 422, 'O perfil não pertence ao tipo de acesso selecionado.');
  121. }
  122. }