|
|
@@ -3,31 +3,47 @@
|
|
|
namespace App\Services;
|
|
|
|
|
|
use App\Enums\UserTypeEnum;
|
|
|
+use App\Models\Unit;
|
|
|
+use App\Models\UnitUser;
|
|
|
use App\Models\User;
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
+use Illuminate\Http\UploadedFile;
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
+use Illuminate\Support\Facades\Storage;
|
|
|
|
|
|
class UserService
|
|
|
{
|
|
|
public function authUser(): ?User
|
|
|
{
|
|
|
- $user = Auth::user();
|
|
|
- return $user;
|
|
|
+ return Auth::user();
|
|
|
}
|
|
|
|
|
|
public function getAll(): Collection
|
|
|
{
|
|
|
- return User::orderBy("created_at", "desc")->get();
|
|
|
+ return User::with('state')->orderBy('name')->get();
|
|
|
}
|
|
|
|
|
|
public function findById(int $id): ?User
|
|
|
{
|
|
|
- return User::find($id);
|
|
|
+ return User::with('state')->find($id);
|
|
|
}
|
|
|
|
|
|
public function create(array $data): User
|
|
|
{
|
|
|
- return User::create($data);
|
|
|
+ $unitId = $data['unit_id'] ?? null;
|
|
|
+ unset($data['unit_id']);
|
|
|
+
|
|
|
+ $data = $this->handleAvatar($data);
|
|
|
+ $user = User::create($data);
|
|
|
+
|
|
|
+ if ($unitId) {
|
|
|
+ UnitUser::create([
|
|
|
+ 'unit_id' => $unitId,
|
|
|
+ 'user_id' => $user->id,
|
|
|
+ ]);
|
|
|
+ }
|
|
|
+
|
|
|
+ return $user->load('state');
|
|
|
}
|
|
|
|
|
|
public function update(int $id, array $data): ?User
|
|
|
@@ -38,8 +54,10 @@ public function update(int $id, array $data): ?User
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
+ unset($data['unit_id']);
|
|
|
+ $data = $this->handleAvatar($data, $model->avatar_url);
|
|
|
$model->update($data);
|
|
|
- return $model->fresh();
|
|
|
+ return $model->fresh(['state']);
|
|
|
}
|
|
|
|
|
|
public function delete(int $id): bool
|
|
|
@@ -50,6 +68,10 @@ public function delete(int $id): bool
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
+ if ($model->avatar_url) {
|
|
|
+ Storage::delete($model->avatar_url);
|
|
|
+ }
|
|
|
+
|
|
|
return $model->delete();
|
|
|
}
|
|
|
|
|
|
@@ -57,4 +79,26 @@ public function getUserTypes(): array
|
|
|
{
|
|
|
return UserTypeEnum::toArray();
|
|
|
}
|
|
|
+
|
|
|
+ private function handleAvatar(array $data, ?string $oldAvatarPath = null): array
|
|
|
+ {
|
|
|
+ if (!isset($data['avatar'])) {
|
|
|
+ return $data;
|
|
|
+ }
|
|
|
+
|
|
|
+ if ($data['avatar'] instanceof UploadedFile) {
|
|
|
+ if ($oldAvatarPath) {
|
|
|
+ Storage::delete($oldAvatarPath);
|
|
|
+ }
|
|
|
+ $data['avatar_url'] = $data['avatar']->store('users/avatars');
|
|
|
+ } elseif (is_null($data['avatar'])) {
|
|
|
+ if ($oldAvatarPath) {
|
|
|
+ Storage::delete($oldAvatarPath);
|
|
|
+ }
|
|
|
+ $data['avatar_url'] = null;
|
|
|
+ }
|
|
|
+
|
|
|
+ unset($data['avatar']);
|
|
|
+ return $data;
|
|
|
+ }
|
|
|
}
|