UserService.php 6.0 KB

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