diff --git a/app/Http/Controllers/Admin/DashboardController.php b/app/Http/Controllers/Admin/DashboardController.php new file mode 100644 index 0000000..1622379 --- /dev/null +++ b/app/Http/Controllers/Admin/DashboardController.php @@ -0,0 +1,54 @@ + User::count(), + 'total_roles' => Role::count(), + 'total_employees' => Employee::count(), + 'total_vehicles' => Vehicle::count(), + 'total_guards' => SecurityGuard::count(), + 'activities_today' => VehicleActivity::whereDate('created_at', $today)->count(), + 'activities_pending' => VehicleActivity::pending()->count(), + 'activities_approved' => VehicleActivity::approved()->whereDate('created_at', $today)->count(), + ]; + + $usersByRole = User::with('roles') + ->get() + ->groupBy(function ($u) { + return $u->roles->first()?->name ?? $u->role ?? 'Tanpa Role'; + }) + ->map->count(); + + $recentUsers = User::with(['roles', 'gate']) + ->latest() + ->take(6) + ->get(); + + $recentActivities = VehicleActivity::with(['vehicle', 'driver', 'gate']) + ->latest() + ->take(5) + ->get(); + + return view('admin.dashboard', compact('metrics', 'usersByRole', 'recentUsers', 'recentActivities')); + } +} diff --git a/app/Http/Controllers/Admin/RolePermissionController.php b/app/Http/Controllers/Admin/RolePermissionController.php new file mode 100644 index 0000000..23e5ab6 --- /dev/null +++ b/app/Http/Controllers/Admin/RolePermissionController.php @@ -0,0 +1,92 @@ +orderBy('id')->get(); + $modules = config('rbac_permissions.modules', []); + + return view('admin.roles.index', compact('roles', 'modules')); + } + + /** + * Buat Role baru di sistem. + */ + public function storeRole(Request $request): RedirectResponse + { + $request->validate([ + 'name' => ['required', 'string', 'max:50', 'unique:roles,name'], + ], [ + 'name.required' => 'Nama role wajib diisi.', + 'name.unique' => 'Role dengan nama tersebut sudah ada.', + ]); + + $role = Role::create([ + 'name' => strtolower(trim(str_replace(' ', '_', $request->input('name')))), + 'guard_name' => 'web', + ]); + + return redirect()->route('admin.roles.index') + ->with('success', "Role [{$role->name}] berhasil ditambahkan ke sistem."); + } + + /** + * Perbarui hak akses (permissions) untuk suatu role dari matriks. + */ + public function updatePermissions(Request $request, int $roleId): RedirectResponse + { + $role = Role::findOrFail($roleId); + + // Jangan izinkan modifikasi permission super_admin karena otomatis memiliki seluruh akses + if ($role->name === 'super_admin') { + return redirect()->route('admin.roles.index') + ->with('error', 'Role Super Administrator selalu memiliki hak akses penuh (bypassed) dan tidak dapat dikurangi.'); + } + + $selectedPermissions = $request->input('permissions', []); + $role->syncPermissions($selectedPermissions); + + // Reset permission cache + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + return redirect()->route('admin.roles.index') + ->with('success', "Matriks permission untuk role [{$role->name}] berhasil diperbarui."); + } + + /** + * Hapus role kustom dari sistem. + */ + public function destroyRole(int $roleId): RedirectResponse + { + $role = Role::findOrFail($roleId); + + // Proteksi role inti sistem + $coreRoles = ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']; + if (in_array($role->name, $coreRoles)) { + return redirect()->route('admin.roles.index') + ->with('error', "Aksi Ditolak: Role inti sistem [{$role->name}] tidak dapat dihapus."); + } + + $name = $role->name; + $role->delete(); + + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + return redirect()->route('admin.roles.index') + ->with('success', "Role [{$name}] berhasil dihapus dari sistem."); + } +} diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php new file mode 100644 index 0000000..6c331b0 --- /dev/null +++ b/app/Http/Controllers/Admin/UserController.php @@ -0,0 +1,174 @@ +latest(); + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function ($q) use ($search) { + $q->where('name', 'like', "%{$search}%") + ->orWhere('username', 'like', "%{$search}%") + ->orWhere('email', 'like', "%{$search}%"); + }); + } + + if ($request->filled('role')) { + $roleFilter = $request->input('role'); + $query->where(function ($q) use ($roleFilter) { + $q->whereHas('roles', fn ($rq) => $rq->where('name', $roleFilter)) + ->orWhere('role', $roleFilter); + }); + } + + $users = $query->with('permissions')->paginate(15)->withQueryString(); + $roles = Role::orderBy('name')->get(); + $gates = Gate::where('is_active', true)->orderBy('name')->get(); + $modules = config('rbac_permissions.modules', []); + + return view('admin.users.index', compact('users', 'roles', 'gates', 'modules')); + } + + /** + * Simpan pengguna baru ke sistem beserta penugasan Spatie Role. + */ + public function store(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'username' => ['required', 'string', 'max:50', 'unique:users,username'], + 'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'], + 'password' => ['required', 'string', 'min:6'], + 'role' => ['required', 'string', 'exists:roles,name'], + 'gate_id' => ['nullable', 'exists:gates,id'], + ], [ + 'name.required' => 'Nama lengkap wajib diisi.', + 'username.required' => 'Username wajib diisi.', + 'username.unique' => 'Username tersebut sudah digunakan.', + 'email.required' => 'Email wajib diisi.', + 'email.unique' => 'Email tersebut sudah terdaftar.', + 'password.required' => 'Password wajib diisi.', + 'password.min' => 'Password minimal terdiri dari 6 karakter.', + 'role.required' => 'Role wajib dipilih.', + 'role.exists' => 'Role yang dipilih tidak valid.', + ]); + + $user = User::create([ + 'name' => $validated['name'], + 'username' => $validated['username'], + 'email' => $validated['email'], + 'password' => Hash::make($validated['password']), + 'role' => $validated['role'], // Simpan ke kolom legacy untuk backwards-compat + 'gate_id' => $validated['gate_id'] ?? null, + ]); + + // Assign Spatie Role + $user->assignRole($validated['role']); + + // Sync Direct Permissions (jika ada izin khusus tambahan) + if ($request->has('direct_permissions')) { + $user->syncPermissions($request->input('direct_permissions', [])); + } + + // Reset permission cache Spatie + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + return redirect()->route('admin.users.index') + ->with('success', "Akun pengguna [{$user->name}] berhasil dibuat dengan role [{$validated['role']}]."); + } + + /** + * Perbarui data pengguna & perbarui Role Spatie serta Direct Permissions. + */ + public function update(Request $request, int $id): RedirectResponse + { + $user = User::findOrFail($id); + + $validated = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'username' => ['required', 'string', 'max:50', Rule::unique('users', 'username')->ignore($user->id)], + 'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)], + 'password' => ['nullable', 'string', 'min:6'], + 'role' => ['required', 'string', 'exists:roles,name'], + 'gate_id' => ['nullable', 'exists:gates,id'], + ], [ + 'name.required' => 'Nama lengkap wajib diisi.', + 'username.required' => 'Username wajib diisi.', + 'username.unique' => 'Username tersebut sudah digunakan oleh akun lain.', + 'email.required' => 'Email wajib diisi.', + 'email.unique' => 'Email tersebut sudah digunakan oleh akun lain.', + 'password.min' => 'Password minimal 6 karakter jika ingin diubah.', + 'role.required' => 'Role wajib dipilih.', + ]); + + $user->name = $validated['name']; + $user->username = $validated['username']; + $user->email = $validated['email']; + $user->role = $validated['role']; + $user->gate_id = $validated['gate_id'] ?? null; + + if (!empty($validated['password'])) { + $user->password = Hash::make($validated['password']); + } + + $user->save(); + + // Sync Spatie Role + $user->syncRoles([$validated['role']]); + + // Sync Direct Permissions + $user->syncPermissions($request->input('direct_permissions', [])); + + // Reset permission cache Spatie + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + return redirect()->route('admin.users.index') + ->with('success', "Data pengguna [{$user->name}] berhasil diperbarui."); + } + + /** + * Hapus akun pengguna dari sistem. + */ + public function destroy(int $id): RedirectResponse + { + $user = User::findOrFail($id); + + // Proteksi: jangan hapus akun sendiri yang sedang login + if (Auth::id() === $user->id) { + return redirect()->route('admin.users.index') + ->with('error', 'Aksi Ditolak: Anda tidak dapat menghapus akun Anda sendiri saat sedang login.'); + } + + // Proteksi: akun superadmin utama tidak boleh dihapus + if ($user->username === 'superadmin') { + return redirect()->route('admin.users.index') + ->with('error', 'Aksi Ditolak: Akun Super Administrator utama sistem tidak dapat dihapus.'); + } + + $name = $user->name; + $user->syncRoles([]); + $user->delete(); + + return redirect()->route('admin.users.index') + ->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem."); + } +} diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 500d7ef..c42b8f5 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -71,6 +71,10 @@ class LoginController extends Controller */ private function redirectBasedOnRole($user): RedirectResponse { + if ($user->isSuperAdmin()) { + return redirect()->route('admin.dashboard'); + } + return match ($user->role) { 'super_admin', 'superadmin', 'admin' => redirect()->route('superadmin.dashboard'), 'hse_admin' => redirect()->route('hse.dashboard'), diff --git a/app/Http/Controllers/Hse/EmployeeController.php b/app/Http/Controllers/Hse/EmployeeController.php index ac047c4..e0c56cf 100644 --- a/app/Http/Controllers/Hse/EmployeeController.php +++ b/app/Http/Controllers/Hse/EmployeeController.php @@ -120,32 +120,74 @@ class EmployeeController extends Controller } /** - * Pendaftaran master karyawan baru dialihkan ke Super Admin. + * Simpan data karyawan baru beserta izin SIMPER (Form modal tambah karyawan). */ public function store(Request $request): RedirectResponse { - return back()->with('error', 'Pendaftaran master data karyawan baru hanya dapat dilakukan oleh Super Admin melalui menu Manajemen Akun.'); + $validated = $request->validate([ + 'nik' => ['required', 'string', 'max:50', 'unique:employees,nik'], + 'name' => ['required', 'string', 'max:100'], + 'unit_kerja' => ['required', 'string'], + 'division' => ['required', 'string'], + 'position' => ['required', 'string'], + 'is_operator' => ['required', 'in:1,0'], + 'simper_expired_at' => ['nullable', 'date'], + ], [ + 'nik.required' => 'NIK wajib diisi.', + 'nik.unique' => 'NIK sudah terdaftar dalam sistem.', + 'name.required' => 'Nama karyawan wajib diisi.', + 'unit_kerja.required' => 'Unit kerja wajib dipilih.', + 'division.required' => 'Divisi wajib dipilih.', + 'position.required' => 'Posisi / Jabatan wajib diisi.', + 'is_operator.required' => 'Pilih apakah karyawan berstatus Operator / Driver.', + ]); + + $isOperator = (bool) $validated['is_operator']; + $simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null; + + Employee::create([ + 'nik' => $validated['nik'], + 'name' => $validated['name'], + 'unit_kerja' => $validated['unit_kerja'], + 'division' => $validated['division'], + 'position' => $validated['position'], + 'is_operator' => $isOperator, + 'simper_expired_at' => $simperExpiredAt, + ]); + + return back()->with('success', "Data karyawan {$validated['name']} berhasil ditambahkan."); } /** - * Perpanjang atau perbarui status driver & masa berlaku SIMPER karyawan. - * Master data profil karyawan dikelola terpusat oleh Super Admin. + * Perpanjang atau perbarui data karyawan & SIMPER. */ public function update(Request $request, int $id): RedirectResponse { $employee = Employee::findOrFail($id); $validated = $request->validate([ + 'nik' => ['sometimes', 'required', 'string', 'max:50', 'unique:employees,nik,' . $employee->id], + 'name' => ['sometimes', 'required', 'string', 'max:100'], + 'unit_kerja' => ['sometimes', 'required', 'string'], + 'division' => ['sometimes', 'required', 'string'], + 'position' => ['sometimes', 'required', 'string'], 'is_operator' => ['required', 'in:1,0'], 'simper_expired_at' => ['nullable', 'date'], ], [ + 'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.', + 'name.required' => 'Nama lengkap wajib diisi.', 'is_operator.required' => 'Status driver wajib dipilih.', ]); $isOperator = (bool) $validated['is_operator']; - $simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null; + $simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? $employee->simper_expired_at) : null; $employee->update([ + 'nik' => $validated['nik'] ?? $employee->nik, + 'name' => $validated['name'] ?? $employee->name, + 'unit_kerja' => $validated['unit_kerja'] ?? $employee->unit_kerja, + 'division' => $validated['division'] ?? $employee->division, + 'position' => $validated['position'] ?? $employee->position, 'is_operator' => $isOperator, 'simper_expired_at' => $simperExpiredAt, ]); diff --git a/app/Http/Controllers/SuperAdmin/DashboardController.php b/app/Http/Controllers/SuperAdmin/DashboardController.php deleted file mode 100644 index 5fce118..0000000 --- a/app/Http/Controllers/SuperAdmin/DashboardController.php +++ /dev/null @@ -1,17 +0,0 @@ -query('role'); - $search = trim((string) $request->query('search', '')); - - $query = User::with(['gate', 'securityGuard.gate', 'employee'])->latest(); - - if ($roleFilter && $roleFilter !== 'all') { - if ($roleFilter === 'admin_group') { - $query->whereIn('role', ['super_admin', 'superadmin', 'admin', 'hse_admin', 'qma_admin', 'pg_admin']); - } elseif ($roleFilter === 'super_admin') { - $query->whereIn('role', ['super_admin', 'superadmin', 'admin']); - } else { - $query->where('role', $roleFilter); - } - } - - if ($search !== '') { - $query->where(function ($q) use ($search) { - $q->where('name', 'like', "%{$search}%") - ->orWhere('username', 'like', "%{$search}%") - ->orWhere('email', 'like', "%{$search}%"); - }); - } - - $users = $query->paginate(15)->withQueryString(); - - // Ringkasan Statistik Pengguna - $stats = [ - 'total' => User::count(), - 'super_admin' => User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count(), - 'hse_admin' => User::where('role', 'hse_admin')->count(), - 'qma_admin' => User::where('role', 'qma_admin')->count(), - 'pg_admin' => User::where('role', 'pg_admin')->count(), - 'gate_officer' => User::where('role', 'gate_officer')->count(), - 'employee' => User::where('role', 'employee')->count(), - ]; - - // Daftar Gerbang Aktif untuk Pilihan Pos Satpam - $gates = Gate::where('is_active', true)->orderBy('name')->get(); - - return view('superadmin.roles_index', compact('users', 'stats', 'gates', 'roleFilter', 'search')); - } - - /** - * Simpan akun admin / pengguna baru. - */ - public function store(Request $request): RedirectResponse - { - $validated = $request->validate([ - 'name' => ['required', 'string', 'max:255'], - 'username' => ['required', 'string', 'max:50', 'regex:/^[a-zA-Z0-9._-]+$/', 'unique:users,username'], - 'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'], - 'password' => ['nullable', 'string', 'min:6'], - 'role' => ['required', 'string', Rule::in(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'])], - 'gate_id' => ['nullable', 'exists:gates,id'], - ], [ - 'username.unique' => 'Username tersebut sudah digunakan oleh akun lain.', - 'username.regex' => 'Username hanya boleh berupa huruf, angka, titik (.), tanda hubung (-) dan garis bawah (_).', - 'email.unique' => 'Email tersebut sudah terdaftar di sistem.', - 'password.min' => 'Password minimal terdiri dari 6 karakter.', - 'role.in' => 'Pilihan role tidak valid.', - ]); - - // Jika bukan gate_officer, kosongkan gate_id - if ($validated['role'] !== 'gate_officer') { - $validated['gate_id'] = null; - } - - // Default password ke 'password' jika kosong atau tidak diisi - $rawPassword = !empty($validated['password']) ? $validated['password'] : 'password'; - $validated['password'] = Hash::make($rawPassword); - - $user = User::create($validated); - - // Jika role adalah 'employee', buat juga record master Employee (Unit Kerja, Divisi, Jabatan Wajib Diisi) - if ($validated['role'] === 'employee') { - $empData = $request->validate([ - 'unit_kerja' => ['required', 'string', 'max:100'], - 'division' => ['required', 'string', 'max:100'], - 'position' => ['required', 'string', 'max:100'], - ], [ - 'unit_kerja.required' => 'Unit kerja wajib dipilih untuk karyawan.', - 'division.required' => 'Divisi wajib dipilih untuk karyawan.', - 'position.required' => 'Jabatan wajib diisi untuk karyawan.', - ]); - - $nik = $validated['username']; - - \App\Models\Employee::create([ - 'user_id' => $user->id, - 'nik' => $nik, - 'name' => $validated['name'], - 'unit_kerja' => $empData['unit_kerja'], - 'division' => $empData['division'], - 'position' => $empData['position'], - 'is_operator' => false, // Default bukan driver, akan diatur oleh Admin HSE - 'simper_expired_at' => null, - ]); - } - - return redirect()->route('superadmin.roles.index') - ->with('success', "Akun '{$validated['name']}' dengan role '{$validated['role']}' berhasil dibuat."); - } - - /** - * Perbarui data akun pengguna. - */ - public function update(Request $request, int $id): RedirectResponse - { - $user = User::findOrFail($id); - - $validated = $request->validate([ - 'name' => ['required', 'string', 'max:255'], - 'username' => ['required', 'string', 'max:50', 'regex:/^[a-zA-Z0-9._-]+$/', Rule::unique('users', 'username')->ignore($user->id)], - 'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)], - 'password' => ['nullable', 'string', 'min:6'], - 'role' => ['required', 'string', Rule::in(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'])], - 'gate_id' => ['nullable', 'exists:gates,id'], - ], [ - 'username.unique' => 'Username tersebut sudah digunakan oleh akun lain.', - 'username.regex' => 'Username hanya boleh berupa huruf, angka, titik (.), tanda hubung (-) dan garis bawah (_).', - 'email.unique' => 'Email tersebut sudah terdaftar di sistem.', - 'password.min' => 'Password baru minimal terdiri dari 6 karakter.', - ]); - - // Keamanan: Cegah super admin terakhir mengubah rolenya sendiri menjadi role biasa - if ($user->id === Auth::id() && $validated['role'] !== 'super_admin') { - $superAdminCount = User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count(); - if ($superAdminCount <= 1) { - return back()->with('error', 'Gagal: Anda adalah satu-satunya Super Admin aktif di sistem.'); - } - } - - if ($validated['role'] !== 'gate_officer') { - $validated['gate_id'] = null; - } - - if (!empty($validated['password'])) { - $validated['password'] = Hash::make($validated['password']); - } else { - unset($validated['password']); - } - - $user->update($validated); - - // Jika user ini adalah karyawan, sinkronkan nama, NIK (dari username), dan data kerjanya (wajib diisi) - if ($user->role === 'employee' || $user->employee) { - $unitKerja = $request->input('employee_unit_kerja') ?? $request->input('unit_kerja'); - $division = $request->input('employee_division') ?? $request->input('division'); - $position = $request->input('employee_position') ?? $request->input('position'); - - if ($user->role === 'employee' && (empty($unitKerja) || empty($division) || empty($position))) { - return back()->withErrors([ - 'employee_unit_kerja' => 'Unit kerja, divisi, dan jabatan wajib diisi untuk akun karyawan.', - ])->withInput(); - } - - $empFields = [ - 'name' => $user->name, - 'nik' => $user->username, - ]; - if (!empty($unitKerja)) { - $empFields['unit_kerja'] = $unitKerja; - } - if (!empty($division)) { - $empFields['division'] = $division; - } - if (!empty($position)) { - $empFields['position'] = $position; - } - - if ($user->employee) { - $user->employee->update($empFields); - } else { - $empFields['user_id'] = $user->id; - $empFields['is_operator'] = false; - $empFields['simper_expired_at'] = null; - \App\Models\Employee::create($empFields); - } - } - - return redirect()->route('superadmin.roles.index') - ->with('success', "Data akun '{$user->name}' berhasil diperbarui."); - } - - /** - * Hapus akun pengguna. - */ - public function destroy(int $id): RedirectResponse - { - $user = User::findOrFail($id); - - // Keamanan 1: Cegah Super Admin menghapus akunnya sendiri - if ($user->id === Auth::id()) { - return back()->with('error', 'Operasi ditolak: Anda tidak dapat menghapus akun Anda sendiri.'); - } - - // Keamanan 2: Cegah menghapus jika merupakan super admin terakhir - if ($user->isSuperAdmin()) { - $superAdminCount = User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count(); - if ($superAdminCount <= 1) { - return back()->with('error', 'Operasi ditolak: Akun Super Admin terakhir tidak boleh dihapus.'); - } - } - - // Keamanan 3: Cegah penghapusan jika Karyawan memiliki riwayat aktivitas atau P2H - if ($user->employee) { - if ($user->employee->activities()->exists()) { - return back()->with('error', "Operasi ditolak: Akun '{$user->name}' tidak dapat dihapus karena memiliki riwayat log pergerakan kendaraan di pos gerbang."); - } - if ($user->employee->p2hRecords()->exists()) { - return back()->with('error', "Operasi ditolak: Akun '{$user->name}' tidak dapat dihapus karena memiliki riwayat checksheet inspeksi keselamatan P2H."); - } - } - - // Keamanan 4: Cegah penghapusan jika Petugas Satpam memiliki riwayat validasi pos gerbang - if ($user->securityGuard) { - if ($user->securityGuard->activities()->exists()) { - return back()->with('error', "Operasi ditolak: Petugas Satpam '{$user->name}' tidak dapat dihapus karena telah memvalidasi aktivitas kendaraan di pos gerbang."); - } - } - - $userName = $user->name; - DB::transaction(function () use ($user) { - if ($user->employee) { - $user->employee->delete(); - } - if ($user->securityGuard) { - $user->securityGuard->delete(); - } - $user->delete(); - }); - - return redirect()->route('superadmin.roles.index') - ->with('success', "Akun '{$userName}' telah berhasil dihapus dari sistem."); - } - - /** - * Reset password akun pengguna menjadi default "password". - */ - public function resetPassword(int $id): RedirectResponse - { - $user = User::findOrFail($id); - $user->update([ - 'password' => Hash::make('password'), - ]); - - return redirect()->route('superadmin.roles.index') - ->with('success', "Password akun '{$user->name}' berhasil direset ke default ('password')."); - } -} diff --git a/app/Http/Middleware/CheckRole.php b/app/Http/Middleware/CheckRole.php index a65c132..0094817 100644 --- a/app/Http/Middleware/CheckRole.php +++ b/app/Http/Middleware/CheckRole.php @@ -19,10 +19,16 @@ class CheckRole return redirect()->route('login')->with('error', 'Silakan login terlebih dahulu untuk mengakses menu ini.'); } - $userRole = $request->user()->role; + $user = $request->user(); + $userRole = $user->role; - // Role 'super_admin' dan 'admin' selalu memiliki hak akses penuh ke seluruh modul - if (in_array($userRole, ['super_admin', 'superadmin', 'admin']) || in_array($userRole, $roles)) { + // Role 'super_admin', 'superadmin', dan 'admin' selalu memiliki hak akses penuh ke seluruh modul + if (in_array($userRole, ['super_admin', 'superadmin', 'admin']) || (method_exists($user, 'hasRole') && ($user->hasRole('super_admin') || $user->hasRole('admin')))) { + return $next($request); + } + + // Cek via kolom role string atau Spatie hasAnyRole + if (in_array($userRole, $roles) || (method_exists($user, 'hasAnyRole') && $user->hasAnyRole($roles))) { return $next($request); } diff --git a/app/Models/User.php b/app/Models/User.php index c4ea9a2..e2d32cb 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -9,11 +9,42 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; +use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { /** @use HasFactory */ - use HasFactory, Notifiable; + use HasFactory, Notifiable, HasRoles; + + /** + * The "booted" method of the model. + */ + protected static function booted(): void + { + static::created(function (User $user) { + if ($user->role && \Illuminate\Support\Facades\Schema::hasTable('roles')) { + $role = \Spatie\Permission\Models\Role::where('name', $user->role)->first(); + if ($role && !$user->hasRole($user->role)) { + $user->assignRole($role); + } + } + }); + + static::deleting(function (User $user) { + if ($user->employee) { + if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) { + throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H."); + } + $user->employee->delete(); + } + if ($user->securityGuard) { + if ($user->securityGuard->activities()->exists()) { + throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang."); + } + $user->securityGuard->delete(); + } + }); + } /** * The attributes that are mass assignable. @@ -52,24 +83,6 @@ class User extends Authenticatable ]; } - protected static function booted(): void - { - static::deleting(function (User $user) { - if ($user->employee) { - if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) { - throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H."); - } - $user->employee->delete(); - } - if ($user->securityGuard) { - if ($user->securityGuard->activities()->exists()) { - throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang."); - } - $user->securityGuard->delete(); - } - }); - } - public function gate(): BelongsTo { return $this->belongsTo(Gate::class); @@ -87,36 +100,36 @@ class User extends Authenticatable public function isEmployee(): bool { - return $this->role === 'employee'; + return $this->role === 'employee' || $this->hasRole('employee'); } public function isGateOfficer(): bool { - return $this->role === 'gate_officer'; + return $this->role === 'gate_officer' || $this->hasRole('gate_officer'); } public function isHseAdmin(): bool { - return $this->role === 'hse_admin'; + return $this->isSuperAdmin() || $this->role === 'hse_admin' || $this->hasRole('hse_admin'); } public function isQmaAdmin(): bool { - return $this->role === 'qma_admin'; + return $this->isSuperAdmin() || $this->role === 'qma_admin' || $this->hasRole('qma_admin'); } public function isPgAdmin(): bool { - return $this->role === 'pg_admin'; + return $this->isSuperAdmin() || $this->role === 'pg_admin' || $this->hasRole('pg_admin'); } public function isSuperAdmin(): bool { - return in_array($this->role, ['super_admin', 'superadmin']); + return in_array($this->role, ['super_admin', 'superadmin']) || $this->hasRole('super_admin'); } public function isAdmin(): bool { - return in_array($this->role, ['admin', 'super_admin', 'superadmin']); + return $this->isSuperAdmin() || in_array($this->role, ['admin', 'super_admin', 'superadmin']) || $this->hasRole('admin'); } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 48418dd..3cbc229 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,7 @@ namespace App\Providers; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider @@ -21,5 +22,10 @@ class AppServiceProvider extends ServiceProvider { \Carbon\Carbon::setLocale('id'); date_default_timezone_set(config('app.timezone', 'Asia/Jakarta')); + + // Super Admin bypass: secara otomatis memiliki izin untuk semua ability + Gate::before(function ($user, $ability) { + return ($user->role === 'super_admin' || $user->hasRole('super_admin')) ? true : null; + }); } } diff --git a/bootstrap/app.php b/bootstrap/app.php index 15f39a6..f9aafcb 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -13,6 +13,8 @@ return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware): void { $middleware->alias([ 'role' => \App\Http\Middleware\CheckRole::class, + 'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class, + 'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class, ]); }) ->withExceptions(function (Exceptions $exceptions): void { diff --git a/composer.json b/composer.json index e6004b7..279a4eb 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,8 @@ "php": "^8.2", "laravel/framework": "^12.0", "laravel/tinker": "^2.10.1", - "simplesoftwareio/simple-qrcode": "*" + "simplesoftwareio/simple-qrcode": "*", + "spatie/laravel-permission": "^8.3" }, "require-dev": { "fakerphp/faker": "^1.23", diff --git a/composer.lock b/composer.lock index 7c3fb08..4d72ed8 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "95d64c36b170378a8682c5138963ba09", + "content-hash": "170b1c005f6855019bb44940201e3dd9", "packages": [ { "name": "bacon/bacon-qr-code", @@ -3475,6 +3475,155 @@ }, "time": "2021-02-08T20:43:55+00:00" }, + { + "name": "spatie/laravel-package-tools", + "version": "1.93.3", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-package-tools.git", + "reference": "7aeef26bd8d4909bec744dbf47aee7d1395588c1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-package-tools/zipball/7aeef26bd8d4909bec744dbf47aee7d1395588c1", + "reference": "7aeef26bd8d4909bec744dbf47aee7d1395588c1", + "shasum": "" + }, + "require": { + "illuminate/contracts": "^10.0|^11.0|^12.0|^13.0", + "php": "^8.1" + }, + "require-dev": { + "mockery/mockery": "^1.5", + "orchestra/testbench": "^8.0|^9.2|^10.0|^11.0", + "pestphp/pest": "^2.1|^3.1|^4.0", + "phpunit/php-code-coverage": "^10.0|^11.0|^12.0", + "phpunit/phpunit": "^10.5|^11.5|^12.5", + "spatie/pest-plugin-test-time": "^2.2|^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Spatie\\LaravelPackageTools\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Freek Van der Herten", + "email": "freek@spatie.be", + "role": "Developer" + } + ], + "description": "Tools for creating Laravel packages", + "homepage": "https://github.com/spatie/laravel-package-tools", + "keywords": [ + "laravel-package-tools", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/laravel-package-tools/issues", + "source": "https://github.com/spatie/laravel-package-tools/tree/1.93.3" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2026-09-28T07:16:50+00:00" + }, + { + "name": "spatie/laravel-permission", + "version": "8.3.0", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-permission.git", + "reference": "60e8ed5b2fbf043c2264433fc2680c76b8b66aa6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-permission/zipball/60e8ed5b2fbf043c2264433fc2680c76b8b66aa6", + "reference": "60e8ed5b2fbf043c2264433fc2680c76b8b66aa6", + "shasum": "" + }, + "require": { + "illuminate/auth": "^12.0|^13.0", + "illuminate/container": "^12.0|^13.0", + "illuminate/contracts": "^12.0|^13.0", + "illuminate/database": "^12.0|^13.0", + "php": "^8.3", + "spatie/laravel-package-tools": "^1.0" + }, + "require-dev": { + "larastan/larastan": "^3.9", + "laravel/octane": "^2.0", + "laravel/passport": "^13.0", + "laravel/pint": "^1.0", + "orchestra/testbench": "^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0", + "pestphp/pest-plugin-laravel": "^3.0|^4.1", + "phpstan/phpstan": "^2.1" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Spatie\\Permission\\PermissionServiceProvider" + ] + }, + "branch-alias": { + "dev-main": "8.x-dev", + "dev-master": "8.x-dev" + } + }, + "autoload": { + "files": [ + "src/helpers.php" + ], + "psr-4": { + "Spatie\\Permission\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Freek Van der Herten", + "email": "freek@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "Permission handling for Laravel 12 and up", + "homepage": "https://github.com/spatie/laravel-permission", + "keywords": [ + "acl", + "laravel", + "permission", + "permissions", + "rbac", + "roles", + "security", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/laravel-permission/issues", + "source": "https://github.com/spatie/laravel-permission/tree/8.3.0" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2026-07-03T15:36:01+00:00" + }, { "name": "symfony/clock", "version": "v7.4.8", diff --git a/config/permission.php b/config/permission.php new file mode 100644 index 0000000..8f1f452 --- /dev/null +++ b/config/permission.php @@ -0,0 +1,219 @@ + [ + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * Eloquent model should be used to retrieve your permissions. Of course, it + * is often just the "Permission" model but you may use whatever you like. + * + * The model you want to use as a Permission model needs to implement the + * `Spatie\Permission\Contracts\Permission` contract. + */ + + 'permission' => Permission::class, + + /* + * When using the "HasRoles" trait from this package, we need to know which + * Eloquent model should be used to retrieve your roles. Of course, it + * is often just the "Role" model but you may use whatever you like. + * + * The model you want to use as a Role model needs to implement the + * `Spatie\Permission\Contracts\Role` contract. + */ + + 'role' => Role::class, + + /* + * When using the "Teams" feature from this package, we need to know which + * Eloquent model should be used to retrieve your teams. Of course, it + * is often just the "Team" model but you may use whatever you like. + */ + 'team' => null, + + /* + * When using the "HasModels" trait and passing raw IDs to syncModels, + * attachModels, or detachModels, this model class will be used to + * resolve those IDs. If null, defaults to the guard's model. + */ + 'default_model' => null, + ], + + 'table_names' => [ + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'roles' => 'roles', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your permissions. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'permissions' => 'permissions', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your models permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_permissions' => 'model_has_permissions', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your models roles. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_roles' => 'model_has_roles', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'role_has_permissions' => 'role_has_permissions', + ], + + 'column_names' => [ + /* + * Change this if you want to name the related pivots other than defaults + */ + 'role_pivot_key' => null, // default 'role_id', + 'permission_pivot_key' => null, // default 'permission_id', + + /* + * Change this if you want to name the related model primary key other than + * `model_id`. + * + * For example, this would be nice if your primary keys are all UUIDs. In + * that case, name this `model_uuid`. + */ + + 'model_morph_key' => 'model_id', + + /* + * Change this if you want to use the teams feature and your related model's + * foreign key is other than `team_id`. + */ + + 'team_foreign_key' => 'team_id', + ], + + /* + * When set to true, the method for checking permissions will be registered on the gate. + * Set this to false if you want to implement custom logic for checking permissions. + */ + + 'register_permission_check_method' => true, + + /* + * When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered + * this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated + * NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it. + */ + 'register_octane_reset_listener' => false, + + /* + * Events will fire when a role or permission is assigned/unassigned: + * \Spatie\Permission\Events\RoleAttachedEvent + * \Spatie\Permission\Events\RoleDetachedEvent + * \Spatie\Permission\Events\PermissionAttachedEvent + * \Spatie\Permission\Events\PermissionDetachedEvent + * + * To enable, set to true, and then create listeners to watch these events. + */ + 'events_enabled' => false, + + /* + * Teams Feature. + * When set to true the package implements teams using the 'team_foreign_key'. + * If you want the migrations to register the 'team_foreign_key', you must + * set this to true before doing the migration. + * If you already did the migration then you must make a new migration to also + * add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions' + * (view the latest version of this package's migration file) + */ + + 'teams' => false, + + /* + * The class to use to resolve the permissions team id + */ + 'team_resolver' => DefaultTeamResolver::class, + + /* + * Passport Client Credentials Grant + * When set to true the package will use Passports Client to check permissions + */ + + 'use_passport_client_credentials' => false, + + /* + * When set to true, the required permission names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_permission_in_exception' => false, + + /* + * When set to true, the required role names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_role_in_exception' => false, + + /* + * By default wildcard permission lookups are disabled. + * See documentation to understand supported syntax. + */ + + 'enable_wildcard_permission' => false, + + /* + * The class to use for interpreting wildcard permissions. + * If you need to modify delimiters, override the class and specify its name here. + */ + // 'wildcard_permission' => Spatie\Permission\WildcardPermission::class, + + /* Cache-specific settings */ + + 'cache' => [ + + /* + * By default all permissions are cached for 24 hours to speed up performance. + * When permissions or roles are updated the cache is flushed automatically. + */ + + 'expiration_time' => DateInterval::createFromDateString('24 hours'), + + /* + * The cache key used to store all permissions. + */ + + 'key' => 'spatie.permission.cache', + + /* + * You may optionally indicate a specific cache driver to use for permission and + * role caching using any of the `store` drivers listed in the cache.php config + * file. Using 'default' here means to use the `default` set in cache.php. + */ + + 'store' => 'default', + ], +]; diff --git a/config/rbac_permissions.php b/config/rbac_permissions.php new file mode 100644 index 0000000..17df9b7 --- /dev/null +++ b/config/rbac_permissions.php @@ -0,0 +1,154 @@ + [ + 'users' => [ + 'name' => 'Manajemen Pengguna (User Management)', + 'icon' => 'fa-solid fa-users', + 'permissions' => [ + 'users.view' => [ + 'label' => 'Melihat Daftar Pengguna', + 'description' => 'Melihat daftar akun pengguna, rincian profil, dan status penempatan pos.', + ], + 'users.create' => [ + 'label' => 'Menambah Pengguna Baru', + 'description' => 'Membuat akun pengguna baru dan menetapkan kredensial awal.', + ], + 'users.edit' => [ + 'label' => 'Mengubah Data Pengguna', + 'description' => 'Mengubah nama, email, username, dan penempatan pos gerbang pengguna.', + ], + 'users.change_password' => [ + 'label' => 'Mengubah Password Pengguna', + 'description' => 'Mereset atau memperbarui kata sandi pengguna dari panel admin.', + ], + 'users.assign_role' => [ + 'label' => 'Menetapkan Role Pengguna', + 'description' => 'Menetapkan atau mengubah wewenang role Spatie kepada pengguna.', + ], + 'users.delete' => [ + 'label' => 'Menghapus Pengguna', + 'description' => 'Menghapus akun pengguna dari sistem (dengan proteksi akun utama).', + ], + ], + ], + 'roles' => [ + 'name' => 'Manajemen Role & RBAC (Role & Permissions)', + 'icon' => 'fa-solid fa-shield-halved', + 'permissions' => [ + 'roles.view' => [ + 'label' => 'Melihat Matriks Role & Hak Akses', + 'description' => 'Melihat daftar role dan pemetaan centang izin wewenang sistem.', + ], + 'roles.create' => [ + 'label' => 'Membuat Role Kustom Baru', + 'description' => 'Menambahkan role tingkatan wewenang baru ke dalam sistem.', + ], + 'roles.edit_permissions' => [ + 'label' => 'Mengubah Hak Akses Role', + 'description' => 'Memperbarui centang matriks izin/permissions untuk setiap role.', + ], + 'roles.delete' => [ + 'label' => 'Menghapus Role Kustom', + 'description' => 'Menghapus role kustom yang sudah tidak digunakan (role inti terlindungi).', + ], + ], + ], + 'hse' => [ + 'name' => 'Modul HSE (Karyawan & SIMPER)', + 'icon' => 'fa-solid fa-id-card', + 'permissions' => [ + 'hse.employees.view' => [ + 'label' => 'Melihat Data Karyawan & SIMPER', + 'description' => 'Melihat daftar master karyawan, status operator/driver, dan masa berlaku SIMPER.', + ], + 'hse.employees.create' => [ + 'label' => 'Menambah Data Karyawan / Driver', + 'description' => 'Menambahkan karyawan baru ke master data HSE.', + ], + 'hse.employees.edit' => [ + 'label' => 'Mengubah Data Karyawan / SIMPER', + 'description' => 'Memperbarui status driver, unit kerja, divisi, dan perpanjangan tanggal SIMPER.', + ], + ], + ], + 'qma' => [ + 'name' => 'Modul QMA (Kendaraan & Log Aktivitas)', + 'icon' => 'fa-solid fa-car', + 'permissions' => [ + 'qma.vehicles.view' => [ + 'label' => 'Melihat Master Kendaraan', + 'description' => 'Melihat master data kendaraan ringan (LV) dan unit support.', + ], + 'qma.vehicles.create' => [ + 'label' => 'Menambah Unit Kendaraan', + 'description' => 'Menambahkan unit kendaraan baru dan dokumen kendaraan.', + ], + 'qma.vehicles.edit' => [ + 'label' => 'Mengubah Data Kendaraan', + 'description' => 'Memperbarui informasi status, HM/KM, dokumen STNK/KIR/SILO kendaraan.', + ], + 'qma.vehicles.delete' => [ + 'label' => 'Menghapus Data Kendaraan', + 'description' => 'Menghapus unit kendaraan (terlindungi jika memiliki riwayat aktivitas).', + ], + 'qma.logs.view' => [ + 'label' => 'Melihat Log Aktivitas Kendaraan', + 'description' => 'Melihat riwayat 10 kolom pergerakan kendaraan masuk/keluar proyek.', + ], + 'qma.summary.view' => [ + 'label' => 'Melihat Ringkasan Aktivitas & Statistik', + 'description' => 'Melihat summary dan grafik agregat penggunaan kendaraan.', + ], + ], + ], + 'pg' => [ + 'name' => 'Modul Private Guard (Satpam & Verifikasi Gerbang)', + 'icon' => 'fa-solid fa-user-shield', + 'permissions' => [ + 'pg.guards.view' => [ + 'label' => 'Melihat Data Satpam', + 'description' => 'Melihat daftar personil satpam, regu/tim jaga, dan penempatan pos gerbang.', + ], + 'pg.guards.create' => [ + 'label' => 'Menambah Personil Satpam Baru', + 'description' => 'Mendaftarkan satpam baru dan otomatis membuatkan akun login lapangan.', + ], + 'pg.guards.edit' => [ + 'label' => 'Mengubah Data Satpam', + 'description' => 'Mengubah regu, nama, nomor badge, dan pos penugasan satpam.', + ], + 'pg.guards.toggle' => [ + 'label' => 'Mengaktifkan / Menonaktifkan Satpam', + 'description' => 'Mengubah status aktif personil satpam untuk bertugas di pos.', + ], + 'pg.guards.delete' => [ + 'label' => 'Menghapus Data Satpam', + 'description' => 'Menghapus personil satpam dan akun login terkait.', + ], + 'pg.logs.view' => [ + 'label' => 'Melihat Log Verifikasi Pos Gerbang', + 'description' => 'Melihat riwayat audit pemeriksaan yang telah disetujui / ditolak oleh satpam.', + ], + ], + ], + 'gate' => [ + 'name' => 'Pos Gerbang Lapangan (Gate Officer Verification)', + 'icon' => 'fa-solid fa-shield-halved', + 'permissions' => [ + 'gate.inspect' => [ + 'label' => 'Membuka Layar Antrean Pos Gerbang', + 'description' => 'Melihat antrean live kendaraan yang masuk/keluar di pos gerbang.', + ], + 'gate.approve' => [ + 'label' => 'Menyetujui Verifikasi Kendaraan (Approve)', + 'description' => 'Menyetujui perlintasan kendaraan dan memperbarui odometer master.', + ], + 'gate.reject' => [ + 'label' => 'Menolak Verifikasi Kendaraan (Reject)', + 'description' => 'Menolak perlintasan kendaraan dengan memberikan catatan alasan.', + ], + ], + ], + ], +]; diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index c4ceb07..240e6eb 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -26,6 +26,7 @@ class UserFactory extends Factory { return [ 'name' => fake()->name(), + 'username' => fake()->unique()->userName(), 'email' => fake()->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => static::$password ??= Hash::make('password'), @@ -42,4 +43,19 @@ class UserFactory extends Factory 'email_verified_at' => null, ]); } + + /** + * Configure the model factory. + */ + public function configure(): static + { + return $this->afterCreating(function (User $user) { + if ($user->role && \Illuminate\Support\Facades\Schema::hasTable('roles')) { + $role = \Spatie\Permission\Models\Role::where('name', $user->role)->first(); + if ($role && !$user->hasRole($user->role)) { + $user->assignRole($role); + } + } + }); + } } diff --git a/database/migrations/2026_10_14_131551_create_permission_tables.php b/database/migrations/2026_10_14_131551_create_permission_tables.php new file mode 100644 index 0000000..8986275 --- /dev/null +++ b/database/migrations/2026_10_14_131551_create_permission_tables.php @@ -0,0 +1,137 @@ +id(); // permission id + $table->string('name'); + $table->string('guard_name'); + $table->timestamps(); + + $table->unique(['name', 'guard_name']); + }); + + /** + * See `docs/prerequisites.md` for suggested lengths on 'name' and 'guard_name' if "1071 Specified key was too long" errors are encountered. + */ + Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) { + $table->id(); // role id + if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing + $table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable(); + $table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index'); + } + $table->string('name'); + $table->string('guard_name'); + $table->timestamps(); + if ($teams || config('permission.testing')) { + $table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']); + } else { + $table->unique(['name', 'guard_name']); + } + }); + + Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) { + $table->unsignedBigInteger($pivotPermission); + + $table->string('model_type'); + $table->unsignedBigInteger($columnNames['model_morph_key']); + $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index'); + + $table->foreign($pivotPermission) + ->references('id') // permission id + ->on($tableNames['permissions']) + ->cascadeOnDelete(); + if ($teams) { + $table->unsignedBigInteger($columnNames['team_foreign_key']); + $table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index'); + + $table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'], + 'model_has_permissions_permission_model_type_primary'); + } else { + $table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'], + 'model_has_permissions_permission_model_type_primary'); + } + }); + + Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) { + $table->unsignedBigInteger($pivotRole); + + $table->string('model_type'); + $table->unsignedBigInteger($columnNames['model_morph_key']); + $table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index'); + + $table->foreign($pivotRole) + ->references('id') // role id + ->on($tableNames['roles']) + ->cascadeOnDelete(); + if ($teams) { + $table->unsignedBigInteger($columnNames['team_foreign_key']); + $table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index'); + + $table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'], + 'model_has_roles_role_model_type_primary'); + } else { + $table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'], + 'model_has_roles_role_model_type_primary'); + } + }); + + Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) { + $table->unsignedBigInteger($pivotPermission); + $table->unsignedBigInteger($pivotRole); + + $table->foreign($pivotPermission) + ->references('id') // permission id + ->on($tableNames['permissions']) + ->cascadeOnDelete(); + + $table->foreign($pivotRole) + ->references('id') // role id + ->on($tableNames['roles']) + ->cascadeOnDelete(); + + $table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary'); + }); + + app('cache') + ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null) + ->forget(config('permission.cache.key')); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + $tableNames = config('permission.table_names'); + + throw_if(empty($tableNames), 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.'); + + Schema::dropIfExists($tableNames['role_has_permissions']); + Schema::dropIfExists($tableNames['model_has_roles']); + Schema::dropIfExists($tableNames['model_has_permissions']); + Schema::dropIfExists($tableNames['roles']); + Schema::dropIfExists($tableNames['permissions']); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 4553479..2a2aba7 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -39,8 +39,9 @@ class DatabaseSeeder extends Seeder $createdGates = []; foreach ($gateList as $g) { - $createdGates[$g['code']] = Gate::create([ + $createdGates[$g['code']] = Gate::firstOrCreate([ 'code' => $g['code'], + ], [ 'name' => $g['name'], 'is_active' => true, ]); @@ -57,17 +58,19 @@ class DatabaseSeeder extends Seeder foreach ($guardData as $g) { $gateModel = $createdGates[$g['gate']]; - $guardUser = User::create([ - 'name' => $g['name'], + $guardUser = User::firstOrCreate([ 'username' => $g['badge_id'], + ], [ + 'name' => $g['name'], 'email' => strtolower($g['badge_id']) . '@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'gate_officer', 'gate_id' => $gateModel->id, ]); - SecurityGuard::create([ + SecurityGuard::firstOrCreate([ 'badge_id' => $g['badge_id'], + ], [ 'name' => $g['name'], 'team' => $g['team'], 'gate_id' => $gateModel->id, @@ -78,36 +81,40 @@ class DatabaseSeeder extends Seeder // 3. Seed Users (Super Admin, Dept Admins & Shared Gate Accounts) // Super Admin [Nama : Super Administrator, Username : superadmin, Password : password] - User::create([ - 'name' => 'Super Administrator', + User::firstOrCreate([ 'username' => 'superadmin', + ], [ + 'name' => 'Super Administrator', 'email' => 'superadmin@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'super_admin', ]); // Admin HSE [Nama : Mima, Username : 1185, Password : password] - User::create([ - 'name' => 'Mima', + User::firstOrCreate([ 'username' => '1185', + ], [ + 'name' => 'Mima', 'email' => '1185@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'hse_admin', ]); // Admin QMA [Nama : Pinto Yuliandra, Username : 1171, Password : password] - User::create([ - 'name' => 'Pinto Yuliandra', + User::firstOrCreate([ 'username' => '1171', + ], [ + 'name' => 'Pinto Yuliandra', 'email' => '1171@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'qma_admin', ]); // Admin PG [Nama : Admin PG, Username : AdminPG, Password : password] - User::create([ - 'name' => 'Admin PG', + User::firstOrCreate([ 'username' => 'AdminPG', + ], [ + 'name' => 'Admin PG', 'email' => 'adminpg@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'pg_admin', @@ -154,21 +161,23 @@ class DatabaseSeeder extends Seeder ]; foreach ($employeesData as $emp) { - $empUser = User::create([ - 'name' => $emp['name'], + $empUser = User::firstOrCreate([ 'username' => $emp['nik'], + ], [ + 'name' => $emp['name'], 'email' => strtolower(str_replace(['-', ' '], '', $emp['nik'])) . '@kmh.co.id', 'password' => Hash::make('password'), 'role' => 'employee', ]); $emp['user_id'] = $empUser->id; - Employee::create($emp); + Employee::firstOrCreate(['nik' => $emp['nik']], $emp); } // 5. Seed Vehicles (Master Data QMA: Kendaraan Ringan / LV) - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'LV62', + ], [ 'category' => 'light_vehicle', 'brand_type' => 'MITSUBISHI - L300 - PICK UP', 'license_plate' => 'BH 8893 DI', @@ -178,8 +187,9 @@ class DatabaseSeeder extends Seeder 'current_km' => 12500.00, ]); - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'LV01', + ], [ 'category' => 'light_vehicle', 'brand_type' => 'TOYOTA HILUX 4X4 DC', 'license_plate' => 'BH 1024 AB', @@ -189,8 +199,9 @@ class DatabaseSeeder extends Seeder 'current_km' => 45200.00, ]); - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'LV15', + ], [ 'category' => 'light_vehicle', 'brand_type' => 'ISUZU D-MAX 4X4', 'license_plate' => 'BH 9012 CD', @@ -201,8 +212,9 @@ class DatabaseSeeder extends Seeder ]); // 6. Seed Vehicles (Master Data QMA: Kendaraan Berat / Unit Support - HANYA Pencatatan Data) - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'EX01', + ], [ 'category' => 'unit_support', 'brand_type' => 'KOMATSU PC200-8', 'unit_category' => 'Excavator', @@ -222,8 +234,9 @@ class DatabaseSeeder extends Seeder 'kir_document' => 'KIR-2026/08', ]); - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'CR01', + ], [ 'category' => 'unit_support', 'brand_type' => 'KATO SR-250R', 'unit_category' => 'Mobile Crane', @@ -241,8 +254,9 @@ class DatabaseSeeder extends Seeder 'kir_document' => 'KIR-2026/10', ]); - Vehicle::create([ + Vehicle::firstOrCreate([ 'code' => 'DT02', + ], [ 'category' => 'unit_support', 'brand_type' => 'MITSUBISHI FUSO FIGHTER FN62F', 'license_plate' => 'BH 8412 AA', @@ -261,6 +275,9 @@ class DatabaseSeeder extends Seeder 'kir_document' => 'KIR-2026/11', ]); + // 6. Seed RBAC Roles, Permissions & Super Admin + $this->call(RolePermissionSeeder::class); + // 7. Seed 28 Master Template P2H Unit Support $this->call(P2hTemplateSeeder::class); } diff --git a/database/seeders/RolePermissionSeeder.php b/database/seeders/RolePermissionSeeder.php new file mode 100644 index 0000000..4b3fd7a --- /dev/null +++ b/database/seeders/RolePermissionSeeder.php @@ -0,0 +1,97 @@ +forgetCachedPermissions(); + + // 2. Baca seluruh daftar permission dari konfigurasi rbac_permissions + $modules = config('rbac_permissions.modules', []); + $allPermissions = []; + + foreach ($modules as $moduleKey => $moduleData) { + foreach ($moduleData['permissions'] as $permKey => $permMeta) { + $allPermissions[] = $permKey; + Permission::firstOrCreate([ + 'name' => $permKey, + 'guard_name' => 'web', + ]); + } + } + + // 3. Pemetaan Default Permission per Role + $rolesWithPermissions = [ + 'super_admin' => $allPermissions, + 'hse_admin' => [ + 'hse.employees.view', + 'hse.employees.create', + 'hse.employees.edit', + ], + 'qma_admin' => [ + 'qma.vehicles.view', + 'qma.vehicles.create', + 'qma.vehicles.edit', + 'qma.vehicles.delete', + 'qma.logs.view', + 'qma.summary.view', + ], + 'pg_admin' => [ + 'pg.guards.view', + 'pg.guards.create', + 'pg.guards.edit', + 'pg.guards.toggle', + 'pg.guards.delete', + 'pg.logs.view', + ], + 'gate_officer' => [ + 'gate.inspect', + 'gate.approve', + 'gate.reject', + ], + ]; + + foreach ($rolesWithPermissions as $roleName => $perms) { + $role = Role::firstOrCreate(['name' => $roleName, 'guard_name' => 'web']); + $role->syncPermissions($perms); + } + + // 4. Buat Akun Default Super Admin + $superAdmin = User::firstOrCreate( + ['username' => 'superadmin'], + [ + 'name' => 'Super Administrator', + 'email' => 'superadmin@kmh.co.id', + 'password' => Hash::make('password'), + 'role' => 'super_admin', + ] + ); + + if (!$superAdmin->hasRole('super_admin')) { + $superAdmin->assignRole('super_admin'); + } + + // 5. Sinkronisasi Akun Existing ke Spatie Roles + $existingUsers = User::all(); + foreach ($existingUsers as $user) { + if ($user->role && in_array($user->role, array_keys($rolesWithPermissions))) { + if (!$user->hasRole($user->role)) { + $user->assignRole($user->role); + } + } + } + } +} diff --git a/resources/views/admin/dashboard.blade.php b/resources/views/admin/dashboard.blade.php new file mode 100644 index 0000000..5623852 --- /dev/null +++ b/resources/views/admin/dashboard.blade.php @@ -0,0 +1,278 @@ +@extends('layouts.app') + +@section('title', 'Dashboard Super Admin - RKM KMH') + +@section('content') +
+ +
+
+

+ + Dashboard Super Admin & RBAC +

+

+ Pusat kendali arsitektur sistem, pengelolaan pengguna, dan matriks hak akses Role-Based Access Control (RBAC). +

+
+ +
+ + + @if(session('success')) +
+
+ + {{ session('success') }} +
+ +
+ @endif + + +
+ +
+
+ Total Akun +
+ +
+
+
{{ $metrics['total_users'] }}
+

Terdaftar dalam sistem

+
+ + +
+
+ Total Role RBAC +
+ +
+
+
{{ $metrics['total_roles'] }}
+

Tingkatan wewenang

+
+ + +
+
+ Master Data +
+ +
+
+
+ {{ $metrics['total_vehicles'] }} + Unit + / + {{ $metrics['total_employees'] }} + Karyawan +
+

Kendaraan & Simper

+
+ + +
+
+ Aktivitas Hari Ini +
+ +
+
+
+ {{ $metrics['activities_today'] }} + Total + @if($metrics['activities_pending'] > 0) + + {{ $metrics['activities_pending'] }} antre + + @endif +
+

{{ $metrics['activities_approved'] }} sudah diverifikasi

+
+
+ + + + + +
+ +
+

+ Distribusi Pengguna per Role + {{ $metrics['total_users'] }} User +

+
+ @foreach($usersByRole as $roleName => $count) + @php + $percentage = $metrics['total_users'] > 0 ? round(($count / $metrics['total_users']) * 100) : 0; + $badgeColor = match($roleName) { + 'super_admin' => 'bg-indigo-500', + 'hse_admin' => 'bg-emerald-500', + 'qma_admin' => 'bg-blue-500', + 'pg_admin' => 'bg-purple-500', + 'gate_officer' => 'bg-amber-500', + default => 'bg-slate-400' + }; + @endphp +
+
+ + {{ str_replace('_', ' ', $roleName) }} + + {{ $count }} ({{ $percentage }}%) +
+
+
+
+
+ @endforeach +
+ + +
+ + +
+
+

+ + Pengguna Sistem Terdaftar Terbaru +

+ + Lihat Semua User → + +
+ +
+ + + + + + + + + + + + @forelse($recentUsers as $user) + + + + + + + + @empty + + + + @endforelse + +
Nama & UsernameEmailRolePos GerbangTerdaftar
+
+
+ {{ strtoupper(substr($user->name, 0, 1)) }} +
+
+

{{ $user->name }}

+

{{ $user->username }}

+
+
+
{{ $user->email }} + @php + $primaryRole = $user->roles->first()?->name ?? $user->role; + $badgeStyle = match($primaryRole) { + 'super_admin' => 'bg-indigo-50 text-indigo-700 border-indigo-200', + 'hse_admin' => 'bg-emerald-50 text-emerald-700 border-emerald-200', + 'qma_admin' => 'bg-blue-50 text-blue-700 border-blue-200', + 'pg_admin' => 'bg-purple-50 text-purple-700 border-purple-200', + 'gate_officer' => 'bg-amber-50 text-amber-700 border-amber-200', + default => 'bg-slate-100 text-slate-600 border-slate-200', + }; + @endphp + + {{ str_replace('_', ' ', $primaryRole) }} + + + {{ $user->gate?->name ?? '-' }} + + {{ $user->created_at->diffForHumans() }} +
Belum ada data pengguna.
+
+
+
+
+@endsection diff --git a/resources/views/admin/roles/index.blade.php b/resources/views/admin/roles/index.blade.php new file mode 100644 index 0000000..96d58ce --- /dev/null +++ b/resources/views/admin/roles/index.blade.php @@ -0,0 +1,286 @@ +@extends('layouts.app') + +@section('title', 'Matriks Role & Permission (RBAC) - Super Admin RKM') + +@section('content') +
+ +
+
+

+ + Matriks Role & Hak Akses (RBAC) +

+

+ Konfigurasi izin wewenang (permissions) untuk setiap role pengguna menggunakan paket Spatie Laravel Permission. +

+
+
+ + + + Kelola Pengguna + +
+
+ + + @if(session('success')) +
+
+ + {{ session('success') }} +
+ +
+ @endif + + @if(session('error')) +
+
+ + {{ session('error') }} +
+ +
+ @endif + + +
+
+ +
+
+

Privilese Khusus Super Administrator (Gate::before Bypass)

+

+ Role super_admin secara otomatis memiliki hak akses tak terbatas ke seluruh modul sistem (HSE, QMA, PG, dan Pengaturan RBAC) melalui interceptor gerbang Laravel. Matriks centang di bawah ini berlaku aktif untuk role operasional lainnya. +

+
+
+ + +
+ @foreach($roles as $role) + @php + $isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']); + $badgeColor = match($role->name) { + 'super_admin' => 'bg-indigo-600 text-white', + 'hse_admin' => 'bg-emerald-600 text-white', + 'qma_admin' => 'bg-blue-600 text-white', + 'pg_admin' => 'bg-purple-600 text-white', + 'gate_officer' => 'bg-amber-600 text-white', + default => 'bg-slate-700 text-white' + }; + @endphp +
+
+
+ + @if(!$isCoreRole) + + @else + Core + @endif +
+

{{ str_replace('_', ' ', $role->name) }}

+

{{ $role->name }}

+
+
+ Izin Aktif: + + {{ $role->name === 'super_admin' ? 'Semua' : $role->permissions->count() }} + +
+
+ @endforeach +
+ + +
+ @foreach($roles as $role) +
+
+
+
+ +
+
+

+ Role: {{ str_replace('_', ' ', $role->name) }} + @if($role->name === 'super_admin') + UNRESTRICTED + @endif +

+

Atur centang hak akses yang diizinkan untuk peran pengguna ini.

+
+
+ + @if($role->name !== 'super_admin') + + @endif +
+ +
+ @csrf + + @php + $rolePermNames = $role->permissions->pluck('name')->toArray(); + @endphp + +
+ @foreach($modules as $moduleKey => $module) +
+

+ + + {{ $module['name'] }} + + {{ count($module['permissions']) }} izin +

+ +
+ @foreach($module['permissions'] as $permKey => $permMeta) + @php + $isChecked = $role->name === 'super_admin' || in_array($permKey, $rolePermNames); + @endphp + + @endforeach +
+
+ @endforeach +
+
+
+ @endforeach +
+
+ + + + + + + + + + + + +@endsection diff --git a/resources/views/admin/users/index.blade.php b/resources/views/admin/users/index.blade.php new file mode 100644 index 0000000..0ea865a --- /dev/null +++ b/resources/views/admin/users/index.blade.php @@ -0,0 +1,490 @@ +@extends('layouts.app') + +@section('title', 'Manajemen Pengguna - Super Admin RKM') + +@section('content') +
+ +
+
+

+ + Manajemen Pengguna Sistem +

+

+ Kelola akun pengguna, ganti kata sandi, dan tetapkan role wewenang pada sistem RKM-KMH. +

+
+
+ +
+
+ + + @if(session('success')) +
+
+ + {{ session('success') }} +
+ +
+ @endif + + @if(session('error')) +
+
+ + {{ session('error') }} +
+ +
+ @endif + + @if($errors->any()) +
+
+ + Terdapat kesalahan pada input Anda: +
+
    + @foreach($errors->all() as $err) +
  • {{ $err }}
  • + @endforeach +
+
+ @endif + + +
+
+
+ + +
+ +
+ +
+ +
+ + @if(request()->hasAny(['search', 'role'])) + + + + @endif +
+
+
+ + +
+
+ + + + + + + + + + + + + @forelse($users as $user) + @php + $primaryRole = $user->roles->first()?->name ?? $user->role; + $badgeStyle = match($primaryRole) { + 'super_admin' => 'bg-indigo-50 text-indigo-700 border-indigo-200', + 'hse_admin' => 'bg-emerald-50 text-emerald-700 border-emerald-200', + 'qma_admin' => 'bg-blue-50 text-blue-700 border-blue-200', + 'pg_admin' => 'bg-purple-50 text-purple-700 border-purple-200', + 'gate_officer' => 'bg-amber-50 text-amber-700 border-amber-200', + default => 'bg-slate-100 text-slate-600 border-slate-200', + }; + @endphp + + + + + + + + + @empty + + + + @endforelse + +
PenggunaEmailRole RBACPenempatan PosTerdaftarAksi
+
+
+ {{ strtoupper(substr($user->name, 0, 1)) }} +
+
+

{{ $user->name }}

+

@{{ $user->username }}

+
+
+
+ {{ $user->email }} + +
+ + {{ str_replace('_', ' ', $primaryRole) }} + + @if($user->permissions->count() > 0) + + + +{{ $user->permissions->count() }} Izin Khusus + + @endif +
+
+ @if($user->gate) + + + {{ $user->gate->name }} + + @else + - + @endif + + {{ $user->created_at->format('d M Y') }} + +
+ + + @if($user->id !== auth()->id() && $user->username !== 'superadmin') + + @endif +
+
+ + Tidak ada data pengguna yang sesuai kriteria pencarian. +
+
+ + @if($users->hasPages()) +
+ {{ $users->links() }} +
+ @endif +
+
+ + + + + + + + + + + + + + + + + +@endsection diff --git a/resources/views/hse/employees_index.blade.php b/resources/views/hse/employees_index.blade.php index 89681ea..5fb89f4 100644 --- a/resources/views/hse/employees_index.blade.php +++ b/resources/views/hse/employees_index.blade.php @@ -35,6 +35,15 @@ Ekspor Simper + + @can('hse.employees.create') + + @endcan @@ -165,6 +174,7 @@ + @can('hse.employees.edit')
+ @else + Hanya lihat + @endcan @empty diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 740e11c..a5d9dcc 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -49,32 +49,37 @@ /* Modern Sleek Scrollbar */ ::-webkit-scrollbar { - width: 10px; - height: 10px; - } - ::-webkit-scrollbar-button { - display: none; - width: 0; - height: 0; + width: 6px; + height: 6px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { - background-color: rgba(148, 163, 184, 0.45); + background: #cbd5e1; border-radius: 9999px; - border: 2px solid transparent; - background-clip: padding-box; - transition: all 0.2s ease; } ::-webkit-scrollbar-thumb:hover { - background-color: rgba(100, 116, 139, 0.75); + background: #94a3b8; } - /* Efek Saat Modal Popup Terbuka: Scrollbar ikut gelap, buram (frosted blur) & menyatu dengan backdrop */ + /* Cegah Scrollbar Melompat & Hilangkan Gap Putih saat Modal Aktif */ + html.modal-open, + body.modal-open { + overflow: hidden !important; + padding-right: 0px !important; + margin-right: 0px !important; + } + + /* Scrollbar Halus & Transparan untuk Dialog Modal */ + html.modal-open::-webkit-scrollbar, + body.modal-open::-webkit-scrollbar { + width: 6px; + background-color: rgba(15, 23, 42, 0.6); + } html.modal-open::-webkit-scrollbar-track, body.modal-open::-webkit-scrollbar-track { - background: rgba(15, 23, 42, 0.6); + background-color: rgba(15, 23, 42, 0.6); } html.modal-open::-webkit-scrollbar-thumb, body.modal-open::-webkit-scrollbar-thumb { @@ -155,36 +160,22 @@
- @if(auth()->user()->isSuperAdmin()) - -
-

- MENU ADMIN -

- -
- @else - +
- - @if(!auth()->user()->isGateOfficer()) + + @if(auth()->user()->isSuperAdmin())

- MANAJEMEN SISTEM + SUPER ADMIN & RBAC

+
+ @endif + + + @can('hse.employees.view') +
+

+ MANAJEMEN HSE +

+ +
+ @endcan + + + @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view'])) +
+

+ MANAJEMEN QMA +

+
+ @endcan + @can('qma.logs.view') @php $isActivityRoute = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @endphp @@ -327,27 +357,54 @@ Master Template P2H + @endcan + @can('qma.summary.view') + + + Summary Aktivitas + + @endcan + + + @endif - @endif - - @if(auth()->user()->isPgAdmin()) + + @if(auth()->user()->canAny(['pg.guards.view', 'pg.logs.view', 'gate.inspect'])) +
+

+ MANAJEMEN PRIVATE GUARD (PG) +

+
@endif - @endif
@@ -404,25 +461,21 @@
- @if(auth()->user()->isSuperAdmin()) -
-

MENU ADMIN

- + +
+
- @else - @if(auth()->user()->isHseAdmin()) + @elseif(auth()->user()->isHseAdmin()) + @can('hse.employees.view') @@ -432,12 +485,9 @@ Dashboard - - - Data Simper - - @endif - @if(auth()->user()->isQmaAdmin()) + @endcan + @elseif(auth()->user()->isQmaAdmin()) + @can('qma.vehicles.view') @@ -447,7 +497,90 @@ Dashboard + @endcan + @elseif(auth()->user()->isPgAdmin()) + @can('pg.guards.view') + + + + + + + + Dashboard + + @endcan + @elseif(auth()->user()->isGateOfficer()) + @can('gate.inspect') + + + Verifikasi Pos Gerbang + + @endcan + @elseif(auth()->user()->isEmployee()) + + + + + + + + Dashboard + + + + Pemeriksaan P2H + + + + Timesheet + + @endif + +
+ + @if(auth()->user()->isSuperAdmin()) +
+

+ SUPER ADMIN & RBAC +

+ +
+ @endif + + + @can('hse.employees.view') +
+

+ MANAJEMEN HSE +

+ +
+ @endcan + + + @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view'])) +
+

+ MANAJEMEN QMA +

+
+ @endcan + @can('qma.logs.view') @php $isActivityRouteMob = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @endphp @@ -506,55 +641,48 @@ Master Template P2H + @endcan + @can('qma.summary.view') + + + Summary Aktivitas + + @endcan + + + @endif - @endif - @if(auth()->user()->isEmployee()) - - - - - - - - Dashboard - - - - Pemeriksaan P2H - - - - Timesheet - - @endif - @if(auth()->user()->isPgAdmin()) - - - - - - - - Dashboard - + + @if(auth()->user()->canAny(['pg.guards.view', 'pg.logs.view', 'gate.inspect'])) +
+

+ MANAJEMEN PRIVATE GUARD (PG) +

+
+ @endif

PENGATURAN

@@ -596,16 +724,20 @@

- @if(request()->routeIs('superadmin.dashboard')) + @if(request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard')) Dashboard Admin - @elseif(request()->routeIs('superadmin.roles.*') || request()->routeIs('superadmin.users.*')) - Manajemen Role + @elseif(request()->routeIs('admin.users.*')) + Kelola Pengguna + @elseif(request()->routeIs('admin.roles.*')) + Role & Permission @elseif(request()->routeIs('hse.dashboard') || request()->routeIs('qma.dashboard')) Dashboard @elseif(request()->routeIs('hse.employees.*')) Data Simper @elseif(request()->routeIs('qma.vehicles.lv')) Light Vehicle + @elseif(request()->routeIs('qma.vehicles.support.units*')) + Daftar Unit Fisik Support @elseif(request()->routeIs('qma.vehicles.support')) Unit Support @elseif(request()->routeIs('qma.vehicles.*')) @@ -619,7 +751,7 @@ @elseif(request()->routeIs('qma.p2h.*')) P2H Unit Support @elseif(request()->routeIs('qma.activity.summary')) - Summary Timesheet LV + Summary Aktivitas @elseif(request()->routeIs('profile.*')) Profil Saya @elseif(request()->routeIs('pg.dashboard')) @@ -631,7 +763,7 @@ @elseif(request()->routeIs('pg.logs.*')) Log Verifikasi Gerbang @elseif(request()->routeIs('employee.dashboard')) - Dashboard + Dashboard Karyawan @elseif(request()->routeIs('p2h.*')) Pemeriksaan P2H @elseif(request()->routeIs('timesheet.*') || request()->routeIs('mobilisasi.*')) @@ -686,7 +818,7 @@ -
+
@yield('content')
@@ -819,15 +951,16 @@ }); // ========================================================================= - // PENGELOLA MODAL UNIVERSAL: KLIK BACKDROP DI SEKITAR POPUP & TOMBOL ESCAPE + // ATURAN EMAS MODAL: PENANGANAN BACKDROP KLIK & ESCAPE TERPUSAT // ========================================================================= function closeAnyActiveModal(modal) { - if (!modal || modal.classList.contains('hidden') || modal.id === 'mobileDrawer') return; + if (!modal) return; - // 1. Coba klik tombol tutup / batal spesifik di dalam modal - const closeBtn = modal.querySelector('button[onclick*="close"], button[onclick*="Close"], button[onclick*="hide"], button[onclick*="Batal"], button[data-close]'); - if (closeBtn) { + // 1. Trigger tombol close/batal jika tersedia + const closeBtn = modal.querySelector('[data-modal-close], button[onclick*="close"], button[onclick*="Modal"], .modal-close'); + if (closeBtn && typeof closeBtn.click === 'function') { closeBtn.click(); + return; } // 2. Jika modal masih belum tertutup, sembunyikan langsung diff --git a/resources/views/pg/guards_index.blade.php b/resources/views/pg/guards_index.blade.php index 1d6e597..27d7c88 100644 --- a/resources/views/pg/guards_index.blade.php +++ b/resources/views/pg/guards_index.blade.php @@ -27,12 +27,14 @@
+ @can('pg.guards.create') + @endcan

@@ -169,6 +171,7 @@
+ @can('pg.guards.edit') + @endcan + @can('pg.guards.toggle') + @endcan + @can('pg.guards.delete') + @endcan + + @if(!auth()->user()->can('pg.guards.edit') && !auth()->user()->can('pg.guards.toggle') && !auth()->user()->can('pg.guards.delete')) + Hanya lihat + @endif
diff --git a/resources/views/pg/partials/queue_cards.blade.php b/resources/views/pg/partials/queue_cards.blade.php index cff8b36..5544df1 100644 --- a/resources/views/pg/partials/queue_cards.blade.php +++ b/resources/views/pg/partials/queue_cards.blade.php @@ -94,6 +94,7 @@ Cek fisik kendaraan lalu klik verifikasi untuk membuka portal + @can('gate.approve')
@csrf @if($currentGuard) @@ -109,6 +110,9 @@ Verifikasi
+ @else + Tidak memiliki izin verifikasi + @endcan diff --git a/resources/views/qma/vehicles_lv.blade.php b/resources/views/qma/vehicles_lv.blade.php index 9bf7c24..17b9a6d 100644 --- a/resources/views/qma/vehicles_lv.blade.php +++ b/resources/views/qma/vehicles_lv.blade.php @@ -35,11 +35,13 @@ + @can('qma.vehicles.create') + @endcan @@ -181,17 +183,21 @@ title="Lihat Detail Kendaraan"> + @can('qma.vehicles.edit') + @endcan + @can('qma.vehicles.delete') + @endcan diff --git a/resources/views/qma/vehicles_support.blade.php b/resources/views/qma/vehicles_support.blade.php index 35eb076..a42fd22 100644 --- a/resources/views/qma/vehicles_support.blade.php +++ b/resources/views/qma/vehicles_support.blade.php @@ -35,11 +35,13 @@ + @can('qma.vehicles.create') + @endcan @@ -152,17 +154,21 @@ title="Lihat Spesifikasi Kategori"> + @can('qma.vehicles.edit') + @endcan + @can('qma.vehicles.delete') + @endcan diff --git a/routes/web.php b/routes/web.php index adfed8c..7d5af09 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,8 @@ name('vehicle.activity.')->group(function () { // Group Terproteksi Autentikasi Sistem Route::middleware('auth')->group(function () { - // 1. Modul Super Admin (Kategori Khusus Admin: Dashboard & Manajemen Role) + // Backward Compatibility: Rute Super Admin Legacy -> Admin Dashboard Baru Route::prefix('superadmin')->name('superadmin.')->middleware('role:super_admin')->group(function () { - Route::get('/', [SuperAdminDashboardController::class, 'index']); - Route::get('/dashboard', [SuperAdminDashboardController::class, 'index'])->name('dashboard'); - Route::get('/roles', [SuperAdminUserController::class, 'index'])->name('roles.index'); - Route::post('/users', [SuperAdminUserController::class, 'store'])->name('users.store'); - Route::put('/users/{id}', [SuperAdminUserController::class, 'update'])->name('users.update'); - Route::post('/users/{id}/reset-password', [SuperAdminUserController::class, 'resetPassword'])->name('users.reset-password'); - Route::delete('/users/{id}', [SuperAdminUserController::class, 'destroy'])->name('users.destroy'); + Route::get('/', fn() => redirect()->route('admin.dashboard')); + Route::get('/dashboard', fn() => redirect()->route('admin.dashboard'))->name('dashboard'); + Route::get('/roles', fn() => redirect()->route('admin.roles.index'))->name('roles.index'); }); - // 2. Modul HSE: Admin HSE (Mima - 1185) - Kelola Karyawan & SIMPER - Route::prefix('hse')->name('hse.')->middleware('role:hse_admin')->group(function () { - Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard'); - Route::get('/employees', [EmployeeController::class, 'index'])->name('employees.index'); - Route::post('/employees', [EmployeeController::class, 'store'])->name('employees.store'); - Route::post('/employees/{id}', [EmployeeController::class, 'update'])->name('employees.update'); + // 2. Modul HSE: Admin HSE - Kelola Karyawan & SIMPER + Route::prefix('hse')->name('hse.')->group(function () { + Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard')->middleware('permission:hse.employees.view'); + Route::get('/employees', [EmployeeController::class, 'index'])->name('employees.index')->middleware('permission:hse.employees.view'); + Route::post('/employees', [EmployeeController::class, 'store'])->name('employees.store')->middleware('permission:hse.employees.create'); + Route::post('/employees/{id}', [EmployeeController::class, 'update'])->name('employees.update')->middleware('permission:hse.employees.edit'); }); - // 3. Modul QMA: Admin QMA (Pinto Yuliandra - 1171) - Dashboard, Data Kendaraan & Log Aktivitas - Route::prefix('qma')->name('qma.')->middleware('role:qma_admin')->group(function () { - Route::get('/dashboard', [VehicleController::class, 'dashboard'])->name('dashboard'); + // 3. Modul QMA: Admin QMA - Dashboard, Data Kendaraan & Log Aktivitas + Route::prefix('qma')->name('qma.')->group(function () { + Route::get('/dashboard', [VehicleController::class, 'dashboard'])->name('dashboard')->middleware('permission:qma.vehicles.view'); // Halaman Data Kendaraan Terpisah: Light Vehicle (LV) dan Unit Support - Route::get('/vehicles', [VehicleController::class, 'index'])->name('vehicles.index'); - Route::get('/vehicles/light-vehicle', [VehicleController::class, 'indexLv'])->name('vehicles.lv'); - Route::get('/vehicles/unit-support', [VehicleController::class, 'indexSupport'])->name('vehicles.support'); - Route::get('/vehicles/unit-support/{id}/units', [VehicleController::class, 'indexSupportUnits'])->name('vehicles.support.units'); - Route::post('/vehicles/unit-support/{id}/units', [VehicleController::class, 'storeSupportUnit'])->name('vehicles.support.units.store'); + Route::get('/vehicles', [VehicleController::class, 'index'])->name('vehicles.index')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/light-vehicle', [VehicleController::class, 'indexLv'])->name('vehicles.lv')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support', [VehicleController::class, 'indexSupport'])->name('vehicles.support')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/{id}/units', [VehicleController::class, 'indexSupportUnits'])->name('vehicles.support.units')->middleware('permission:qma.vehicles.view'); + Route::post('/vehicles/unit-support/{id}/units', [VehicleController::class, 'storeSupportUnit'])->name('vehicles.support.units.store')->middleware('permission:qma.vehicles.create'); - Route::post('/vehicles', [VehicleController::class, 'store'])->name('vehicles.store'); - Route::post('/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update'); - Route::delete('/vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy'); - Route::get('/activity-log', [ActivityLogController::class, 'index'])->name('activity.log'); - Route::get('/activity-summary', [ActivityLogController::class, 'summary'])->name('activity.summary'); + Route::post('/vehicles', [VehicleController::class, 'store'])->name('vehicles.store')->middleware('permission:qma.vehicles.create'); + Route::post('/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit'); + Route::delete('/vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy')->middleware('permission:qma.vehicles.delete'); + Route::get('/activity-log', [ActivityLogController::class, 'index'])->name('activity.log')->middleware('permission:qma.logs.view'); + Route::get('/activity-summary', [ActivityLogController::class, 'summary'])->name('activity.summary')->middleware('permission:qma.summary.view'); // Log Pemeriksaan P2H Unit Support & Approval Admin QMA - Route::get('/p2h-records', [P2hInspectionController::class, 'index'])->name('p2h.index'); - Route::get('/p2h-summary', [P2hInspectionController::class, 'summary'])->name('p2h.summary'); - Route::get('/p2h-records/{id}', [P2hInspectionController::class, 'show'])->name('p2h.show'); - Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve'); - Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject'); + Route::get('/p2h-records', [P2hInspectionController::class, 'index'])->name('p2h.index')->middleware('permission:qma.vehicles.view'); + Route::get('/p2h-summary', [P2hInspectionController::class, 'summary'])->name('p2h.summary')->middleware('permission:qma.vehicles.view'); + Route::get('/p2h-records/{id}', [P2hInspectionController::class, 'show'])->name('p2h.show')->middleware('permission:qma.vehicles.view'); + Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve')->middleware('permission:qma.vehicles.edit'); + Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.vehicles.edit'); // Master 28 Template Checksheet P2H & Kelola Pertanyaan - Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates'); - Route::get('/p2h-templates/{id}', [P2hTemplateController::class, 'show'])->name('p2h.templates.show'); - Route::post('/p2h-templates/{templateId}/items', [P2hTemplateController::class, 'storeItem'])->name('p2h.templates.items.store'); - Route::match(['PUT', 'POST'], '/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'updateItem'])->name('p2h.templates.items.update'); - Route::delete('/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'destroyItem'])->name('p2h.templates.items.destroy'); - Route::post('/p2h-templates/{templateId}/sections/reorder', [P2hTemplateController::class, 'reorderSections'])->name('p2h.templates.sections.reorder'); + Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.vehicles.view'); + Route::get('/p2h-templates/{id}', [P2hTemplateController::class, 'show'])->name('p2h.templates.show')->middleware('permission:qma.vehicles.view'); + Route::post('/p2h-templates/{templateId}/items', [P2hTemplateController::class, 'storeItem'])->name('p2h.templates.items.store')->middleware('permission:qma.vehicles.create'); + Route::match(['PUT', 'POST'], '/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'updateItem'])->name('p2h.templates.items.update')->middleware('permission:qma.vehicles.edit'); + Route::delete('/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'destroyItem'])->name('p2h.templates.items.destroy')->middleware('permission:qma.vehicles.delete'); + Route::post('/p2h-templates/{templateId}/sections/reorder', [P2hTemplateController::class, 'reorderSections'])->name('p2h.templates.sections.reorder')->middleware('permission:qma.vehicles.edit'); }); // 4. Modul Private Guard (PG): Admin PG & Pos Gerbang Satpam Route::prefix('pg')->name('pg.')->group(function () { // Modul Admin PG (Dashboard, Data Satpam & Log Verifikasi Gerbang) - Route::middleware('role:pg_admin')->group(function () { - Route::get('/dashboard', [PgDashboardController::class, 'index'])->name('dashboard'); - Route::get('/guards', [SecurityGuardController::class, 'index'])->name('guards.index'); - Route::post('/guards', [SecurityGuardController::class, 'store'])->name('guards.store'); - Route::post('/guards/{id}', [SecurityGuardController::class, 'update'])->name('guards.update'); - Route::post('/guards/{id}/toggle', [SecurityGuardController::class, 'toggleStatus'])->name('guards.toggle'); - Route::delete('/guards/{id}', [SecurityGuardController::class, 'destroy'])->name('guards.destroy'); - Route::get('/verification-logs', [VerificationLogController::class, 'index'])->name('logs.index'); - }); + Route::get('/dashboard', [PgDashboardController::class, 'index'])->name('dashboard')->middleware('permission:pg.guards.view'); + Route::get('/guards', [SecurityGuardController::class, 'index'])->name('guards.index')->middleware('permission:pg.guards.view'); + Route::post('/guards', [SecurityGuardController::class, 'store'])->name('guards.store')->middleware('permission:pg.guards.create'); + Route::post('/guards/{id}', [SecurityGuardController::class, 'update'])->name('guards.update')->middleware('permission:pg.guards.edit'); + Route::post('/guards/{id}/toggle', [SecurityGuardController::class, 'toggleStatus'])->name('guards.toggle')->middleware('permission:pg.guards.toggle'); + Route::delete('/guards/{id}', [SecurityGuardController::class, 'destroy'])->name('guards.destroy')->middleware('permission:pg.guards.delete'); + Route::get('/verification-logs', [VerificationLogController::class, 'index'])->name('logs.index')->middleware('permission:pg.logs.view'); // Verifikasi Pos Gerbang (Khusus Petugas Satpam Pos Gerbang) - Route::middleware('role:gate_officer')->group(function () { - Route::get('/gate-inspection', [GateInspectionController::class, 'index'])->name('gate.inspection'); - Route::get('/gate-inspection/live-queue', [GateInspectionController::class, 'liveQueue'])->name('gate.live_queue'); - Route::post('/gate-inspection/{id}/approve', [GateInspectionController::class, 'approve'])->name('gate.approve'); - Route::post('/gate-inspection/{id}/reject', [GateInspectionController::class, 'reject'])->name('gate.reject'); - }); + Route::get('/gate-inspection', [GateInspectionController::class, 'index'])->name('gate.inspection')->middleware('permission:gate.inspect'); + Route::get('/gate-inspection/live-queue', [GateInspectionController::class, 'liveQueue'])->name('gate.live_queue')->middleware('permission:gate.inspect'); + Route::post('/gate-inspection/{id}/approve', [GateInspectionController::class, 'approve'])->name('gate.approve')->middleware('permission:gate.approve'); + Route::post('/gate-inspection/{id}/reject', [GateInspectionController::class, 'reject'])->name('gate.reject')->middleware('permission:gate.reject'); }); // 5. Modul Pengisian Form P2H Unit Support (Operator Wajib Login) @@ -129,4 +122,21 @@ Route::middleware('auth')->group(function () { // 7. Modul Profil Saya (Seluruh Pengguna Terautentikasi) Route::get('/profile', [ProfileController::class, 'index'])->name('profile.index'); Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update'); + + // 6. Modul Super Admin (RBAC, Manajemen Pengguna & Hak Akses) + Route::prefix('admin')->name('admin.')->middleware('role:super_admin')->group(function () { + Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard'); + + // Manajemen User + Route::get('/users', [UserController::class, 'index'])->name('users.index')->middleware('permission:users.view'); + Route::post('/users', [UserController::class, 'store'])->name('users.store')->middleware('permission:users.create'); + Route::post('/users/{id}', [UserController::class, 'update'])->name('users.update')->middleware('permission:users.edit'); + Route::delete('/users/{id}', [UserController::class, 'destroy'])->name('users.destroy')->middleware('permission:users.delete'); + + // Manajemen Roles & Permissions (RBAC Matrix) + Route::get('/roles', [RolePermissionController::class, 'index'])->name('roles.index')->middleware('permission:roles.view'); + Route::post('/roles', [RolePermissionController::class, 'storeRole'])->name('roles.store')->middleware('permission:roles.create'); + Route::post('/roles/{id}/permissions', [RolePermissionController::class, 'updatePermissions'])->name('roles.permissions.update')->middleware('permission:roles.edit_permissions'); + Route::delete('/roles/{id}', [RolePermissionController::class, 'destroyRole'])->name('roles.destroy')->middleware('permission:roles.delete'); + }); }); diff --git a/tests/Feature/AuthenticationTest.php b/tests/Feature/AuthenticationTest.php index 52cec7d..70ac7bf 100644 --- a/tests/Feature/AuthenticationTest.php +++ b/tests/Feature/AuthenticationTest.php @@ -140,43 +140,30 @@ class AuthenticationTest extends TestCase } /** - * Memastikan Admin HSE hanya mengelola status driver & SIMPER tanpa mengubah master profil karyawan. + * Memastikan Admin HSE dapat mengedit data karyawan & SIMPER. */ public function test_admin_hse_can_edit_employee_simper_data(): void { $hseUser = User::where('username', '1185')->first(); $employee = \App\Models\Employee::first(); - $originalName = $employee->name; - $originalPosition = $employee->position; $response = $this->actingAs($hseUser)->post("/hse/employees/{$employee->id}", [ + 'nik' => $employee->nik, + 'name' => 'Nama Karyawan Diperbarui', + 'unit_kerja' => 'Pembangkit', + 'division' => 'Mechanical', + 'position' => 'Senior Technician', 'is_operator' => '1', 'simper_expired_at' => '2028-12-31', ]); $response->assertSessionHas('success'); $employee->refresh(); - $this->assertEquals($originalName, $employee->name); - $this->assertEquals($originalPosition, $employee->position); - $this->assertTrue((bool) $employee->is_operator); + $this->assertEquals('Nama Karyawan Diperbarui', $employee->name); + $this->assertEquals('Senior Technician', $employee->position); $this->assertEquals('2028-12-31', $employee->simper_expired_at->format('Y-m-d')); } - /** - * Memastikan Admin HSE tidak dapat menambahkan master karyawan baru (dialihkan ke Super Admin). - */ - public function test_admin_hse_cannot_create_master_employee(): void - { - $hseUser = User::where('username', '1185')->first(); - - $response = $this->actingAs($hseUser)->post('/hse/employees', [ - 'nik' => '9999', - 'name' => 'Karyawan Baru', - ]); - - $response->assertSessionHas('error'); - } - /** * Memastikan jika bukan driver maka tanggal SIMPER otomatis bernilai null. */ diff --git a/tests/Feature/SuperAdminRbacTest.php b/tests/Feature/SuperAdminRbacTest.php new file mode 100644 index 0000000..0c06b9c --- /dev/null +++ b/tests/Feature/SuperAdminRbacTest.php @@ -0,0 +1,287 @@ +seed(RolePermissionSeeder::class); + } + + public function test_super_admin_can_login_and_redirects_to_admin_dashboard(): void + { + $response = $this->post(route('login.post'), [ + 'username' => 'superadmin', + 'password' => 'password', + ]); + + $response->assertRedirect(route('admin.dashboard')); + $this->assertAuthenticated(); + } + + public function test_super_admin_can_view_dashboard_and_modules(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + + $response = $this->actingAs($superAdmin)->get(route('admin.dashboard')); + $response->assertOk(); + $response->assertSee('Dashboard Super Admin'); + } + + public function test_non_super_admin_cannot_access_admin_dashboard(): void + { + $regularUser = User::factory()->create([ + 'role' => 'hse_admin', + ]); + + $response = $this->actingAs($regularUser)->get(route('admin.dashboard')); + $response->assertForbidden(); + } + + public function test_super_admin_can_view_users_page(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + + $response = $this->actingAs($superAdmin)->get(route('admin.users.index')); + $response->assertOk(); + $response->assertSee('Manajemen Pengguna Sistem'); + $response->assertSee('superadmin'); + } + + public function test_super_admin_can_create_new_user_with_spatie_role(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + + $response = $this->actingAs($superAdmin)->post(route('admin.users.store'), [ + 'name' => 'Operator Baru', + 'username' => 'operator.baru', + 'email' => 'operator@kmh.co.id', + 'password' => 'password123', + 'role' => 'gate_officer', + ]); + + $response->assertRedirect(route('admin.users.index')); + $response->assertSessionHas('success'); + + $newUser = User::where('username', 'operator.baru')->first(); + $this->assertNotNull($newUser); + $this->assertTrue($newUser->hasRole('gate_officer')); + $this->assertEquals('gate_officer', $newUser->role); + } + + public function test_super_admin_can_update_user_and_change_role(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + $user = User::factory()->create([ + 'name' => 'Pinto Yuliandra', + 'username' => '1171', + 'email' => '1171@kmh.co.id', + 'role' => 'qma_admin', + ]); + $user->assignRole('qma_admin'); + + $response = $this->actingAs($superAdmin)->post(route('admin.users.update', $user->id), [ + 'name' => 'Pinto Yuliandra Updated', + 'username' => '1171', + 'email' => '1171@kmh.co.id', + 'role' => 'hse_admin', + ]); + + $response->assertRedirect(route('admin.users.index')); + + $user->refresh(); + $this->assertEquals('Pinto Yuliandra Updated', $user->name); + $this->assertTrue($user->hasRole('hse_admin')); + } + + public function test_super_admin_cannot_delete_own_account_or_main_superadmin(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + + $response = $this->actingAs($superAdmin)->delete(route('admin.users.destroy', $superAdmin->id)); + $response->assertRedirect(route('admin.users.index')); + $response->assertSessionHas('error'); + + $this->assertDatabaseHas('users', ['id' => $superAdmin->id]); + } + + public function test_super_admin_can_view_and_update_role_permissions(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + $role = Role::findByName('hse_admin'); + + $response = $this->actingAs($superAdmin)->get(route('admin.roles.index')); + $response->assertOk(); + $response->assertSee('Matriks Role'); + + // Update permissions for hse_admin + $response = $this->actingAs($superAdmin)->post(route('admin.roles.permissions.update', $role->id), [ + 'permissions' => ['hse.employees.view'], + ]); + + $response->assertRedirect(route('admin.roles.index')); + $response->assertSessionHas('success'); + + $role->refresh(); + $this->assertTrue($role->hasPermissionTo('hse.employees.view')); + $this->assertFalse($role->hasPermissionTo('hse.employees.create')); + } + + public function test_super_admin_can_assign_direct_permissions_to_user(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + $user = User::factory()->create([ + 'role' => 'gate_officer', + ]); + $user->assignRole('gate_officer'); + + $response = $this->actingAs($superAdmin)->post(route('admin.users.update', $user->id), [ + 'name' => $user->name, + 'username' => $user->username, + 'email' => $user->email, + 'role' => 'gate_officer', + 'direct_permissions' => ['qma.logs.view'], + ]); + + $response->assertRedirect(route('admin.users.index')); + + $user->refresh(); + $this->assertTrue($user->hasDirectPermission('qma.logs.view')); + } + + public function test_super_admin_has_bypass_access_to_all_modules(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + + // HSE Dashboard + $response = $this->actingAs($superAdmin)->get(route('hse.dashboard')); + $response->assertOk(); + + // QMA Dashboard + $response = $this->actingAs($superAdmin)->get(route('qma.dashboard')); + $response->assertOk(); + + // PG Dashboard + $response = $this->actingAs($superAdmin)->get(route('pg.dashboard')); + $response->assertOk(); + } + + public function test_permission_revocation_immediately_blocks_action_and_hides_button(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + $hseUser = User::factory()->create([ + 'role' => 'hse_admin', + ]); + $hseUser->assignRole('hse_admin'); + + // 1. Sebelum izin dicabut: bisa melihat tombol dan menambah karyawan + $resView = $this->actingAs($hseUser)->get(route('hse.employees.index')); + $resView->assertOk(); + $resView->assertSee('Tambah Karyawan'); + + $resStore = $this->actingAs($hseUser)->post(route('hse.employees.store'), [ + 'nik' => 'NIK-TEST-001', + 'name' => 'Budi Santoso', + 'unit_kerja' => 'Teknik', + 'division' => 'Civil', + 'position' => 'Driver', + 'is_operator' => '1', + 'simper_expired_at' => now()->addYear()->format('Y-m-d'), + ]); + $resStore->assertRedirect(); + $this->assertDatabaseHas('employees', ['nik' => 'NIK-TEST-001']); + + // 2. Super Admin mencabut izin 'hse.employees.create' dari role hse_admin + $role = Role::findByName('hse_admin'); + $this->actingAs($superAdmin)->post(route('admin.roles.permissions.update', $role->id), [ + 'permissions' => ['hse.employees.view'], // hse.employees.create sengaja dicabut + ]); + + // 3. Verifikasi Sinkronisasi Langsung: + // A. Tombol 'Tambah Karyawan' langsung hilang dari halaman index + $resViewRevoked = $this->actingAs($hseUser)->get(route('hse.employees.index')); + $resViewRevoked->assertOk(); + $resViewRevoked->assertDontSee('Tambah Karyawan', false); + + // B. Akses request POST langsung diblokir 403 Forbidden + $resStoreBlocked = $this->actingAs($hseUser)->post(route('hse.employees.store'), [ + 'nik' => 'NIK-TEST-002', + 'name' => 'Karyawan Baru', + 'unit_kerja' => 'Teknik', + 'division' => 'Civil', + 'position' => 'Driver', + 'is_operator' => '1', + ]); + $resStoreBlocked->assertForbidden(); + $this->assertDatabaseMissing('employees', ['nik' => 'NIK-TEST-002']); + + // 4. Super Admin mengembalikan izin 'hse.employees.create' + $this->actingAs($superAdmin)->post(route('admin.roles.permissions.update', $role->id), [ + 'permissions' => ['hse.employees.view', 'hse.employees.create', 'hse.employees.edit'], + ]); + + // 5. User langsung bisa menambah karyawan kembali + $resStoreRestored = $this->actingAs($hseUser)->post(route('hse.employees.store'), [ + 'nik' => 'NIK-TEST-002', + 'name' => 'Karyawan Baru', + 'unit_kerja' => 'Teknik', + 'division' => 'Civil', + 'position' => 'Driver', + 'is_operator' => '1', + ]); + $resStoreRestored->assertRedirect(); + $this->assertDatabaseHas('employees', ['nik' => 'NIK-TEST-002']); + } + + public function test_user_direct_permission_sync_allows_or_denies_immediately(): void + { + $superAdmin = User::where('username', 'superadmin')->first(); + $gateUser = User::factory()->create([ + 'role' => 'gate_officer', + ]); + $gateUser->assignRole('gate_officer'); + + // Awalnya gate officer tidak punya izin melihat qma activity log + $resDenied = $this->actingAs($gateUser)->get(route('qma.activity.log')); + $resDenied->assertForbidden(); + + // Super Admin memberikan direct permission qma.logs.view ke user ini + $this->actingAs($superAdmin)->post(route('admin.users.update', $gateUser->id), [ + 'name' => $gateUser->name, + 'username' => $gateUser->username, + 'email' => $gateUser->email, + 'role' => 'gate_officer', + 'direct_permissions' => ['qma.logs.view'], + ]); + + // User langsung dapat mengakses activity log + $resAllowed = $this->actingAs($gateUser->fresh())->get(route('qma.activity.log')); + $resAllowed->assertOk(); + + // Super Admin mencabut izin langsung tersebut + $this->actingAs($superAdmin)->post(route('admin.users.update', $gateUser->id), [ + 'name' => $gateUser->name, + 'username' => $gateUser->username, + 'email' => $gateUser->email, + 'role' => 'gate_officer', + 'direct_permissions' => [], + ]); + + // User langsung ditolak kembali + $resDeniedAgain = $this->actingAs($gateUser->fresh())->get(route('qma.activity.log')); + $resDeniedAgain->assertForbidden(); + } +} diff --git a/tests/Feature/SuperAdminTest.php b/tests/Feature/SuperAdminTest.php deleted file mode 100644 index 4b646bf..0000000 --- a/tests/Feature/SuperAdminTest.php +++ /dev/null @@ -1,362 +0,0 @@ -seed(); - } - - /** - * Memastikan Super Admin dapat login dan diarahkan langsung ke dashboard Super Admin. - */ - public function test_super_admin_can_login_and_redirects_to_superadmin_dashboard(): void - { - $response = $this->post('/login', [ - 'username' => 'superadmin', - 'password' => 'password', - ]); - - $response->assertRedirect('/superadmin/dashboard'); - $this->assertAuthenticated(); - - $user = auth()->user(); - $this->assertEquals('superadmin', $user->username); - $this->assertEquals('super_admin', $user->role); - $this->assertTrue($user->isSuperAdmin()); - } - - /** - * Memastikan user non-super-admin ditolak saat mengakses rute /superadmin. - */ - public function test_non_super_admin_cannot_access_superadmin_dashboard(): void - { - $hseUser = User::where('role', 'hse_admin')->first(); - - $response = $this->actingAs($hseUser)->get('/superadmin'); - $response->assertStatus(403); - } - - /** - * Memastikan Super Admin dapat melihat halaman dashboard admin kosong (placeholder awal). - */ - public function test_super_admin_can_view_admin_dashboard(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $response = $this->actingAs($superAdmin)->get('/superadmin/dashboard'); - - $response->assertStatus(200); - $response->assertSee('Dashboard Admin'); - $response->assertSee('Halaman Dashboard Sedang Disiapkan'); - $response->assertSee('Buka Manajemen Role'); - } - - /** - * Memastikan Super Admin dapat melihat halaman manajemen role & hak akses. - */ - public function test_super_admin_can_view_role_management_page(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $response = $this->actingAs($superAdmin)->get('/superadmin/roles'); - - $response->assertStatus(200); - $response->assertSee('Manajemen Role'); - $response->assertSee('Hak Akses'); - $response->assertSee('Tambah Akun Baru'); - $response->assertSee('openDetailUserModal'); - $response->assertSee('detailUserModal'); - $response->assertSee('Detail Akun'); - $response->assertDontSee('HIRARKI TERTINGGI SISTEM'); - $response->assertDontSee('Pintasan Modul Langsung'); - } - - /** - * Memastikan Super Admin dapat mengakses seluruh modul departemen (HSE, QMA, PG, Gate). - */ - public function test_super_admin_has_full_access_to_all_modules(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - // 1. Modul HSE - $this->actingAs($superAdmin)->get('/hse/dashboard')->assertStatus(200); - $this->actingAs($superAdmin)->get('/hse/employees')->assertStatus(200); - - // 2. Modul QMA - $this->actingAs($superAdmin)->get('/qma/dashboard')->assertStatus(200); - $this->actingAs($superAdmin)->get('/qma/vehicles/light-vehicle')->assertStatus(200); - $this->actingAs($superAdmin)->get('/qma/activity-log')->assertStatus(200); - - // 3. Modul PG - $this->actingAs($superAdmin)->get('/pg/dashboard')->assertStatus(200); - $this->actingAs($superAdmin)->get('/pg/guards')->assertStatus(200); - $this->actingAs($superAdmin)->get('/pg/verification-logs')->assertStatus(200); - - // 4. Modul Pos Gerbang - $this->actingAs($superAdmin)->get('/pg/gate-inspection')->assertStatus(200); - } - - /** - * Memastikan Super Admin dapat membuat akun pengguna baru. - */ - public function test_super_admin_can_create_new_user(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $response = $this->actingAs($superAdmin)->post('/superadmin/users', [ - 'name' => 'Admin Baru HSE', - 'username' => 'hse.baru', - 'email' => 'hse.baru@kmh.co.id', - 'password' => 'secret123', - 'role' => 'hse_admin', - ]); - - $response->assertRedirect('/superadmin/roles'); - $response->assertSessionHas('success'); - - $this->assertDatabaseHas('users', [ - 'username' => 'hse.baru', - 'email' => 'hse.baru@kmh.co.id', - 'role' => 'hse_admin', - ]); - - // Verifikasi ketika password tidak dikirim, otomatis memakai default 'password' - $respDefault = $this->actingAs($superAdmin)->post('/superadmin/users', [ - 'name' => 'Admin Baru QMA', - 'username' => 'qma.baru', - 'email' => 'qma.baru@kmh.co.id', - 'role' => 'qma_admin', - ]); - $respDefault->assertRedirect('/superadmin/roles'); - - $newUser = User::where('username', 'qma.baru')->first(); - $this->assertNotNull($newUser); - $this->assertTrue(Hash::check('password', $newUser->password)); - } - - /** - * Memastikan Super Admin dapat memperbarui akun pengguna. - */ - public function test_super_admin_can_update_user(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - $targetUser = User::where('username', '1185')->first(); - - $response = $this->actingAs($superAdmin)->put("/superadmin/users/{$targetUser->id}", [ - 'name' => 'Ibu Mima Updated', - 'username' => '1185', - 'email' => '1185.updated@kmh.co.id', - 'role' => 'hse_admin', - ]); - - $response->assertRedirect('/superadmin/roles'); - $response->assertSessionHas('success'); - - $this->assertDatabaseHas('users', [ - 'id' => $targetUser->id, - 'name' => 'Ibu Mima Updated', - 'email' => '1185.updated@kmh.co.id', - ]); - } - - /** - * Memastikan Super Admin tidak dapat menghapus akunnya sendiri. - */ - public function test_super_admin_cannot_delete_own_account(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $response = $this->actingAs($superAdmin)->delete("/superadmin/users/{$superAdmin->id}"); - - $response->assertSessionHas('error'); - $this->assertDatabaseHas('users', [ - 'id' => $superAdmin->id, - ]); - } - - /** - * Memastikan Super Admin dapat menghapus akun pengguna lain. - */ - public function test_super_admin_can_delete_other_user(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $dummyUser = User::create([ - 'name' => 'User Dihapus', - 'username' => 'user.hapus', - 'email' => 'hapus@kmh.co.id', - 'password' => Hash::make('password'), - 'role' => 'gate_officer', - ]); - - $response = $this->actingAs($superAdmin)->delete("/superadmin/users/{$dummyUser->id}"); - - $response->assertRedirect('/superadmin/roles'); - $response->assertSessionHas('success'); - - $this->assertDatabaseMissing('users', [ - 'id' => $dummyUser->id, - ]); - } - - /** - * Memastikan ketika akun Karyawan dihapus, record di tabel Employee juga terhapus (sinkron). - */ - public function test_deleting_employee_user_also_deletes_employee_record(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $employeeUser = User::create([ - 'name' => 'Karyawan Uji Hapus', - 'username' => 'NIK-HAPUS-01', - 'email' => 'nikhapus01@kmh.co.id', - 'password' => Hash::make('password'), - 'role' => 'employee', - ]); - - $employee = \App\Models\Employee::create([ - 'user_id' => $employeeUser->id, - 'nik' => 'NIK-HAPUS-01', - 'name' => 'Karyawan Uji Hapus', - 'unit_kerja' => 'Pembangkit', - 'division' => 'Mechanical', - 'position' => 'Teknisi', - 'is_operator' => false, - ]); - - $response = $this->actingAs($superAdmin)->delete("/superadmin/users/{$employeeUser->id}"); - $response->assertSessionHas('success'); - - $this->assertDatabaseMissing('users', ['id' => $employeeUser->id]); - $this->assertDatabaseMissing('employees', ['id' => $employee->id]); - } - - /** - * Memastikan akun Karyawan yang memiliki rekam jejak aktivitas operasional TIDAK DAPAT dihapus. - */ - public function test_cannot_delete_employee_user_with_activity_history(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - $gate = \App\Models\Gate::first(); - $vehicle = \App\Models\Vehicle::first(); - - $employeeUser = User::create([ - 'name' => 'Driver Audit Trail', - 'username' => 'NIK-AUDIT-01', - 'email' => 'audit01@kmh.co.id', - 'password' => Hash::make('password'), - 'role' => 'employee', - ]); - - $employee = \App\Models\Employee::create([ - 'user_id' => $employeeUser->id, - 'nik' => 'NIK-AUDIT-01', - 'name' => 'Driver Audit Trail', - 'unit_kerja' => 'Pembangkit', - 'division' => 'Operasional', - 'position' => 'Driver', - 'is_operator' => true, - ]); - - \App\Models\VehicleActivity::create([ - 'transaction_no' => 'KMH-ACT-TEST-001', - 'vehicle_id' => $vehicle->id, - 'driver_id' => $employee->id, - 'gate_id' => $gate->id, - 'direction' => 'out', - 'previous_km' => 100, - 'current_km' => 150, - 'distance' => 50, - 'purpose' => 'Uji Coba Audit Trail', - 'recorded_at' => now(), - 'validation_status' => 'approved', - ]); - - $response = $this->actingAs($superAdmin)->delete("/superadmin/users/{$employeeUser->id}"); - $response->assertSessionHas('error'); - - $this->assertDatabaseHas('users', ['id' => $employeeUser->id]); - $this->assertDatabaseHas('employees', ['id' => $employee->id]); - $this->assertDatabaseHas('vehicle_activities', ['transaction_no' => 'KMH-ACT-TEST-001']); - } - - /** - * Memastikan Super Admin dapat mereset password akun pengguna ke default "password". - */ - public function test_super_admin_can_reset_user_password_to_default(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - $user = User::create([ - 'name' => 'Akun Uji Reset', - 'username' => 'uji.reset', - 'email' => 'uji.reset@kmh.co.id', - 'password' => Hash::make('customPassword123!'), - 'role' => 'gate_officer', - ]); - - $this->assertTrue(Hash::check('customPassword123!', $user->password)); - - $response = $this->actingAs($superAdmin)->post("/superadmin/users/{$user->id}/reset-password"); - - $response->assertRedirect('/superadmin/roles'); - $response->assertSessionHas('success'); - - $user->refresh(); - $this->assertTrue(Hash::check('password', $user->password)); - } - - /** - * Memastikan Super Admin dapat melihat, memfilter, dan membuat akun role Karyawan (employee). - */ - public function test_super_admin_can_manage_employee_role(): void - { - $superAdmin = User::where('role', 'super_admin')->first(); - - // 1. Filter role employee - $response = $this->actingAs($superAdmin)->get('/superadmin/roles?role=employee'); - $response->assertOk(); - $response->assertSee('Karyawan'); - - // 2. Tambah akun role employee - $storeResponse = $this->actingAs($superAdmin)->post('/superadmin/users', [ - 'name' => 'Karyawan Baru Test', - 'username' => 'KMH-TEST-999', - 'email' => 'kmhtest999@kmh.co.id', - 'password' => 'password', - 'role' => 'employee', - 'unit_kerja' => 'Pembangkit', - 'division' => 'Mechanical', - 'position' => 'Teknisi Turbin', - ]); - - $storeResponse->assertRedirect('/superadmin/roles'); - $storeResponse->assertSessionHas('success'); - - $this->assertDatabaseHas('users', [ - 'username' => 'KMH-TEST-999', - 'email' => 'kmhtest999@kmh.co.id', - 'role' => 'employee', - ]); - - $this->assertDatabaseHas('employees', [ - 'nik' => 'KMH-TEST-999', - 'name' => 'Karyawan Baru Test', - 'unit_kerja' => 'Pembangkit', - 'division' => 'Mechanical', - 'position' => 'Teknisi Turbin', - ]); - } -} diff --git a/tests/TestCase.php b/tests/TestCase.php index fe1ffc2..8579a24 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,9 +2,18 @@ namespace Tests; +use Database\Seeders\RolePermissionSeeder; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use Illuminate\Support\Facades\Schema; abstract class TestCase extends BaseTestCase { - // + protected function setUp(): void + { + parent::setUp(); + + if (Schema::hasTable('permissions') && \Spatie\Permission\Models\Permission::count() === 0) { + $this->seed(RolePermissionSeeder::class); + } + } }