diff --git a/app/Http/Controllers/Employee/DashboardController.php b/app/Http/Controllers/Employee/DashboardController.php
index 60875f4..c9a5295 100644
--- a/app/Http/Controllers/Employee/DashboardController.php
+++ b/app/Http/Controllers/Employee/DashboardController.php
@@ -3,11 +3,16 @@
namespace App\Http\Controllers\Employee;
use App\Http\Controllers\Controller;
+use App\Models\P2hRecord;
+use App\Models\UnitSupportTimesheet;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
+use App\Services\P2hInspectionPdfExporter;
+use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
+use Illuminate\Http\Response;
use Illuminate\View\View;
class DashboardController extends Controller
@@ -201,4 +206,260 @@ class DashboardController extends Controller
'validated_at' => $activity->validated_at ? $activity->validated_at->format('H:i') . ' WIB' : null,
]);
}
+
+ /**
+ * Tampilkan halaman Riwayat Aktivitas Pribadi Karyawan.
+ * Mengisolasi data hanya milik karyawan yang sedang login (P2H, Timesheet Alat Berat, dan Perjalanan LV).
+ * Tab yang tampil dinamis menyesuaikan hak akses dan catatan riwayat yang dimiliki karyawan.
+ */
+ public function history(Request $request): View
+ {
+ $user = auth()->user();
+ if (!$user->isSuperAdmin() && !$user->can('employee.dashboard') && !$user->can('employee.timesheet') && !$user->can('employee.p2h') && !$user->isEmployee()) {
+ abort(403, 'Akses Ditolak: Anda tidak memiliki wewenang untuk membuka halaman riwayat aktivitas karyawan.');
+ }
+
+ $employee = $user->getOrCreateEmployee();
+
+ // 1. Periksa ketersediaan modul/tab berdasarkan wewenang (permission) & riwayat aktual karyawan
+ $canP2h = $user->can('employee.p2h') || ($employee && P2hRecord::where('employee_id', $employee->id)->exists());
+ $canTimesheet = ($employee && $employee->is_operator) || ($employee && UnitSupportTimesheet::where('operator_id', $employee->id)->exists()) || $user->can('qma.logs.view');
+ $canTrips = $user->can('employee.timesheet') || ($employee && VehicleActivity::where('driver_id', $employee->id)->exists());
+
+ // Hitung total catatan riwayat per kategori untuk badge tab
+ $p2hCount = $employee ? P2hRecord::where('employee_id', $employee->id)->count() : 0;
+ $timesheetCount = $employee ? UnitSupportTimesheet::where('operator_id', $employee->id)->count() : 0;
+ $tripCount = $employee ? VehicleActivity::where('driver_id', $employee->id)->count() : 0;
+
+ // Tentukan tab aktif
+ $availableTabs = [];
+ if ($canP2h) {
+ $availableTabs[] = 'p2h';
+ }
+ if ($canTimesheet) {
+ $availableTabs[] = 'timesheet';
+ }
+ if ($canTrips) {
+ $availableTabs[] = 'trips';
+ }
+
+ $requestedTab = $request->query('tab');
+ if ($requestedTab && in_array($requestedTab, $availableTabs, true)) {
+ $activeTab = $requestedTab;
+ } else {
+ $activeTab = $availableTabs[0] ?? 'none';
+ }
+
+ // Filter parameter
+ $search = trim((string) $request->query('search', ''));
+ $dateFrom = $request->query('date_from');
+ $dateTo = $request->query('date_to');
+ $status = $request->query('status');
+
+ $p2hRecords = collect();
+ $timesheetRecords = collect();
+ $tripRecords = collect();
+
+ // Query data khusus tab aktif
+ if ($employee && $activeTab === 'p2h') {
+ $query = P2hRecord::with(['vehicle', 'template', 'validator'])
+ ->where('employee_id', $employee->id);
+
+ if ($search !== '') {
+ $query->where(function ($q) use ($search) {
+ $q->where('transaction_no', 'like', "%{$search}%")
+ ->orWhereHas('vehicle', function ($vq) use ($search) {
+ $vq->where('code', 'like', "%{$search}%")
+ ->orWhere('brand_type', 'like', "%{$search}%");
+ });
+ });
+ }
+
+ if ($dateFrom) {
+ $query->whereDate('inspected_at', '>=', $dateFrom);
+ }
+ if ($dateTo) {
+ $query->whereDate('inspected_at', '<=', $dateTo);
+ }
+
+ if ($status) {
+ if (in_array($status, ['pending', 'approved', 'rejected'], true)) {
+ $query->where('validation_status', $status);
+ } elseif (in_array($status, ['good', 'has_defect'], true)) {
+ $query->where('summary_condition', $status);
+ }
+ }
+
+ $p2hRecords = $query->latest('inspected_at')
+ ->latest('id')
+ ->paginate(15)
+ ->withQueryString();
+ } elseif ($employee && $activeTab === 'timesheet') {
+ $query = UnitSupportTimesheet::with(['vehicle'])
+ ->where('operator_id', $employee->id);
+
+ if ($search !== '') {
+ $query->where(function ($q) use ($search) {
+ $q->where('timesheet_no', 'like', "%{$search}%")
+ ->orWhere('location', 'like', "%{$search}%")
+ ->orWhere('task_description', 'like', "%{$search}%")
+ ->orWhereHas('vehicle', function ($vq) use ($search) {
+ $vq->where('code', 'like', "%{$search}%")
+ ->orWhere('brand_type', 'like', "%{$search}%");
+ });
+ });
+ }
+
+ if ($dateFrom) {
+ $query->whereDate('date', '>=', $dateFrom);
+ }
+ if ($dateTo) {
+ $query->whereDate('date', '<=', $dateTo);
+ }
+
+ if ($status) {
+ $query->where('status', $status);
+ }
+
+ $timesheetRecords = $query->latest('date')
+ ->latest('id')
+ ->paginate(15)
+ ->withQueryString();
+ } elseif ($employee && $activeTab === 'trips') {
+ $query = VehicleActivity::with(['vehicle', 'gate', 'securityGuard'])
+ ->where('driver_id', $employee->id);
+
+ if ($search !== '') {
+ $query->where(function ($q) use ($search) {
+ $q->where('transaction_no', 'like', "%{$search}%")
+ ->orWhere('purpose', 'like', "%{$search}%")
+ ->orWhereHas('vehicle', function ($vq) use ($search) {
+ $vq->where('code', 'like', "%{$search}%")
+ ->orWhere('brand_type', 'like', "%{$search}%")
+ ->orWhere('license_plate', 'like', "%{$search}%");
+ })
+ ->orWhereHas('gate', function ($gq) use ($search) {
+ $gq->where('name', 'like', "%{$search}%");
+ });
+ });
+ }
+
+ if ($dateFrom) {
+ $query->whereDate('recorded_at', '>=', $dateFrom);
+ }
+ if ($dateTo) {
+ $query->whereDate('recorded_at', '<=', $dateTo);
+ }
+
+ if ($status) {
+ $query->where('validation_status', $status);
+ }
+
+ $tripRecords = $query->latest('recorded_at')
+ ->latest('id')
+ ->paginate(15)
+ ->withQueryString();
+ }
+
+ // Ringkasan KPI pribadi karyawan
+ $stats = [
+ 'p2h_total' => $p2hCount,
+ 'p2h_good' => $employee ? P2hRecord::where('employee_id', $employee->id)->where('summary_condition', 'good')->count() : 0,
+ 'p2h_defects' => $employee ? P2hRecord::where('employee_id', $employee->id)->where('summary_condition', 'has_defect')->count() : 0,
+ 'timesheet_total' => $timesheetCount,
+ 'timesheet_hours' => $employee ? (float) UnitSupportTimesheet::where('operator_id', $employee->id)->sum('operating_hours') : 0.0,
+ 'trip_total' => $tripCount,
+ 'trip_distance' => $employee ? (float) VehicleActivity::where('driver_id', $employee->id)->sum('distance') : 0.0,
+ ];
+
+ return view('employee.history', compact(
+ 'employee',
+ 'canP2h',
+ 'canTimesheet',
+ 'canTrips',
+ 'p2hCount',
+ 'timesheetCount',
+ 'tripCount',
+ 'activeTab',
+ 'p2hRecords',
+ 'timesheetRecords',
+ 'tripRecords',
+ 'stats',
+ 'search',
+ 'dateFrom',
+ 'dateTo',
+ 'status'
+ ));
+ }
+
+ /**
+ * Detail checklist P2H pribadi karyawan (Format JSON untuk modal inspeksi).
+ */
+ public function p2hDetail(int $id): JsonResponse
+ {
+ $user = auth()->user();
+ $employee = $user->getOrCreateEmployee();
+
+ $record = P2hRecord::with(['vehicle', 'employee', 'template', 'validator', 'items'])
+ ->findOrFail($id);
+
+ if (!$user->isSuperAdmin() && (!$employee || $record->employee_id !== $employee->id)) {
+ abort(403, 'Aksi Ditolak: Anda hanya dapat melihat lembar pemeriksaan P2H milik Anda sendiri.');
+ }
+
+ return response()->json([
+ 'id' => $record->id,
+ 'transaction_no' => $record->transaction_no,
+ 'vehicle_code' => $record->vehicle?->code ?? '-',
+ 'vehicle_name' => $record->vehicle?->brand_type ?? '-',
+ 'template_name' => $record->template?->name ?? 'P2H Checksheet',
+ 'shift' => $record->shift,
+ 'start_hm' => $record->start_hm,
+ 'start_km' => $record->start_km,
+ 'summary_condition' => $record->summary_condition,
+ 'defect_count' => $record->defect_count,
+ 'general_notes' => $record->general_notes,
+ 'validation_status' => $record->validation_status,
+ 'validator_name' => $record->validator?->name,
+ 'validation_notes' => $record->validation_notes,
+ 'validated_at' => $record->validated_at ? $record->validated_at->format('d/m/Y H:i') : null,
+ 'inspected_at' => $record->inspected_at ? $record->inspected_at->format('d/m/Y H:i') : null,
+ 'items' => $record->items->map(function ($item) {
+ return [
+ 'id' => $item->id,
+ 'item_name' => $item->title,
+ 'section' => $item->section,
+ 'condition' => $item->condition_status,
+ 'notes' => $item->notes,
+ ];
+ }),
+ ]);
+ }
+
+ /**
+ * Download / Cetak PDF lembar pemeriksaan P2H pribadi milik karyawan.
+ */
+ public function p2hPdf(int $id): Response
+ {
+ $user = auth()->user();
+ $employee = $user->getOrCreateEmployee();
+
+ $record = P2hRecord::with(['vehicle', 'employee', 'template', 'validator', 'items'])
+ ->findOrFail($id);
+
+ if (!$user->isSuperAdmin() && (!$employee || $record->employee_id !== $employee->id)) {
+ abort(403, 'Aksi Ditolak: Anda hanya dapat mengunduh lembar pemeriksaan P2H milik Anda sendiri.');
+ }
+
+ $pdfBinary = P2hInspectionPdfExporter::generate($record);
+ $fileName = 'Lembar_P2H_' . ($record->vehicle->code ?? 'Unit') . '_' . $record->transaction_no . '.pdf';
+
+ return response($pdfBinary, 200, [
+ 'Content-Type' => 'application/pdf',
+ 'Content-Disposition' => 'inline; filename="' . $fileName . '"',
+ 'Content-Length' => strlen($pdfBinary),
+ 'Cache-Control' => 'private, max-age=0, must-revalidate',
+ 'Pragma' => 'public',
+ ]);
+ }
}
diff --git a/resources/views/employee/dashboard.blade.php b/resources/views/employee/dashboard.blade.php
index e389fee..b4758f8 100644
--- a/resources/views/employee/dashboard.blade.php
+++ b/resources/views/employee/dashboard.blade.php
@@ -312,9 +312,16 @@
Catatan mobilisasi kendaraan yang pernah Anda isi di sistem.
-
- {{ $myRecentActivities->count() }} Perjalanan Terbaru
-
+
@@ -411,6 +418,11 @@
Catatan mobilisasi unit kendaraan ringan (LV) yang Anda kendarai akan otomatis muncul di sini setelah Anda mengisi formulir perjalanan.
+
@endif
diff --git a/resources/views/employee/history.blade.php b/resources/views/employee/history.blade.php
new file mode 100644
index 0000000..e53971b
--- /dev/null
+++ b/resources/views/employee/history.blade.php
@@ -0,0 +1,637 @@
+@extends('layouts.app')
+
+@section('title', 'Riwayat Aktivitas - Sistem RKM | PT Kerinci Merangin Hidro')
+
+@section('content')
+
+
+
+
+
+
+ Portal Karyawan
+ •
+ Catatan Operasional
+
+
+
+ Rekap seluruh aktivitas pemeriksaan kelaikan P2H, timesheet alat berat, dan mobilisasi kendaraan Anda.
+
+
+
+
+
+
+
+
+ @if($canP2h)
+
+
P2H Heavy Equipment
+
+ {{ number_format($stats['p2h_total']) }}
+
+ {{ $stats['p2h_good'] }} Layak
+
+
+
+ {{ $stats['p2h_defects'] }} catatan memiliki temuan kerusakan
+
+
+ @endif
+
+ @if($canTimesheet)
+
+
Timesheet Alat Berat
+
+ {{ number_format($stats['timesheet_hours'], 1, ',', '.') }} Jam
+
+ {{ number_format($stats['timesheet_total']) }} Sesi
+
+
+
+ Total akumulasi jam operasi alat berat
+
+
+ @endif
+
+ @if($canTrips)
+
+
Perjalanan Gerbang (LV)
+
+ {{ number_format($stats['trip_distance'], 0, ',', '.') }} KM
+
+ {{ number_format($stats['trip_total']) }} Trip
+
+
+
+ Jarak kumulatif mobilisasi kendaraan dinas
+
+
+ @endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ @if($activeTab === 'p2h')
+ @if(isset($p2hRecords) && $p2hRecords->isNotEmpty())
+
+
+
+
+ | Waktu Inspeksi |
+ No. Transaksi |
+ Unit Alat Berat |
+ Shift & Odometer |
+ Kelaikan Operasi |
+ Status QMA |
+ Aksi |
+
+
+
+ @foreach($p2hRecords as $rec)
+
+ |
+ {{ $rec->inspected_at ? $rec->inspected_at->format('d/m/Y') : '-' }}
+ {{ $rec->inspected_at ? $rec->inspected_at->format('H:i') . ' WIB' : '-' }}
+ |
+
+ {{ $rec->transaction_no }}
+ |
+
+ {{ $rec->vehicle->code ?? '-' }}
+ {{ $rec->vehicle->brand_type ?? '-' }}
+ |
+
+ Shift {{ $rec->shift }}
+ HM: {{ number_format($rec->start_hm, 1) }}
+ |
+
+ @if($rec->summary_condition === 'good')
+
+ Layak Jalan
+
+ @else
+
+ Ada Temuan ({{ $rec->defect_count }})
+
+ @endif
+ |
+
+ @if($rec->validation_status === 'approved')
+
+ Disetujui
+
+ @elseif($rec->validation_status === 'rejected')
+
+ Ditolak
+
+ @else
+
+ Menunggu QMA
+
+ @endif
+ |
+
+
+
+ PDF
+
+ |
+
+ @endforeach
+
+
+
+
+
+
+ {{ $p2hRecords->links() }}
+
+ @else
+
+
Belum Ada Riwayat P2H Heavy Equipment
+
+ Data pemeriksaan kelaikan unit yang pernah Anda kerjakan akan otomatis tampil di tabel ini.
+
+ @can('employee.p2h')
+
+ @endcan
+
+ @endif
+
+
+
+
+ @elseif($activeTab === 'timesheet')
+ @if(isset($timesheetRecords) && $timesheetRecords->isNotEmpty())
+
+
+
+
+ | Tanggal & Shift |
+ No. Timesheet |
+ Unit Alat Berat |
+ Odometer (HM / KM) |
+ Jam Operasi |
+ Lokasi & Aktivitas |
+ Status |
+
+
+
+ @foreach($timesheetRecords as $ts)
+
+ |
+ {{ $ts->date ? $ts->date->format('d/m/Y') : '-' }}
+ Shift {{ $ts->shift }}
+ |
+
+ {{ $ts->timesheet_no }}
+ |
+
+ {{ $ts->vehicle->code ?? '-' }}
+ {{ $ts->vehicle->brand_type ?? '-' }}
+ |
+
+ {{ number_format($ts->start_meter, 1) }} → {{ number_format($ts->end_meter, 1) }}
+ {{ strtoupper($ts->meter_type ?? 'HM') }}
+ |
+
+ {{ number_format($ts->operating_hours, 1) }} Jam
+ @if($ts->standby_hours > 0 || $ts->breakdown_hours > 0)
+
+ Stb: {{ number_format($ts->standby_hours, 1) }} | BD: {{ number_format($ts->breakdown_hours, 1) }}
+
+ @endif
+ |
+
+ {{ $ts->location ?? '-' }}
+ {{ $ts->task_description ?? '-' }}
+ |
+
+ @if($ts->status === 'completed')
+
+ Selesai
+
+ @else
+
+ Berjalan
+
+ @endif
+ |
+
+ @endforeach
+
+
+
+
+
+
+ {{ $timesheetRecords->links() }}
+
+ @else
+
+
Belum Ada Riwayat Timesheet Alat Berat
+
+ Data jam kerja dan catatan operasional operator heavy equipment akan tampil di sini setelah dicatat.
+
+
+ @endif
+
+
+
+
+ @elseif($activeTab === 'trips')
+ @if(isset($tripRecords) && $tripRecords->isNotEmpty())
+
+
+
+
+ | Waktu |
+ No. Transaksi |
+ Unit Kendaraan |
+ Pos Gerbang & Arah |
+ Odometer & Jarak |
+ Keperluan |
+ Status Satpam |
+
+
+
+ @foreach($tripRecords as $act)
+
+ |
+ {{ $act->recorded_at ? $act->recorded_at->format('d/m/Y') : '-' }}
+ {{ $act->recorded_at ? $act->recorded_at->format('H:i') . ' WIB' : '-' }}
+ |
+
+ {{ $act->transaction_no }}
+ |
+
+ {{ $act->vehicle->code ?? '-' }}
+
+ {{ $act->vehicle->brand_type ?? '-' }} • {{ $act->vehicle->license_plate ?? 'Tanpa Plat' }}
+
+ |
+
+ {{ $act->gate->name ?? 'Pos Gerbang' }}
+ @if($act->direction === 'in')
+
+ MASUK
+
+ @else
+
+ KELUAR
+
+ @endif
+ |
+
+ {{ number_format($act->current_km, 0, ',', '.') }} KM
+ +{{ number_format($act->distance, 0, ',', '.') }} KM
+ |
+
+
+ {{ $act->purpose ?: '-' }}
+
+ |
+
+ @if($act->validation_status === 'approved')
+
+ Disetujui
+
+ @elseif($act->validation_status === 'cancelled')
+
+ Dibatalkan
+
+ @elseif($act->validation_status === 'rejected')
+
+ Ditolak
+
+ @else
+
+ Menunggu Satpam
+
+ @endif
+ |
+
+ @endforeach
+
+
+
+
+
+
+ {{ $tripRecords->links() }}
+
+ @else
+
+
Belum Ada Riwayat Perjalanan Pos Gerbang
+
+ Catatan mobilisasi kendaraan ringan (LV) Anda yang melewati pos penjagaan satpam akan dicatat di sini.
+
+
+ @endif
+
+ @else
+
+
Tidak Ada Modul Riwayat yang Tersedia
+
+ Akun Anda saat ini belum memiliki hak akses operasional yang aktif.
+
+
+ @endif
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Detail Lembar P2H
+
Hasil pemeriksaan kelaikan unit alat berat
+
+
+
+
+
+
+
+
+
+ Unit Alat Berat
+ -
+ -
+
+
+ Shift & Odometer
+ -
+ -
+
+
+ Waktu Inspeksi
+ -
+
+
+ Status Approval
+ -
+
+
+
+
+
+
+
+
+
Daftar Pemeriksaan Komponen:
+
+
+
+
+ | Bagian |
+ Komponen / Item |
+ Kondisi |
+ Catatan Temuan |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+@endsection
diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php
index bc7b1d1..a0a2c56 100644
--- a/resources/views/layouts/app.blade.php
+++ b/resources/views/layouts/app.blade.php
@@ -501,6 +501,12 @@
Timesheet
@endcan
+
+
@endif
@@ -881,6 +887,11 @@
Timesheet
@endcan
+
+
@endif
@@ -987,6 +998,8 @@
Log Verifikasi Gerbang
@elseif(request()->routeIs('employee.dashboard'))
Dashboard Karyawan
+ @elseif(request()->routeIs('employee.history*'))
+ Riwayat Aktivitas
@elseif(request()->routeIs('p2h.*'))
Pemeriksaan P2H
@elseif(request()->routeIs('timesheet.*') || request()->routeIs('mobilisasi.*'))
diff --git a/routes/web.php b/routes/web.php
index f7db37a..f2e05b8 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -188,8 +188,11 @@ Route::middleware('auth')->group(function () {
Route::post('/{code}', [P2hFormController::class, 'store'])->middleware('throttle:30,1')->name('store');
});
- // 6. Modul Karyawan (Dashboard, P2H, Timesheet)
+ // 6. Modul Karyawan (Dashboard, Riwayat Aktivitas, P2H, Timesheet)
Route::get('/karyawan/dashboard', [\App\Http\Controllers\Employee\DashboardController::class, 'index'])->name('employee.dashboard');
+ Route::get('/karyawan/riwayat', [\App\Http\Controllers\Employee\DashboardController::class, 'history'])->name('employee.history');
+ Route::get('/karyawan/riwayat/p2h/{id}', [\App\Http\Controllers\Employee\DashboardController::class, 'p2hDetail'])->name('employee.history.p2h_detail');
+ Route::get('/karyawan/riwayat/p2h/{id}/pdf', [\App\Http\Controllers\Employee\DashboardController::class, 'p2hPdf'])->name('employee.history.p2h_pdf');
Route::get('/karyawan/aktivitas/status-polling', [\App\Http\Controllers\Employee\DashboardController::class, 'activeTripStatus'])->name('employee.activity.status_polling');
Route::post('/karyawan/aktivitas/{id}/update-km', [\App\Http\Controllers\Employee\DashboardController::class, 'updateKm'])->name('employee.activity.update_km');
Route::post('/karyawan/aktivitas/{id}/cancel', [\App\Http\Controllers\Employee\DashboardController::class, 'cancelActivity'])->name('employee.activity.cancel');
diff --git a/tests/Feature/EmployeeHistoryTest.php b/tests/Feature/EmployeeHistoryTest.php
new file mode 100644
index 0000000..3811ad5
--- /dev/null
+++ b/tests/Feature/EmployeeHistoryTest.php
@@ -0,0 +1,338 @@
+seed(RolePermissionSeeder::class);
+
+ // Karyawan / Operator A
+ $this->userA = User::create([
+ 'name' => 'Operator Alex Test',
+ 'username' => 'operator_alex',
+ 'email' => 'alex@kerinci.local',
+ 'password' => Hash::make('password123'),
+ 'role' => 'employee',
+ ]);
+ $this->userA->givePermissionTo(['employee.dashboard', 'employee.p2h', 'employee.timesheet']);
+ $this->empA = $this->userA->getOrCreateEmployee();
+ $this->empA->update(['is_operator' => true]);
+
+ // Karyawan / Operator B
+ $this->userB = User::create([
+ 'name' => 'Operator Budi Test',
+ 'username' => 'operator_budi',
+ 'email' => 'budi@kerinci.local',
+ 'password' => Hash::make('password123'),
+ 'role' => 'employee',
+ ]);
+ $this->userB->givePermissionTo(['employee.dashboard', 'employee.p2h', 'employee.timesheet']);
+ $this->empB = $this->userB->getOrCreateEmployee();
+ $this->empB->update(['is_operator' => true]);
+
+ // Unit Heavy Equipment
+ $this->heavyEquipment = Vehicle::create([
+ 'code' => 'EXC-HIST-01',
+ 'brand_type' => 'Komatsu PC200 History Test',
+ 'category' => 'unit_support',
+ 'unit_category' => 'Excavator',
+ 'status' => 'Operation',
+ ]);
+
+ // Unit Light Vehicle
+ $this->lightVehicle = Vehicle::create([
+ 'code' => 'LV-HIST-01',
+ 'brand_type' => 'Toyota Hilux 4x4',
+ 'category' => 'light_vehicle',
+ 'license_plate' => 'BH 1234 XY',
+ 'status' => 'Operation',
+ ]);
+
+ // Pos Gerbang
+ $this->gate = Gate::create([
+ 'name' => 'Pos Gerbang Utama PLTA',
+ 'code' => 'PG-01',
+ 'status' => 'active',
+ ]);
+
+ // Template P2H
+ $this->template = P2hTemplate::firstOrCreate(
+ ['code' => 'EXD4RP'],
+ [
+ 'name' => 'Excavator Checksheet Test',
+ 'is_active' => true,
+ ]
+ );
+ }
+
+ public function test_guest_is_redirected_to_login(): void
+ {
+ $response = $this->get(route('employee.history'));
+ $response->assertRedirect(route('login'));
+ }
+
+ public function test_employee_can_access_history_page(): void
+ {
+ $response = $this->actingAs($this->userA)->get(route('employee.history'));
+ $response->assertStatus(200);
+ $response->assertSee('Riwayat Aktivitas Saya');
+ $response->assertSee('P2H Heavy Equipment');
+ }
+
+ public function test_employee_only_sees_their_own_p2h_records(): void
+ {
+ // P2H milik A
+ $recordA = P2hRecord::create([
+ 'transaction_no' => 'P2H-ALEX-001',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'employee_id' => $this->empA->id,
+ 'template_id' => $this->template->id,
+ 'shift' => '1',
+ 'start_hm' => 1250.5,
+ 'summary_condition' => 'good',
+ 'defect_count' => 0,
+ 'validation_status' => 'approved',
+ 'inspected_at' => Carbon::now(),
+ ]);
+
+ // P2H milik B
+ $recordB = P2hRecord::create([
+ 'transaction_no' => 'P2H-BUDI-999',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'employee_id' => $this->empB->id,
+ 'template_id' => $this->template->id,
+ 'shift' => '2',
+ 'start_hm' => 2400.0,
+ 'summary_condition' => 'has_defect',
+ 'defect_count' => 1,
+ 'validation_status' => 'pending',
+ 'inspected_at' => Carbon::now(),
+ ]);
+
+ // Acting as User A
+ $responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'p2h']));
+ $responseA->assertStatus(200);
+ $responseA->assertSee('P2H-ALEX-001');
+ $responseA->assertDontSee('P2H-BUDI-999');
+
+ // Acting as User B
+ $responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'p2h']));
+ $responseB->assertStatus(200);
+ $responseB->assertSee('P2H-BUDI-999');
+ $responseB->assertDontSee('P2H-ALEX-001');
+ }
+
+ public function test_employee_only_sees_their_own_timesheets(): void
+ {
+ // Timesheet milik Operator A
+ UnitSupportTimesheet::create([
+ 'timesheet_no' => 'TS-ALEX-001',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'operator_id' => $this->empA->id,
+ 'date' => Carbon::today(),
+ 'shift' => '1',
+ 'meter_type' => 'hm',
+ 'start_meter' => 100,
+ 'end_meter' => 108,
+ 'operating_hours' => 8.0,
+ 'activity_type' => 'Operation',
+ 'location' => 'Incline Shaft Section 1',
+ 'task_description' => 'Mucking and clearing rocks',
+ 'status' => 'completed',
+ ]);
+
+ // Timesheet milik Operator B
+ UnitSupportTimesheet::create([
+ 'timesheet_no' => 'TS-BUDI-999',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'operator_id' => $this->empB->id,
+ 'date' => Carbon::today(),
+ 'shift' => '2',
+ 'meter_type' => 'hm',
+ 'start_meter' => 200,
+ 'end_meter' => 206,
+ 'operating_hours' => 6.0,
+ 'activity_type' => 'Operation',
+ 'location' => 'Powerhouse Cavern',
+ 'task_description' => 'Excavation trench',
+ 'status' => 'completed',
+ ]);
+
+ // Acting as User A
+ $responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'timesheet']));
+ $responseA->assertStatus(200);
+ $responseA->assertSee('TS-ALEX-001');
+ $responseA->assertSee('Incline Shaft Section 1');
+ $responseA->assertDontSee('TS-BUDI-999');
+ $responseA->assertDontSee('Powerhouse Cavern');
+
+ // Acting as User B
+ $responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'timesheet']));
+ $responseB->assertStatus(200);
+ $responseB->assertSee('TS-BUDI-999');
+ $responseB->assertSee('Powerhouse Cavern');
+ $responseB->assertDontSee('TS-ALEX-001');
+ }
+
+ public function test_employee_only_sees_their_own_vehicle_activity_trips(): void
+ {
+ // Trip milik Driver A
+ VehicleActivity::create([
+ 'transaction_no' => 'TRIP-ALEX-001',
+ 'vehicle_id' => $this->lightVehicle->id,
+ 'driver_id' => $this->empA->id,
+ 'gate_id' => $this->gate->id,
+ 'direction' => 'out',
+ 'previous_km' => 10000,
+ 'current_km' => 10035,
+ 'distance' => 35,
+ 'purpose' => 'Antar Logistik ke Camp Merangin Alex',
+ 'recorded_at' => Carbon::now(),
+ 'validation_status' => 'approved',
+ ]);
+
+ // Trip milik Driver B
+ VehicleActivity::create([
+ 'transaction_no' => 'TRIP-BUDI-999',
+ 'vehicle_id' => $this->lightVehicle->id,
+ 'driver_id' => $this->empB->id,
+ 'gate_id' => $this->gate->id,
+ 'direction' => 'in',
+ 'previous_km' => 20000,
+ 'current_km' => 20050,
+ 'distance' => 50,
+ 'purpose' => 'Patroli Jalur Pipa Budi',
+ 'recorded_at' => Carbon::now(),
+ 'validation_status' => 'approved',
+ ]);
+
+ // Acting as User A
+ $responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'trips']));
+ $responseA->assertStatus(200);
+ $responseA->assertSee('TRIP-ALEX-001');
+ $responseA->assertSee('Antar Logistik ke Camp Merangin Alex');
+ $responseA->assertDontSee('TRIP-BUDI-999');
+ $responseA->assertDontSee('Patroli Jalur Pipa Budi');
+
+ // Acting as User B
+ $responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'trips']));
+ $responseB->assertStatus(200);
+ $responseB->assertSee('TRIP-BUDI-999');
+ $responseB->assertSee('Patroli Jalur Pipa Budi');
+ $responseB->assertDontSee('TRIP-ALEX-001');
+ }
+
+ public function test_tabs_adapt_according_to_employee_permissions_and_records(): void
+ {
+ // User C: Hanya punya akses Timesheet LV, tidak punya P2H dan bukan operator
+ $userC = User::create([
+ 'name' => 'Driver Cici Test',
+ 'username' => 'driver_cici',
+ 'email' => 'cici@kerinci.local',
+ 'password' => Hash::make('password123'),
+ 'role' => 'employee',
+ ]);
+ $userC->syncRoles([]);
+ $userC->givePermissionTo(['employee.dashboard', 'employee.timesheet']);
+ $empC = $userC->getOrCreateEmployee();
+ $empC->update(['is_operator' => false]);
+
+ $response = $this->actingAs($userC)->get(route('employee.history'));
+ $response->assertStatus(200);
+ $response->assertSee('Mobilisasi');
+ $response->assertSee('Pos Gerbang');
+ $response->assertDontSee('P2H Heavy Equipment');
+ $response->assertDontSee('Timesheet Heavy Equipment');
+ }
+
+ public function test_employee_can_view_own_p2h_detail_and_pdf(): void
+ {
+ $recordA = P2hRecord::create([
+ 'transaction_no' => 'P2H-DETAIL-001',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'employee_id' => $this->empA->id,
+ 'template_id' => $this->template->id,
+ 'shift' => '1',
+ 'start_hm' => 1500,
+ 'summary_condition' => 'good',
+ 'defect_count' => 0,
+ 'validation_status' => 'approved',
+ 'inspected_at' => Carbon::now(),
+ ]);
+
+ P2hRecordItem::create([
+ 'p2h_record_id' => $recordA->id,
+ 'section' => 'Cabin Inspection',
+ 'title' => 'Kaca Spion & Wiper',
+ 'question_type' => 'choice',
+ 'condition_status' => 'baik',
+ ]);
+
+ // Detail JSON
+ $resJson = $this->actingAs($this->userA)->get(route('employee.history.p2h_detail', $recordA->id));
+ $resJson->assertStatus(200);
+ $resJson->assertJsonFragment([
+ 'transaction_no' => 'P2H-DETAIL-001',
+ 'item_name' => 'Kaca Spion & Wiper',
+ ]);
+
+ // PDF stream
+ $resPdf = $this->actingAs($this->userA)->get(route('employee.history.p2h_pdf', $recordA->id));
+ $resPdf->assertStatus(200);
+ $resPdf->assertHeader('Content-Type', 'application/pdf');
+ }
+
+ public function test_employee_cannot_view_or_download_pdf_of_other_employee_p2h(): void
+ {
+ // Record milik B
+ $recordB = P2hRecord::create([
+ 'transaction_no' => 'P2H-PRIVATE-BUDI',
+ 'vehicle_id' => $this->heavyEquipment->id,
+ 'employee_id' => $this->empB->id,
+ 'template_id' => $this->template->id,
+ 'shift' => '1',
+ 'start_hm' => 2000,
+ 'summary_condition' => 'good',
+ 'defect_count' => 0,
+ 'validation_status' => 'approved',
+ 'inspected_at' => Carbon::now(),
+ ]);
+
+ // User A mencoba melihat detail B -> 403 Forbidden
+ $resDetail = $this->actingAs($this->userA)->get(route('employee.history.p2h_detail', $recordB->id));
+ $resDetail->assertStatus(403);
+
+ // User A mencoba mengunduh PDF B -> 403 Forbidden
+ $resPdf = $this->actingAs($this->userA)->get(route('employee.history.p2h_pdf', $recordB->id));
+ $resPdf->assertStatus(403);
+ }
+}