diff --git a/app/Services/Admin/Master/DepartmentService.php b/app/Services/Admin/Master/DepartmentService.php index 591136f..cb258ef 100644 --- a/app/Services/Admin/Master/DepartmentService.php +++ b/app/Services/Admin/Master/DepartmentService.php @@ -4,6 +4,7 @@ use App\Models\Department; use App\Models\DepartmentLeadership; +use App\Models\Lecturer; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Collection; @@ -57,23 +58,53 @@ private function syncLeadership(Department $department, ?int $lecturerId, ?strin ->first(); if (! $lecturerId) { - $currentLeader?->update(['ended_at' => now()]); + if ($currentLeader) { + $currentLeader->update(['ended_at' => now()]); + $this->revokeKaprodiRoleIfNoLongerLeading($currentLeader->lecturer_id); + } return; } if ($currentLeader && $currentLeader->lecturer_id === $lecturerId) { $currentLeader->update(['started_at' => $startedAt ?? $currentLeader->started_at]); + $this->grantKaprodiRole($lecturerId); return; } - $currentLeader?->update(['ended_at' => now()]); + if ($currentLeader) { + $currentLeader->update(['ended_at' => now()]); + $this->revokeKaprodiRoleIfNoLongerLeading($currentLeader->lecturer_id); + } $department->leaderships()->create([ 'lecturer_id' => $lecturerId, 'started_at' => $startedAt ?? now(), ]); + + $this->grantKaprodiRole($lecturerId); + } + + private function grantKaprodiRole(int $lecturerId): void + { + $user = Lecturer::find($lecturerId)?->user; + + if ($user && ! $user->hasRole('kaprodi')) { + $user->assignRole('kaprodi'); + } + } + + private function revokeKaprodiRoleIfNoLongerLeading(int $lecturerId): void + { + $stillLeadsAnyDepartment = DepartmentLeadership::query() + ->where('lecturer_id', $lecturerId) + ->whereNull('ended_at') + ->exists(); + + if (! $stillLeadsAnyDepartment) { + Lecturer::find($lecturerId)?->user?->removeRole('kaprodi'); + } } public function delete(Department $department): bool