UserService.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. // Suporta unit_ids[] (múltiplas) ou unit_id (retrocompatibilidade)
  37. $unitIds = $data['unit_ids'] ?? null;
  38. if (empty($unitIds) && isset($data['unit_id'])) {
  39. $unitIds = array_filter([$data['unit_id']]);
  40. }
  41. if (empty($unitIds) && ($data['access_scope'] ?? 'unit') === 'unit') {
  42. $fallback = Auth::user()->units->first()?->id;
  43. $unitIds = $fallback ? [$fallback] : [];
  44. }
  45. unset($data['unit_ids'], $data['unit_id']);
  46. $role = $this->resolveRole($data, $unitIds[0] ?? null);
  47. unset($data['user_type_id']);
  48. $data['user_type'] = $role?->slug ?? $data['user_type'];
  49. $data['franchisor_user_type_id'] = ($data['access_scope'] ?? 'unit') === 'franchisor' ? $role?->id : null;
  50. $data = $this->handleAvatar($data);
  51. $user = User::create($data);
  52. if (!empty($unitIds)) {
  53. $this->syncUnitRoles($user, $unitIds, $data['user_type']);
  54. }
  55. return $user->load('state', 'units');
  56. }
  57. public function update(int $id, array $data): ?User
  58. {
  59. $model = $this->findById($id);
  60. if (!$model) {
  61. return null;
  62. }
  63. // Suporta unit_ids[] (múltiplas) com fallback para unit_id (retrocompatibilidade)
  64. $hasUnitIds = array_key_exists('unit_ids', $data);
  65. $unitIds = $data['unit_ids'] ?? null;
  66. $hasUnitId = array_key_exists('unit_id', $data);
  67. $unitId = $data['unit_id'] ?? null;
  68. unset($data['unit_ids'], $data['unit_id']);
  69. $targetUnitId = $unitIds[0] ?? $unitId;
  70. $role = $this->resolveRole($data, $targetUnitId, $model);
  71. unset($data['user_type_id']);
  72. if ($role) {
  73. $data['user_type'] = $role->slug;
  74. $data['franchisor_user_type_id'] = ($data['access_scope'] ?? $model->access_scope) === 'franchisor'
  75. ? $role->id
  76. : null;
  77. }
  78. $data = $this->handleAvatar($data, $model->avatar_url);
  79. $model->update($data);
  80. if (($data['access_scope'] ?? $model->access_scope) === 'franchisor') {
  81. $model->units()->sync([]);
  82. } elseif ($hasUnitIds) {
  83. $this->syncUnitRoles($model, array_filter($unitIds ?? []), $data['user_type'] ?? $model->user_type);
  84. } elseif ($hasUnitId) {
  85. $this->syncUnitRoles($model, $unitId ? [$unitId] : [], $data['user_type'] ?? $model->user_type);
  86. }
  87. return $model->fresh(['state', 'units']);
  88. }
  89. public function delete(int $id): bool
  90. {
  91. $model = $this->findById($id);
  92. if (!$model) {
  93. return false;
  94. }
  95. if ($model->avatar_url) {
  96. Storage::delete($model->avatar_url);
  97. }
  98. return $model->delete();
  99. }
  100. public function getUserTypes(): \Illuminate\Database\Eloquent\Collection
  101. {
  102. $scope = request()->input('access_scope', Auth::user()?->access_scope);
  103. $unitId = request()->input('active_unit_id') ?? Auth::user()?->units()->value('units.id');
  104. return \App\Models\UserType::query()
  105. ->when($scope === 'unit', fn ($query) => $query->where('unit_id', $unitId))
  106. ->when($scope === 'franchisor', fn ($query) => $query->whereNull('unit_id'))
  107. ->orderBy('label')
  108. ->get();
  109. }
  110. private function handleAvatar(array $data, ?string $oldAvatarPath = null): array
  111. {
  112. if (!isset($data['avatar'])) {
  113. return $data;
  114. }
  115. if ($data['avatar'] instanceof UploadedFile) {
  116. if ($oldAvatarPath) {
  117. Storage::delete($oldAvatarPath);
  118. }
  119. $data['avatar_url'] = $data['avatar']->store('users/avatars');
  120. } elseif (is_null($data['avatar'])) {
  121. if ($oldAvatarPath) {
  122. Storage::delete($oldAvatarPath);
  123. }
  124. $data['avatar_url'] = null;
  125. }
  126. unset($data['avatar']);
  127. return $data;
  128. }
  129. private function resolveRole(array $data, ?int $unitId, ?User $user = null): ?\App\Models\UserType
  130. {
  131. if (!empty($data['user_type_id'])) {
  132. return \App\Models\UserType::find($data['user_type_id']);
  133. }
  134. $slug = $data['user_type'] ?? $user?->user_type;
  135. $scope = $data['access_scope'] ?? $user?->access_scope;
  136. $type = \App\Models\UserType::query()
  137. ->where('slug', $slug)
  138. ->when($scope === 'unit', fn ($query) => $query->where('unit_id', $unitId))
  139. ->when($scope === 'franchisor', fn ($query) => $query->whereNull('unit_id'))
  140. ->first();
  141. abort_if(!$type, 422, 'O perfil não pertence ao contexto selecionado.');
  142. return $type;
  143. }
  144. private function syncUnitRoles(User $user, array $unitIds, string $slug): void
  145. {
  146. $roles = \App\Models\UserType::query()
  147. ->whereIn('unit_id', $unitIds)
  148. ->where('slug', $slug)
  149. ->pluck('id', 'unit_id');
  150. abort_if($roles->count() !== count($unitIds), 422, 'O perfil precisa existir em todas as unidades selecionadas.');
  151. $user->units()->sync(collect($unitIds)->mapWithKeys(
  152. fn ($id) => [$id => ['user_type_id' => $roles[$id]]],
  153. )->all());
  154. }
  155. }