|
|
@@ -2,8 +2,6 @@
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
-use App\Enums\UserTypeEnum;
|
|
|
-use App\Models\Unit;
|
|
|
use App\Models\UnitUser;
|
|
|
use App\Models\User;
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
@@ -20,17 +18,31 @@ public function authUser(): ?User
|
|
|
|
|
|
public function getAll(): Collection
|
|
|
{
|
|
|
- return User::with(['state', 'units'])->orderBy('name')->get();
|
|
|
+ return User::with(['state', 'units', 'userType'])->orderBy('name')->get();
|
|
|
+ }
|
|
|
+
|
|
|
+ public function getAllByUnit(): Collection
|
|
|
+ {
|
|
|
+ $unitId = Auth::user()->units->first()?->id;
|
|
|
+
|
|
|
+ if (!$unitId) {
|
|
|
+ return User::with(['state', 'units', 'userType'])->whereNull('id')->get();
|
|
|
+ }
|
|
|
+
|
|
|
+ return User::with(['state', 'units', 'userType'])
|
|
|
+ ->whereHas('units', fn($q) => $q->where('units.id', $unitId))
|
|
|
+ ->orderBy('name')
|
|
|
+ ->get();
|
|
|
}
|
|
|
|
|
|
public function findById(int $id): ?User
|
|
|
{
|
|
|
- return User::with(['state', 'units'])->find($id);
|
|
|
+ return User::with(['state', 'units', 'userType'])->find($id);
|
|
|
}
|
|
|
|
|
|
public function create(array $data): User
|
|
|
{
|
|
|
- $unitId = $data['unit_id'] ?? null;
|
|
|
+ $unitId = $data['unit_id'] ?? Auth::user()->units->first()?->id;
|
|
|
unset($data['unit_id']);
|
|
|
|
|
|
$data = $this->handleAvatar($data);
|
|
|
@@ -54,13 +66,16 @@ public function update(int $id, array $data): ?User
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
- $unitId = $data['unit_id'] ?? null;
|
|
|
+ $hasUnitId = array_key_exists('unit_id', $data);
|
|
|
+ $unitId = $data['unit_id'] ?? null;
|
|
|
unset($data['unit_id']);
|
|
|
|
|
|
$data = $this->handleAvatar($data, $model->avatar_url);
|
|
|
$model->update($data);
|
|
|
|
|
|
- $model->units()->sync($unitId ? [$unitId] : []);
|
|
|
+ if ($hasUnitId) {
|
|
|
+ $model->units()->sync($unitId ? [$unitId] : []);
|
|
|
+ }
|
|
|
|
|
|
return $model->fresh(['state', 'units']);
|
|
|
}
|
|
|
@@ -80,9 +95,9 @@ public function delete(int $id): bool
|
|
|
return $model->delete();
|
|
|
}
|
|
|
|
|
|
- public function getUserTypes(): array
|
|
|
+ public function getUserTypes(): \Illuminate\Database\Eloquent\Collection
|
|
|
{
|
|
|
- return UserTypeEnum::toArray();
|
|
|
+ return \App\Models\UserType::orderBy('label')->get();
|
|
|
}
|
|
|
|
|
|
private function handleAvatar(array $data, ?string $oldAvatarPath = null): array
|