feat: implementasi log riwayat aktivitas super admin dengan tampilan ramah non-it

This commit is contained in:
Ray1111-aa
2026-10-17 09:28:35 +07:00
parent 034da013d3
commit d216322ac6
11 changed files with 1201 additions and 1 deletions
@@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;
class AdminActivityLogController extends Controller
{
/**
* Tampilkan riwayat log aktivitas yang dilakukan Super Admin.
*/
public function index(Request $request): View
{
$query = AdminActivityLog::with('user')->latest();
// 1. Filter Pencarian Kata Kunci
if ($request->filled('search')) {
$search = trim($request->input('search'));
$query->where(function ($q) use ($search) {
$q->where('description', 'like', "%{$search}%")
->orWhere('user_name', 'like', "%{$search}%")
->orWhere('user_username', 'like', "%{$search}%")
->orWhere('target_name', 'like', "%{$search}%");
});
}
// 2. Filter Tipe Aksi
if ($request->filled('action_type')) {
$query->where('action_type', $request->input('action_type'));
}
// 3. Filter Rentang Tanggal
if ($request->filled('start_date')) {
$query->whereDate('created_at', '>=', $request->input('start_date'));
}
if ($request->filled('end_date')) {
$query->whereDate('created_at', '<=', $request->input('end_date'));
}
$logs = $query->paginate(20)->withQueryString();
// Metrik Ringkasan di Bagian Atas
$today = Carbon::today();
$stats = [
'today_count' => AdminActivityLog::whereDate('created_at', $today)->count(),
'create_count' => AdminActivityLog::where('action_type', 'create')->count(),
'update_count' => AdminActivityLog::whereIn('action_type', ['update', 'permission'])->count(),
'delete_count' => AdminActivityLog::where('action_type', 'delete')->count(),
];
return view('admin.activity_logs.index', compact('logs', 'stats'));
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Models\Employee; use App\Models\Employee;
use App\Models\SecurityGuard; use App\Models\SecurityGuard;
use App\Models\User; use App\Models\User;
@@ -49,6 +50,10 @@ class DashboardController extends Controller
->take(5) ->take(5)
->get(); ->get();
return view('admin.dashboard', compact('metrics', 'usersByRole', 'recentUsers', 'recentActivities')); $recentAdminLogs = AdminActivityLog::latest()
->take(5)
->get();
return view('admin.dashboard', compact('metrics', 'usersByRole', 'recentUsers', 'recentActivities', 'recentAdminLogs'));
} }
} }
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\View\View; use Illuminate\View\View;
@@ -40,6 +41,18 @@ class RolePermissionController extends Controller
'guard_name' => 'web', 'guard_name' => 'web',
]); ]);
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleNameClean = ucwords(str_replace('_', ' ', $role->name));
AdminActivityLog::record(
actionType: 'create',
module: 'Role & Hak Akses',
description: "Menambahkan peran hak akses baru: '{$roleNameClean}' ({$role->name}) ke dalam sistem.",
targetType: 'Role',
targetId: $role->id,
targetName: $role->name,
newValues: ['name' => $role->name]
);
return redirect()->route('admin.roles.index') return redirect()->route('admin.roles.index')
->with('success', "Role [{$role->name}] berhasil ditambahkan ke sistem."); ->with('success', "Role [{$role->name}] berhasil ditambahkan ke sistem.");
} }
@@ -63,6 +76,19 @@ class RolePermissionController extends Controller
// Reset permission cache // Reset permission cache
app()[PermissionRegistrar::class]->forgetCachedPermissions(); app()[PermissionRegistrar::class]->forgetCachedPermissions();
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleNameClean = ucwords(str_replace('_', ' ', $role->name));
$count = count($selectedPermissions);
AdminActivityLog::record(
actionType: 'permission',
module: 'Role & Hak Akses',
description: "Memperbarui izin akses untuk peran '{$roleNameClean}' ({$count} izin akses aktif).",
targetType: 'Role',
targetId: $role->id,
targetName: $role->name,
newValues: ['permissions' => $selectedPermissions]
);
return redirect()->route('admin.roles.index') return redirect()->route('admin.roles.index')
->with('success', "Matriks permission untuk role [{$role->name}] berhasil diperbarui."); ->with('success', "Matriks permission untuk role [{$role->name}] berhasil diperbarui.");
} }
@@ -86,6 +112,17 @@ class RolePermissionController extends Controller
app()[PermissionRegistrar::class]->forgetCachedPermissions(); app()[PermissionRegistrar::class]->forgetCachedPermissions();
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleNameClean = ucwords(str_replace('_', ' ', $name));
AdminActivityLog::record(
actionType: 'delete',
module: 'Role & Hak Akses',
description: "Menghapus peran hak akses: '{$roleNameClean}' ({$name}) dari sistem.",
targetType: 'Role',
targetId: $roleId,
targetName: $name
);
return redirect()->route('admin.roles.index') return redirect()->route('admin.roles.index')
->with('success', "Role [{$name}] berhasil dihapus dari sistem."); ->with('success', "Role [{$name}] berhasil dihapus dari sistem.");
} }
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Admin; namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Models\Gate; use App\Models\Gate;
use App\Models\User; use App\Models\User;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -101,6 +102,24 @@ class UserController extends Controller
// Reset permission cache Spatie // Reset permission cache Spatie
app()[PermissionRegistrar::class]->forgetCachedPermissions(); app()[PermissionRegistrar::class]->forgetCachedPermissions();
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleTitle = $this->getFriendlyRoleName($validated['role']);
AdminActivityLog::record(
actionType: 'create',
module: 'Manajemen Pengguna',
description: "Menambahkan akun pengguna baru: {$user->name} (Username: {$user->username}) dengan hak akses '{$roleTitle}'.",
targetType: 'User',
targetId: $user->id,
targetName: $user->name,
newValues: [
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'role' => $validated['role'],
'gate_id' => $user->gate_id,
]
);
return redirect()->route('admin.users.index') return redirect()->route('admin.users.index')
->with('success', "Akun pengguna [{$user->name}] berhasil dibuat dengan role [{$validated['role']}]."); ->with('success', "Akun pengguna [{$user->name}] berhasil dibuat dengan role [{$validated['role']}].");
} }
@@ -129,14 +148,25 @@ class UserController extends Controller
'role.required' => 'Role wajib dipilih.', 'role.required' => 'Role wajib dipilih.',
]); ]);
$oldValues = [
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'role' => $user->role,
'gate_id' => $user->gate_id,
];
$oldRole = $user->role;
$user->name = $validated['name']; $user->name = $validated['name'];
$user->username = $validated['username']; $user->username = $validated['username'];
$user->email = $validated['email']; $user->email = $validated['email'];
$user->role = $validated['role']; $user->role = $validated['role'];
$user->gate_id = $validated['gate_id'] ?? null; $user->gate_id = $validated['gate_id'] ?? null;
$passwordUpdated = false;
if (!empty($validated['password'])) { if (!empty($validated['password'])) {
$user->password = Hash::make($validated['password']); $user->password = Hash::make($validated['password']);
$passwordUpdated = true;
} }
$user->save(); $user->save();
@@ -150,6 +180,53 @@ class UserController extends Controller
// Reset permission cache Spatie // Reset permission cache Spatie
app()[PermissionRegistrar::class]->forgetCachedPermissions(); app()[PermissionRegistrar::class]->forgetCachedPermissions();
// Susun deskripsi perubahan yang mudah dipahami non-IT
$roleChanged = $oldRole !== $validated['role'];
$changes = [];
if (($oldValues['name'] ?? '') !== $user->name) {
$changes[] = "nama dari '{$oldValues['name']}' menjadi '{$user->name}'";
}
if (($oldValues['username'] ?? '') !== $user->username) {
$changes[] = "username dari '{$oldValues['username']}' menjadi '{$user->username}'";
}
if (($oldValues['email'] ?? '') !== $user->email) {
$changes[] = "email menjadi '{$user->email}'";
}
if ($roleChanged) {
$oldRoleTitle = $this->getFriendlyRoleName($oldRole);
$newRoleTitle = $this->getFriendlyRoleName($validated['role']);
$changes[] = "hak akses dari '{$oldRoleTitle}' menjadi '{$newRoleTitle}'";
}
if ($passwordUpdated) {
$changes[] = "kata sandi (password) diperbarui";
}
$desc = "Memperbarui akun pengguna: {$user->name} ({$user->username})";
if (!empty($changes)) {
$desc .= " — " . implode(', ', $changes) . ".";
} else {
$desc .= " — Informasi profil disimpan.";
}
// Rekam ke Log Riwayat Aktivitas Super Admin
AdminActivityLog::record(
actionType: 'update',
module: 'Manajemen Pengguna',
description: $desc,
targetType: 'User',
targetId: $user->id,
targetName: $user->name,
oldValues: $oldValues,
newValues: [
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'role' => $validated['role'],
'gate_id' => $user->gate_id,
]
);
return redirect()->route('admin.users.index') return redirect()->route('admin.users.index')
->with('success', "Data pengguna [{$user->name}] berhasil diperbarui."); ->with('success', "Data pengguna [{$user->name}] berhasil diperbarui.");
} }
@@ -173,11 +250,50 @@ class UserController extends Controller
->with('error', 'Aksi Ditolak: Akun Super Administrator utama sistem tidak dapat dihapus.'); ->with('error', 'Aksi Ditolak: Akun Super Administrator utama sistem tidak dapat dihapus.');
} }
$deletedSnapshot = [
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'role' => $user->role,
'gate_id' => $user->gate_id,
];
$name = $user->name; $name = $user->name;
$username = $user->username;
$userRole = $user->role ?? '';
$userId = $user->id;
$user->syncRoles([]); $user->syncRoles([]);
$user->delete(); $user->delete();
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleTitle = $this->getFriendlyRoleName($userRole);
AdminActivityLog::record(
actionType: 'delete',
module: 'Manajemen Pengguna',
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
targetType: 'User',
targetId: $userId,
targetName: $name,
oldValues: $deletedSnapshot
);
return redirect()->route('admin.users.index') return redirect()->route('admin.users.index')
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem."); ->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
} }
/**
* Konversi kode role teknis menjadi nama peran yang mudah dipahami dalam Bahasa Indonesia.
*/
private function getFriendlyRoleName(string $role): string
{
return match($role) {
'super_admin' => 'Super Administrator (Akses Penuh)',
'hse_admin' => 'Admin HSE (Keselamatan & Karyawan)',
'qma_admin' => 'Admin QMA (Armada Kendaraan)',
'pg_admin' => 'Admin PG (Keamanan & Satpam)',
'gate_officer' => 'Petugas Pos Gerbang',
default => ucwords(str_replace('_', ' ', $role))
};
}
} }
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
class AdminActivityLog extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'user_name',
'user_username',
'action_type',
'module',
'target_type',
'target_id',
'target_name',
'description',
'old_values',
'new_values',
'ip_address',
'user_agent',
];
protected $casts = [
'old_values' => 'array',
'new_values' => 'array',
'created_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Helper statis untuk merekam log aktivitas Super Admin secara otomatis.
*/
public static function record(
string $actionType,
string $module,
string $description,
?string $targetType = null,
?int $targetId = null,
?string $targetName = null,
?array $oldValues = null,
?array $newValues = null
): self {
$actor = Auth::user();
return self::create([
'user_id' => $actor?->id,
'user_name' => $actor?->name ?? 'Super Admin',
'user_username' => $actor?->username ?? 'superadmin',
'action_type' => $actionType,
'module' => $module,
'target_type' => $targetType,
'target_id' => $targetId,
'target_name' => $targetName,
'description' => $description,
'old_values' => $oldValues,
'new_values' => $newValues,
'ip_address' => Request::ip(),
'user_agent' => Request::userAgent(),
]);
}
}
@@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('admin_activity_logs', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('user_name')->nullable();
$table->string('user_username')->nullable();
$table->string('action_type', 30)->index(); // 'create', 'update', 'delete', 'permission'
$table->string('module', 50)->index(); // 'Manajemen Pengguna', 'Role & Permission'
$table->string('target_type', 50)->nullable();
$table->unsignedBigInteger('target_id')->nullable();
$table->string('target_name')->nullable();
$table->text('description');
$table->json('old_values')->nullable();
$table->json('new_values')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->timestamps();
$table->index(['created_at', 'action_type']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('admin_activity_logs');
}
};
@@ -0,0 +1,562 @@
@extends('layouts.app')
@section('title', 'Log Riwayat Aktivitas Admin - Super Admin RKM')
@section('content')
<div class="space-y-6">
<!-- Header Halaman -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5">
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span>
<span>Log Riwayat Aktivitas Admin</span>
</h1>
<p class="text-xs text-slate-500 mt-1">
Catatan lengkap kegiatan admin: penambahan akun, perubahan data, pengaturan hak akses, dan penghapusan data di sistem RKM-KMH.
</p>
</div>
<div class="flex items-center gap-2">
<span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-50 text-indigo-700 border border-indigo-200">
<i class="fa-solid fa-shield-halved"></i>
<span>Rekaman Keamanan Sistem</span>
</span>
</div>
</div>
<!-- Metrik Ringkasan Aktivitas -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="flex items-center justify-between">
<div>
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Hari Ini</span>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-1 block">{{ number_format($stats['today_count']) }}</span>
</div>
<div class="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-lg">
<i class="fa-solid fa-calendar-day"></i>
</div>
</div>
<span class="text-[10px] text-slate-400 font-medium block mt-2">Aktivitas admin hari ini</span>
</div>
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="flex items-center justify-between">
<div>
<span class="text-[11px] font-bold text-emerald-600 uppercase tracking-wider block">Tambah Baru</span>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-1 block">{{ number_format($stats['create_count']) }}</span>
</div>
<div class="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center text-lg">
<i class="fa-solid fa-circle-plus"></i>
</div>
</div>
<span class="text-[10px] text-slate-400 font-medium block mt-2">Akun / data baru dibuat</span>
</div>
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="flex items-center justify-between">
<div>
<span class="text-[11px] font-bold text-amber-600 uppercase tracking-wider block">Ubah & Hak Akses</span>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-1 block">{{ number_format($stats['update_count']) }}</span>
</div>
<div class="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center text-lg">
<i class="fa-solid fa-pen-to-square"></i>
</div>
</div>
<span class="text-[10px] text-slate-400 font-medium block mt-2">Data atau izin yang diperbarui</span>
</div>
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="flex items-center justify-between">
<div>
<span class="text-[11px] font-bold text-rose-600 uppercase tracking-wider block">Hapus Data</span>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-1 block">{{ number_format($stats['delete_count']) }}</span>
</div>
<div class="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center text-lg">
<i class="fa-solid fa-trash-can"></i>
</div>
</div>
<span class="text-[10px] text-slate-400 font-medium block mt-2">Data dihapus dari sistem</span>
</div>
</div>
<!-- Filter & Pencarian Cepat -->
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<form method="GET" action="{{ route('admin.activity_logs.index') }}" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
<!-- Input Pencarian Kata Kunci -->
<div class="lg:col-span-2">
<label for="search" class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-1.5">Cari Aktivitas</label>
<div class="relative">
<input type="text"
id="search"
name="search"
value="{{ request('search') }}"
placeholder="Cari nama admin, nama akun, kata kunci..."
class="w-full text-xs rounded-xl border border-slate-200 bg-slate-50/50 hover:bg-white focus:bg-white pl-9 pr-3 py-2.5 text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition shadow-2xs">
<i class="fa-solid fa-magnifying-glass text-slate-400 text-xs absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
<!-- Jenis Kegiatan -->
<div>
<label for="action_type" class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-1.5">Jenis Kegiatan</label>
<select id="action_type"
name="action_type"
class="w-full text-xs rounded-xl border border-slate-200 bg-slate-50/50 hover:bg-white focus:bg-white px-3 py-2.5 text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition shadow-2xs">
<option value="">Semua Jenis Kegiatan</option>
<option value="create" {{ request('action_type') === 'create' ? 'selected' : '' }}>🟢 Penambahan Data Baru</option>
<option value="update" {{ request('action_type') === 'update' ? 'selected' : '' }}>🟡 Perubahan / Edit Data</option>
<option value="permission" {{ request('action_type') === 'permission' ? 'selected' : '' }}>🔵 Pengaturan Hak Akses</option>
<option value="delete" {{ request('action_type') === 'delete' ? 'selected' : '' }}>🔴 Penghapusan Data</option>
</select>
</div>
<!-- Tanggal Mulai -->
<div>
<label for="start_date" class="block text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-1.5">Dari Tanggal</label>
<input type="date"
id="start_date"
name="start_date"
value="{{ request('start_date') }}"
class="w-full text-xs rounded-xl border border-slate-200 bg-slate-50/50 hover:bg-white focus:bg-white px-3 py-2 text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition shadow-2xs">
</div>
<!-- Tombol Submit & Reset -->
<div class="flex items-end gap-2">
<button type="submit"
class="flex-1 py-2.5 px-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-2xs transition flex items-center justify-center gap-1.5 cursor-pointer">
<i class="fa-solid fa-filter text-xs"></i>
<span>Terapkan</span>
</button>
@if(request()->anyFilled(['search', 'action_type', 'start_date', 'end_date']))
<a href="{{ route('admin.activity_logs.index') }}"
class="py-2.5 px-3 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition flex items-center justify-center cursor-pointer"
title="Reset Filter">
<i class="fa-solid fa-rotate-left"></i>
</a>
@endif
</div>
</form>
</div>
<!-- Tabel Riwayat Aktivitas Admin -->
<div class="bg-white rounded-none sm:rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="min-w-full text-xs text-left border-collapse">
<!-- Header Navy Solid Gelap #06213f -->
<thead class="bg-[#06213f] text-white font-bold text-[11px] uppercase tracking-wider">
<tr>
<th class="py-3.5 px-4 text-center w-12">NO</th>
<th class="py-3.5 px-4 w-36">TANGGAL & WAKTU</th>
<th class="py-3.5 px-4 w-44">ADMIN PELAKSANA</th>
<th class="py-3.5 px-4 text-center w-28">JENIS AKSI</th>
<th class="py-3.5 px-4 w-36">BAGIAN / MENU</th>
<th class="py-3.5 px-4">RINGKASAN KEGIATAN</th>
<th class="py-3.5 px-4 text-center w-28">RINCIAN</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700 bg-white">
@forelse($logs as $index => $log)
@php
$rowNum = $logs->firstItem() ? ($logs->firstItem() + $index) : ($index + 1);
@endphp
<tr class="hover:bg-slate-50/70 transition">
<!-- Nomor -->
<td class="py-3.5 px-4 text-center font-medium text-slate-400">{{ $rowNum }}</td>
<!-- Waktu & Tanggal -->
<td class="py-3.5 px-4 font-mono text-[11px] text-slate-600 whitespace-nowrap">
<span class="font-bold text-slate-900 block">{{ $log->created_at->format('d M Y') }}</span>
<span class="text-slate-400">{{ $log->created_at->format('H:i') }} WIB</span>
</td>
<!-- Pelaku Admin -->
<td class="py-3.5 px-4">
<div class="flex items-center gap-2">
<div class="w-7 h-7 rounded-lg bg-indigo-50 text-indigo-700 font-bold text-[10px] flex items-center justify-center flex-shrink-0 border border-indigo-200/60">
{{ strtoupper(substr($log->user_name ?? 'A', 0, 1)) }}
</div>
<div class="min-w-0">
<span class="font-bold text-slate-900 block truncate leading-tight">{{ $log->user_name ?? 'Super Admin' }}</span>
<span class="text-[10px] text-slate-400 font-mono block truncate">{{ $log->user_username ?? 'superadmin' }}</span>
</div>
</div>
</td>
<!-- Jenis Aksi -->
<td class="py-3.5 px-4 text-center">
@if($log->action_type === 'create')
<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-black bg-emerald-50 text-emerald-800 border border-emerald-300">
<i class="fa-solid fa-plus text-[9px]"></i>
<span>TAMBAH</span>
</span>
@elseif($log->action_type === 'update')
<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-black bg-amber-50 text-amber-800 border border-amber-300">
<i class="fa-solid fa-pen text-[9px]"></i>
<span>UBAH</span>
</span>
@elseif($log->action_type === 'permission')
<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-black bg-blue-50 text-blue-800 border border-blue-300">
<i class="fa-solid fa-shield-halved text-[9px]"></i>
<span>HAK AKSES</span>
</span>
@elseif($log->action_type === 'delete')
<span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-black bg-rose-50 text-rose-800 border border-rose-300">
<i class="fa-solid fa-trash text-[9px]"></i>
<span>HAPUS</span>
</span>
@else
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-slate-100 text-slate-700">
{{ strtoupper($log->action_type) }}
</span>
@endif
</td>
<!-- Bagian / Menu -->
<td class="py-3.5 px-4 font-semibold text-slate-700 whitespace-nowrap">
<span class="px-2.5 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] border border-slate-200/80 font-medium">
{{ $log->module }}
</span>
</td>
<!-- Ringkasan Kegiatan -->
<td class="py-3.5 px-4 text-slate-800 leading-relaxed font-medium">
<div>{{ $log->description }}</div>
@if($log->target_name)
<span class="inline-block mt-0.5 text-[10px] font-semibold text-indigo-600 bg-indigo-50/70 px-2 py-0.5 rounded-md border border-indigo-100">
Target: {{ $log->target_name }}
</span>
@endif
</td>
<!-- Tombol Rincian Modal -->
<td class="py-3.5 px-4 text-center">
@if(!empty($log->old_values) || !empty($log->new_values))
<button type="button"
onclick='openLogDetailModal(@json($log))'
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-indigo-700 bg-indigo-50 hover:bg-indigo-100 border border-indigo-200/80 text-[11px] font-bold transition cursor-pointer"
title="Lihat Rincian Perubahan">
<i class="fa-solid fa-list-check text-xs"></i>
<span>Rincian</span>
</button>
@else
<span class="text-slate-300 text-[11px]">-</span>
@endif
</td>
</tr>
@empty
<tr>
<td colspan="7" class="py-12 text-center text-slate-400">
<div class="max-w-xs mx-auto space-y-2">
<div class="w-12 h-12 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto text-xl">
<i class="fa-solid fa-clock-rotate-left"></i>
</div>
<p class="font-bold text-slate-700 text-sm">Belum Ada Riwayat Kegiatan</p>
<p class="text-xs text-slate-400">Setiap kali admin menambah akun, mengedit data, atau mengatur hak akses, catatannya akan otomatis tersimpan di sini.</p>
</div>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@if($logs->hasPages())
<div class="p-4 border-t border-slate-100 bg-slate-50/50">
{{ $logs->links() }}
</div>
@endif
</div>
</div>
<!-- ========================================================================= -->
<!-- MODAL RINCIAN DATA PERUBAHAN (RAMAH UNTUK PENGGUNA NON-IT) -->
<!-- ========================================================================= -->
<div id="logDetailModal" class="fixed inset-0 z-50 hidden overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-2xl max-w-2xl w-full shadow-2xl border border-slate-200 overflow-hidden transform transition-all">
<!-- Header Modal -->
<div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/80">
<div class="flex items-center gap-2.5">
<div class="w-8 h-8 rounded-xl bg-indigo-50 text-indigo-700 flex items-center justify-center font-bold text-sm">
<i class="fa-solid fa-file-lines"></i>
</div>
<div>
<h3 class="text-sm font-extrabold text-slate-900" id="detailModalTitle">Rincian Perubahan Data</h3>
<p class="text-[11px] text-slate-400" id="detailModalSubtitle">Catatan riwayat aktivitas</p>
</div>
</div>
<button type="button" onclick="closeLogDetailModal()" class="text-slate-400 hover:text-slate-600 p-1.5 rounded-lg hover:bg-slate-100 transition cursor-pointer">
<i class="fa-solid fa-xmark text-base"></i>
</button>
</div>
<!-- Isi Modal -->
<div class="p-5 space-y-4 max-h-[75vh] overflow-y-auto">
<!-- Informasi Umum Kegiatan -->
<div class="bg-indigo-50/40 rounded-xl p-3.5 border border-indigo-100 text-xs">
<div class="font-bold text-slate-800 text-sm mb-1" id="detailModalDescription"></div>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-2 text-[11px] text-slate-600 mt-2.5 pt-2.5 border-t border-indigo-100/80">
<div>
<span class="text-slate-400 block text-[10px] uppercase font-bold">Admin Pelaksana:</span>
<strong class="text-slate-800 font-semibold" id="detailModalActor"></strong>
</div>
<div>
<span class="text-slate-400 block text-[10px] uppercase font-bold">Waktu Kejadian:</span>
<strong class="text-slate-800 font-semibold" id="detailModalTime"></strong>
</div>
<div>
<span class="text-slate-400 block text-[10px] uppercase font-bold">Bagian Menu:</span>
<strong class="text-slate-800 font-semibold" id="detailModalModule"></strong>
</div>
</div>
</div>
<!-- Wadah Render Visual yang Ramah Non-IT -->
<div id="detailHumanFriendlyContainer" class="space-y-3">
<!-- Diisi secara dinamis oleh JavaScript -->
</div>
<!-- Bagian Opsional untuk Teknis / Raw Data (Bisa Dibuka-Tutup) -->
<div class="pt-2">
<button type="button"
onclick="toggleTechnicalDetails()"
class="text-[11px] font-bold text-slate-400 hover:text-indigo-600 flex items-center gap-1 transition cursor-pointer">
<i class="fa-solid fa-code text-[10px]"></i>
<span id="techToggleText">Tampilkan Rincian Format Teknis (JSON)</span>
</button>
<div id="technicalDetailsBlock" class="hidden mt-2 p-3 bg-slate-900 text-slate-200 rounded-xl font-mono text-[10px] space-y-2 overflow-x-auto">
<div>
<span class="text-rose-400 font-bold block mb-1">Old Values:</span>
<pre id="detailOldValuesText" class="whitespace-pre-wrap break-words"></pre>
</div>
<div class="pt-2 border-t border-slate-800">
<span class="text-emerald-400 font-bold block mb-1">New Values:</span>
<pre id="detailNewValuesText" class="whitespace-pre-wrap break-words"></pre>
</div>
</div>
</div>
</div>
<!-- Footer Modal -->
<div class="px-5 py-3 border-t border-slate-100 bg-slate-50 flex justify-end">
<button type="button"
onclick="closeLogDetailModal()"
class="px-4 py-2 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded-xl text-xs font-bold transition cursor-pointer">
Tutup
</button>
</div>
</div>
</div>
<script>
// Kamus terjemahan istilah ramah pengguna (Non-IT Friendly Dictionary)
const FIELD_LABELS = {
'name': 'Nama Lengkap',
'username': 'Username Akun',
'email': 'Alamat Email',
'role': 'Peran / Hak Akses',
'gate_id': 'Penugasan Pos Gerbang',
'password': 'Kata Sandi',
'password_changed': 'Status Password',
'permissions': 'Daftar Izin Akses',
'status': 'Status Akun'
};
const ROLE_LABELS = {
'super_admin': 'Super Administrator (Akses Penuh)',
'hse_admin': 'Admin HSE (Keselamatan & Karyawan)',
'qma_admin': 'Admin QMA (Armada Kendaraan)',
'pg_admin': 'Admin PG (Keamanan & Satpam)',
'gate_officer': 'Petugas Pos Gerbang',
'employee': 'Karyawan Biasa'
};
const ACTION_TITLES = {
'create': 'Penambahan Data Baru',
'update': 'Perubahan Data Akun',
'permission': 'Pengaturan Hak Akses',
'delete': 'Penghapusan Data'
};
function formatFieldValue(key, val) {
if (val === null || val === undefined || val === '') {
return '<span class="text-slate-400 italic">(Tidak diatur / Kosong)</span>';
}
if (key === 'role') {
return `<strong class="text-indigo-700 font-semibold">${ROLE_LABELS[val] || val}</strong>`;
}
if (key === 'gate_id') {
return `Pos Gerbang #${val}`;
}
if (key === 'password_changed') {
return val ? '<span class="text-emerald-700 font-bold">Kata Sandi Baru Telah Ditetapkan</span>' : 'Tidak Berubah';
}
if (Array.isArray(val)) {
if (val.length === 0) return '<span class="text-slate-400 italic">(Tidak ada izin yang dipilih)</span>';
return `<div class="flex flex-wrap gap-1 max-h-36 overflow-y-auto p-1.5 bg-slate-50 rounded-lg border border-slate-200">
${val.map(item => `<span class="px-2 py-0.5 rounded text-[10px] font-medium bg-white text-slate-700 border border-slate-200/80 shadow-2xs">${item}</span>`).join('')}
</div>`;
}
return `<span>${val}</span>`;
}
function openLogDetailModal(log) {
const actionTitle = ACTION_TITLES[log.action_type] || log.action_type.toUpperCase();
document.getElementById('detailModalTitle').textContent = `Rincian: ${actionTitle}`;
document.getElementById('detailModalSubtitle').textContent = `Bagian: ${log.module} • ID Log: #${log.id}`;
document.getElementById('detailModalDescription').textContent = log.description;
document.getElementById('detailModalActor').textContent = `${log.user_name || 'Admin'} (${log.user_username || 'system'})`;
document.getElementById('detailModalModule').textContent = log.module;
const dateObj = new Date(log.created_at);
document.getElementById('detailModalTime').textContent = dateObj.toLocaleDateString('id-ID', {
day: 'numeric', month: 'short', year: 'numeric'
}) + ' ' + dateObj.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }) + ' WIB';
const container = document.getElementById('detailHumanFriendlyContainer');
container.innerHTML = '';
const oldVals = log.old_values || {};
const newVals = log.new_values || {};
const hasOld = Object.keys(oldVals).length > 0;
const hasNew = Object.keys(newVals).length > 0;
// Mode 1: Edit / Update (Bandingkan Sebelum vs Sesudah)
if (hasOld && hasNew) {
const allKeys = Array.from(new Set([...Object.keys(oldVals), ...Object.keys(newVals)]));
let tableRows = '';
allKeys.forEach(key => {
const label = FIELD_LABELS[key] || key.replace('_', ' ').toUpperCase();
const oldFmt = formatFieldValue(key, oldVals[key]);
const newFmt = formatFieldValue(key, newVals[key]);
const isDifferent = JSON.stringify(oldVals[key]) !== JSON.stringify(newVals[key]);
const rowBg = isDifferent ? 'bg-amber-50/40' : 'bg-white';
const statusBadge = isDifferent
? '<span class="inline-block px-1.5 py-0.5 rounded text-[9px] font-bold bg-amber-100 text-amber-800">Berubah</span>'
: '<span class="text-slate-300 text-[10px]">Sama</span>';
tableRows += `
<tr class="${rowBg} border-b border-slate-100">
<td class="py-2.5 px-3 font-semibold text-slate-700 whitespace-nowrap">
${label}
<div class="mt-0.5">${statusBadge}</div>
</td>
<td class="py-2.5 px-3 text-slate-600 bg-rose-50/20">${oldFmt}</td>
<td class="py-2.5 px-3 text-slate-800 bg-emerald-50/20 font-medium">${newFmt}</td>
</tr>
`;
});
container.innerHTML = `
<div class="rounded-xl border border-slate-200 overflow-hidden shadow-2xs">
<table class="w-full text-xs text-left">
<thead class="bg-slate-100 text-slate-600 font-bold text-[10px] uppercase">
<tr>
<th class="py-2 px-3 w-36">Kolom Data</th>
<th class="py-2 px-3 bg-rose-50/60 text-rose-800 w-1/2">Data Sebelum Diubah</th>
<th class="py-2 px-3 bg-emerald-50/60 text-emerald-800 w-1/2">Data Sesudah Diubah</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
</div>
`;
}
// Mode 2: Penambahan Baru (Hanya Ada Data Baru)
else if (hasNew) {
let rows = '';
Object.entries(newVals).forEach(([key, val]) => {
const label = FIELD_LABELS[key] || key.replace('_', ' ').toUpperCase();
rows += `
<div class="flex flex-col sm:flex-row sm:items-center justify-between py-2 border-b border-slate-100 gap-1">
<span class="text-slate-500 font-medium w-44">${label}</span>
<div class="text-slate-900 font-semibold flex-1">${formatFieldValue(key, val)}</div>
</div>
`;
});
container.innerHTML = `
<div class="rounded-xl border border-emerald-200 bg-emerald-50/20 p-4">
<span class="text-[11px] font-bold text-emerald-800 uppercase tracking-wider block mb-2 flex items-center gap-1.5">
<i class="fa-solid fa-circle-plus"></i>
<span>Rincian Data Baru yang Ditambahkan:</span>
</span>
<div class="text-xs divide-y divide-slate-100 bg-white rounded-lg p-3 border border-emerald-100">
${rows}
</div>
</div>
`;
}
// Mode 3: Penghapusan (Hanya Ada Data Lama / Terhapus)
else if (hasOld) {
let rows = '';
Object.entries(oldVals).forEach(([key, val]) => {
const label = FIELD_LABELS[key] || key.replace('_', ' ').toUpperCase();
rows += `
<div class="flex flex-col sm:flex-row sm:items-center justify-between py-2 border-b border-slate-100 gap-1">
<span class="text-slate-500 font-medium w-44">${label}</span>
<div class="text-slate-900 font-semibold flex-1">${formatFieldValue(key, val)}</div>
</div>
`;
});
container.innerHTML = `
<div class="rounded-xl border border-rose-200 bg-rose-50/20 p-4">
<span class="text-[11px] font-bold text-rose-800 uppercase tracking-wider block mb-2 flex items-center gap-1.5">
<i class="fa-solid fa-trash-can"></i>
<span>Rincian Data Sebelum Dihapus:</span>
</span>
<div class="text-xs divide-y divide-slate-100 bg-white rounded-lg p-3 border border-rose-100">
${rows}
</div>
</div>
`;
} else {
container.innerHTML = `
<p class="text-xs text-slate-400 italic text-center py-4">Tidak ada rincian data tersimpan untuk aktivitas ini.</p>
`;
}
// Set raw JSON for developers if opened
document.getElementById('detailOldValuesText').textContent = hasOld ? JSON.stringify(oldVals, null, 2) : '(none)';
document.getElementById('detailNewValuesText').textContent = hasNew ? JSON.stringify(newVals, null, 2) : '(none)';
// Reset tech view block to hidden
document.getElementById('technicalDetailsBlock').classList.add('hidden');
document.getElementById('techToggleText').textContent = 'Tampilkan Rincian Format Teknis (JSON)';
document.getElementById('logDetailModal').classList.remove('hidden');
}
function toggleTechnicalDetails() {
const block = document.getElementById('technicalDetailsBlock');
const text = document.getElementById('techToggleText');
if (block.classList.contains('hidden')) {
block.classList.remove('hidden');
text.textContent = 'Sembunyikan Rincian Format Teknis (JSON)';
} else {
block.classList.add('hidden');
text.textContent = 'Tampilkan Rincian Format Teknis (JSON)';
}
}
function closeLogDetailModal() {
document.getElementById('logDetailModal').classList.add('hidden');
}
// Tutup saat klik di luar modal / Escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
closeLogDetailModal();
}
});
document.getElementById('logDetailModal')?.addEventListener('click', function(e) {
if (e.target === this) {
closeLogDetailModal();
}
});
</script>
@endsection
+71
View File
@@ -26,6 +26,11 @@
<i class="fa-solid fa-shield-halved text-indigo-600 text-sm"></i> <i class="fa-solid fa-shield-halved text-indigo-600 text-sm"></i>
<span>Matriks Role & Izin</span> <span>Matriks Role & Izin</span>
</a> </a>
<a href="{{ route('admin.activity_logs.index') }}"
class="inline-flex items-center gap-2 px-4 py-2.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 rounded-xl text-xs font-bold shadow-sm transition">
<i class="fa-solid fa-clock-rotate-left text-indigo-600 text-sm"></i>
<span>Log Aktivitas</span>
</a>
</div> </div>
</div> </div>
@@ -274,5 +279,71 @@
</div> </div>
</div> </div>
</div> </div>
<!-- Log Riwayat Aktivitas Terkini (Super Admin) -->
<div class="bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm">
<div class="flex items-center justify-between mb-4">
<div>
<h2 class="text-sm font-bold text-slate-800 flex items-center gap-2">
<i class="fa-solid fa-clock-rotate-left text-indigo-600"></i>
Aktivitas Administratif Terkini
</h2>
<p class="text-xs text-slate-400 mt-0.5">5 tindakan terakhir yang dilakukan oleh Super Admin</p>
</div>
<a href="{{ route('admin.activity_logs.index') }}" class="text-xs font-bold text-indigo-600 hover:text-indigo-800 flex items-center gap-1">
<span>Lihat Semua Riwayat</span>
<i class="fa-solid fa-arrow-right text-[10px]"></i>
</a>
</div>
<div class="overflow-x-auto">
<table class="w-full text-left text-xs">
<thead>
<tr class="border-b border-slate-100 text-slate-400 font-semibold">
<th class="pb-2.5 w-36">Tanggal & Waktu</th>
<th class="pb-2.5 w-28 text-center">Jenis Aksi</th>
<th class="pb-2.5 w-36">Bagian</th>
<th class="pb-2.5">Keterangan Kegiatan</th>
<th class="pb-2.5 text-right w-36">Admin</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-50">
@forelse($recentAdminLogs as $log)
<tr class="hover:bg-slate-50/60 transition">
<td class="py-2.5 pr-2 font-mono text-[11px] text-slate-500 whitespace-nowrap">
{{ $log->created_at->format('d M, H:i') }} WIB
</td>
<td class="py-2.5 pr-2 text-center">
@if($log->action_type === 'create')
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-black bg-emerald-50 text-emerald-800 border border-emerald-300">TAMBAH</span>
@elseif($log->action_type === 'update')
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-black bg-amber-50 text-amber-800 border border-amber-300">UBAH</span>
@elseif($log->action_type === 'permission')
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-black bg-blue-50 text-blue-800 border border-blue-300">HAK AKSES</span>
@elseif($log->action_type === 'delete')
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-black bg-rose-50 text-rose-800 border border-rose-300">HAPUS</span>
@else
<span class="inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-bold bg-slate-100 text-slate-700">{{ strtoupper($log->action_type) }}</span>
@endif
</td>
<td class="py-2.5 pr-2 text-slate-600 font-medium">
<span class="px-2 py-0.5 rounded-lg bg-slate-100 text-slate-700 text-[10px]">{{ $log->module }}</span>
</td>
<td class="py-2.5 pr-2 text-slate-800 font-medium">
{{ $log->description }}
</td>
<td class="py-2.5 text-right font-bold text-slate-700">
{{ $log->user_name ?? 'Super Admin' }}
</td>
</tr>
@empty
<tr>
<td colspan="5" class="py-4 text-center text-slate-400">Belum ada riwayat aktivitas yang tercatat.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div> </div>
@endsection @endsection
+10
View File
@@ -258,6 +258,12 @@
<i class="fa-solid fa-shield-halved text-base w-5 text-center"></i> <i class="fa-solid fa-shield-halved text-base w-5 text-center"></i>
<span>Role & Permission</span> <span>Role & Permission</span>
</a> </a>
<a href="{{ route('admin.activity_logs.index') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.activity_logs.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-clock-rotate-left text-base w-5 text-center"></i>
<span>Log Aktivitas Admin</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
@@ -547,6 +553,10 @@
<i class="fa-solid fa-shield-halved w-5 text-center"></i> <i class="fa-solid fa-shield-halved w-5 text-center"></i>
<span>Role & Permission</span> <span>Role & Permission</span>
</a> </a>
<a href="{{ route('admin.activity_logs.index') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.activity_logs.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-clock-rotate-left w-5 text-center"></i>
<span>Log Aktivitas Admin</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
+4
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Http\Controllers\Admin\AdminActivityLogController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController; use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\RolePermissionController; use App\Http\Controllers\Admin\RolePermissionController;
use App\Http\Controllers\Admin\UserController; use App\Http\Controllers\Admin\UserController;
@@ -162,5 +163,8 @@ Route::middleware('auth')->group(function () {
Route::post('/roles', [RolePermissionController::class, 'storeRole'])->name('roles.store')->middleware('permission:roles.create'); 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::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'); Route::delete('/roles/{id}', [RolePermissionController::class, 'destroyRole'])->name('roles.destroy')->middleware('permission:roles.delete');
// Log Riwayat Aktivitas Super Admin
Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index');
}); });
}); });
+223
View File
@@ -0,0 +1,223 @@
<?php
namespace Tests\Feature;
use App\Models\AdminActivityLog;
use App\Models\User;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class AdminActivityLogTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(RolePermissionSeeder::class);
}
public function test_super_admin_can_view_activity_logs_page(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
// Create a dummy log
AdminActivityLog::record(
actionType: 'create',
module: 'Manajemen Pengguna',
description: 'Menambahkan user baru: Test User',
targetType: 'User',
targetId: 999,
targetName: 'Test User'
);
$response = $this->actingAs($superAdmin)->get(route('admin.activity_logs.index'));
$response->assertOk();
$response->assertSee('Log Riwayat Aktivitas Admin');
$response->assertSee('Menambahkan user baru: Test User');
$response->assertSee('Test User');
}
public function test_non_super_admin_cannot_access_activity_logs(): void
{
$regularUser = User::factory()->create([
'role' => 'hse_admin',
]);
$response = $this->actingAs($regularUser)->get(route('admin.activity_logs.index'));
$response->assertForbidden();
}
public function test_user_creation_is_logged(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
$response = $this->actingAs($superAdmin)->post(route('admin.users.store'), [
'name' => 'Operator Test Log',
'username' => 'operator.log',
'email' => '[email protected]',
'password' => 'password123',
'role' => 'gate_officer',
]);
$response->assertRedirect(route('admin.users.index'));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'create',
'module' => 'Manajemen Pengguna',
'target_type' => 'User',
'target_name' => 'Operator Test Log',
'user_username' => 'superadmin',
]);
$log = AdminActivityLog::where('target_name', 'Operator Test Log')->first();
$this->assertNotNull($log);
$this->assertStringContainsString('Operator Test Log', $log->description);
$this->assertNotNull($log->new_values);
$this->assertEquals('gate_officer', $log->new_values['role']);
}
public function test_user_update_is_logged_with_diff(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
$user = User::factory()->create([
'name' => 'Original Name',
'username' => 'update.target',
'email' => '[email protected]',
'role' => 'gate_officer',
]);
$user->assignRole('gate_officer');
$response = $this->actingAs($superAdmin)->post(route('admin.users.update', $user->id), [
'name' => 'Updated Name',
'username' => 'update.target',
'email' => '[email protected]',
'role' => 'hse_admin',
]);
$response->assertRedirect(route('admin.users.index'));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'update',
'module' => 'Manajemen Pengguna',
'target_type' => 'User',
'target_name' => 'Updated Name',
]);
$log = AdminActivityLog::where('target_name', 'Updated Name')->first();
$this->assertNotNull($log);
$this->assertEquals('Original Name', $log->old_values['name']);
$this->assertEquals('Updated Name', $log->new_values['name']);
$this->assertEquals('gate_officer', $log->old_values['role']);
$this->assertEquals('hse_admin', $log->new_values['role']);
}
public function test_user_deletion_is_logged(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
$user = User::factory()->create([
'name' => 'Delete Me',
'username' => 'delete.me',
'email' => '[email protected]',
'role' => 'gate_officer',
]);
$user->assignRole('gate_officer');
$response = $this->actingAs($superAdmin)->delete(route('admin.users.destroy', $user->id));
$response->assertRedirect(route('admin.users.index'));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'delete',
'module' => 'Manajemen Pengguna',
'target_type' => 'User',
'target_name' => 'Delete Me',
]);
}
public function test_role_creation_and_permission_update_are_logged(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
// 1. Create Role
$response = $this->actingAs($superAdmin)->post(route('admin.roles.store'), [
'name' => 'auditor_custom',
]);
$response->assertRedirect(route('admin.roles.index'));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'create',
'module' => 'Role & Hak Akses',
'target_name' => 'auditor_custom',
]);
$createdRole = Role::findByName('auditor_custom');
// 2. Update Permissions
$response = $this->actingAs($superAdmin)->post(route('admin.roles.permissions.update', $createdRole->id), [
'permissions' => ['hse.employees.view'],
]);
$response->assertRedirect(route('admin.roles.index'));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'permission',
'module' => 'Role & Hak Akses',
'target_name' => 'auditor_custom',
]);
}
public function test_activity_logs_filtering_works(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
// Create 2 different logs
AdminActivityLog::record(
actionType: 'create',
module: 'Manajemen Pengguna',
description: 'Membuat user alpha',
targetType: 'User',
targetName: 'user.alpha'
);
AdminActivityLog::record(
actionType: 'delete',
module: 'Manajemen Pengguna',
description: 'Menghapus user beta',
targetType: 'User',
targetName: 'user.beta'
);
// Filter by action_type = delete
$response = $this->actingAs($superAdmin)->get(route('admin.activity_logs.index', ['action_type' => 'delete']));
$response->assertOk();
$response->assertSee('Menghapus user beta');
$response->assertDontSee('Membuat user alpha');
// Filter by search = alpha
$responseSearch = $this->actingAs($superAdmin)->get(route('admin.activity_logs.index', ['search' => 'alpha']));
$responseSearch->assertOk();
$responseSearch->assertSee('Membuat user alpha');
$responseSearch->assertDontSee('Menghapus user beta');
}
public function test_dashboard_displays_recent_activity_widget(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
AdminActivityLog::record(
actionType: 'create',
module: 'Manajemen Pengguna',
description: 'Aktivitas Khusus Dashboard Test',
targetType: 'User',
targetName: 'dash.test'
);
$response = $this->actingAs($superAdmin)->get(route('admin.dashboard'));
$response->assertOk();
$response->assertSee('Aktivitas Administratif Terkini');
$response->assertSee('Aktivitas Khusus Dashboard Test');
}
}