Compare commits

...
10 Commits
Author SHA1 Message Date
Ray1111-aa 1e1286e3e2 security(core): patch driver IDOR, protect employee core role, harden XLSX parser, and fix timesheet concurrency race condition 2026-10-28 15:37:01 +07:00
Ray1111-aa 48678df82b fix(employee): strictly filter heavy equipment history tabs by active SIMPER scope (hide heavy tabs for LV-only drivers) 2026-10-28 15:07:27 +07:00
Ray1111-aa 2c959ca392 feat(employee): add personal activity history view with dynamic permission-based tabs, minimal icon design, and p2h detail modal 2026-10-28 14:58:54 +07:00
Ray1111-aa 315830c924 feat(p2h): add soft delete feature for p2h heavy equipment records with confirmation modal and trash support 2026-10-28 14:39:10 +07:00
Ray1111-aa 7675c3e500 fix(qma): clean up search input layout and remove cramped search button in heavy equipment timesheet 2026-10-28 14:26:35 +07:00
Ray1111-aa 68ff69e8e4 feat(timesheet): dynamically filter operators by equipment SIMPER in QMA heavy equipment timesheet 2026-10-28 14:18:47 +07:00
Ray1111-aa 852404be32 fix(trash): preserve photos during soft delete and only erase physical files on force delete 2026-10-28 13:47:44 +07:00
Ray1111-aa af61766546 feat(backup): expand backup upload validation limit to 1GB 2026-10-28 12:03:07 +07:00
Ray1111-aa 03af709a12 fix(backup): handle PostTooLargeException gracefully and add client-side file size guard 2026-10-28 11:59:42 +07:00
Ray1111-aa ee83b9d189 fix(ui): prevent button wrapping in backup header and align side-by-side 2026-10-28 11:49:31 +07:00
28 changed files with 2209 additions and 152 deletions
@@ -60,7 +60,35 @@ class BackupController extends Controller
$log->file_exists = File::exists($fullPath); $log->file_exists = File::exists($fullPath);
}); });
return view('admin.backups.index', compact('backupLogs', 'backups', 'stats', 'tableGroups')); // Ambil info batas upload server PHP saat ini
$uploadMax = ini_get('upload_max_filesize') ?: '256M';
$postMax = ini_get('post_max_size') ?: '256M';
$maxUploadBytes = min($this->parseIniBytes($uploadMax), $this->parseIniBytes($postMax));
$maxUploadHuman = $this->backupService->formatBytes($maxUploadBytes);
return view('admin.backups.index', compact('backupLogs', 'backups', 'stats', 'tableGroups', 'maxUploadBytes', 'maxUploadHuman'));
}
/**
* Konversi notasi string PHP INI (misal 256M, 1G) ke byte integer.
*/
protected function parseIniBytes(string $val): int
{
$val = trim($val);
$last = strtolower($val[strlen($val) - 1] ?? '');
$num = (int) $val;
switch ($last) {
case 'g':
$num *= 1024 * 1024 * 1024;
break;
case 'm':
$num *= 1024 * 1024;
break;
case 'k':
$num *= 1024;
break;
}
return $num > 0 ? $num : 268435456; // Fallback 256 MB
} }
/** /**
@@ -192,11 +220,11 @@ class BackupController extends Controller
} }
$request->validate([ $request->validate([
'backup_file' => ['required', 'file', 'max:204800'], // Maks. 200 MB 'backup_file' => ['required', 'file', 'max:1048576'], // Maks. 1024 MB (1 GB)
], [ ], [
'backup_file.required' => 'Pilih file backup yang ingin diunggah.', 'backup_file.required' => 'Pilih file backup yang ingin diunggah.',
'backup_file.file' => 'File yang diunggah tidak valid.', 'backup_file.file' => 'File yang diunggah tidak valid.',
'backup_file.max' => 'Ukuran file backup maksimal 200 MB.', 'backup_file.max' => 'Ukuran file backup maksimal 1 GB.',
]); ]);
$originalName = basename($file->getClientOriginalName()); $originalName = basename($file->getClientOriginalName());
@@ -101,7 +101,7 @@ class RolePermissionController extends Controller
$role = Role::findOrFail($roleId); $role = Role::findOrFail($roleId);
// Proteksi role inti sistem // Proteksi role inti sistem
$coreRoles = ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']; $coreRoles = ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'];
if (in_array($role->name, $coreRoles)) { if (in_array($role->name, $coreRoles)) {
return redirect()->route('admin.roles.index') return redirect()->route('admin.roles.index')
->with('error', "Aksi Ditolak: Role inti sistem [{$role->name}] tidak dapat dihapus."); ->with('error', "Aksi Ditolak: Role inti sistem [{$role->name}] tidak dapat dihapus.");
@@ -3,11 +3,16 @@
namespace App\Http\Controllers\Employee; namespace App\Http\Controllers\Employee;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\P2hRecord;
use App\Models\UnitSupportTimesheet;
use App\Models\Vehicle; use App\Models\Vehicle;
use App\Models\VehicleActivity; use App\Models\VehicleActivity;
use App\Services\P2hInspectionPdfExporter;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View; use Illuminate\View\View;
class DashboardController extends Controller class DashboardController extends Controller
@@ -201,4 +206,276 @@ class DashboardController extends Controller
'validated_at' => $activity->validated_at ? $activity->validated_at->format('H:i') . ' WIB' : null, '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. Cek riwayat aktual yang pernah dikerjakan oleh karyawan
$hasP2hRecords = $employee ? P2hRecord::where('employee_id', $employee->id)->exists() : false;
$hasTimesheetRecords = $employee ? UnitSupportTimesheet::where('operator_id', $employee->id)->exists() : false;
$hasTripRecords = $employee ? VehicleActivity::where('driver_id', $employee->id)->exists() : false;
// 2. Cek kualifikasi SIMPER karyawan terhadap jenis armada (Heavy Equipment vs Light Vehicle)
$canHeavy = $user->isSuperAdmin() || ($employee && $employee->canOperateHeavyEquipment());
$canLv = $user->isSuperAdmin() || ($employee && $employee->canDriveLightVehicle());
// 3. Modul P2H Heavy Equipment:
// Hanya tampil jika karyawan memiliki riwayat P2H ATAU (memiliki hak akses employee.p2h DAN izin SIMPER alat berat)
$canP2h = $hasP2hRecords || ($user->can('employee.p2h') && $canHeavy);
// 4. Modul Timesheet Heavy Equipment:
// Hanya tampil jika karyawan memiliki riwayat timesheet ATAU (memiliki izin SIMPER alat berat dan status operator)
$canTimesheet = $hasTimesheetRecords || ($canHeavy && ($employee?->is_operator || $user->can('qma.logs.view')));
// 5. Modul Perjalanan Pos Gerbang (LV):
// Tampil jika karyawan memiliki riwayat perjalanan ATAU (memiliki hak akses employee.timesheet dan SIMPER LV)
$canTrips = $hasTripRecords || ($user->can('employee.timesheet') && ($canLv || !$canHeavy));
// 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',
]);
}
} }
@@ -780,13 +780,11 @@ class EmployeeController extends Controller
$empNik = $employee->nik; $empNik = $employee->nik;
$photoPath = $employee->photo_path; $photoPath = $employee->photo_path;
DB::transaction(function () use ($employee, $photoPath) { DB::transaction(function () use ($employee) {
$user = $employee->user ?: User::where('username', $employee->nik)->first(); $user = $employee->user ?: User::where('username', $employee->nik)->first();
// Hapus berkas foto profil jika tersimpan secara lokal di storage // Berkas foto tidak dihapus saat soft delete agar foto tetap ada jika dipulihkan dari tong sampah.
if ($photoPath) { // Berkas baru dihapus permanen ketika dilakukan 'Hapus Permanen' (force delete) di TrashService.
ImageCompressionService::deleteIfExists($photoPath);
}
// Hapus data karyawan (relasi employee_simpers otomatis cascade terhapus) // Hapus data karyawan (relasi employee_simpers otomatis cascade terhapus)
$employee->delete(); $employee->delete();
@@ -163,18 +163,14 @@ class GateInspectionController extends Controller
$guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null); $guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null);
if (!$guardId) { if (!$guardId) {
$fallbackGuard = SecurityGuard::where('is_active', true)->first() ?? SecurityGuard::first();
if ($fallbackGuard) {
$guardId = $fallbackGuard->id;
} else {
$request->validate([ $request->validate([
'security_guard_id' => ['required', 'exists:security_guards,id'], 'security_guard_id' => ['required', 'exists:security_guards,id'],
], [ ], [
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam yang melakukan pemeriksaan.', 'security_guard_id.required' => 'Silakan pilih nama petugas Satpam yang melakukan pemeriksaan fisik.',
'security_guard_id.exists' => 'Petugas Satpam yang dipilih tidak valid dalam sistem.',
]); ]);
$guardId = $request->input('security_guard_id'); $guardId = $request->input('security_guard_id');
} }
}
$activity = VehicleActivity::with(['vehicle', 'gate'])->findOrFail($id); $activity = VehicleActivity::with(['vehicle', 'gate'])->findOrFail($id);
@@ -767,4 +767,20 @@ class P2hInspectionController extends Controller
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} DITOLAK. Status unit diubah ke Breakdown."); return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} DITOLAK. Status unit diubah ke Breakdown.");
} }
/**
* Hapus pemeriksaan P2H Heavy Equipment (Soft Delete).
* Data yang dihapus akan dipindahkan ke Tong Sampah dan dapat dipulihkan sewaktu-waktu.
*/
public function destroy(int $id): RedirectResponse
{
$record = P2hRecord::findOrFail($id);
$trxNo = $record->transaction_no;
// Cascade soft delete record items
$record->items()->delete();
$record->delete();
return redirect()->route('qma.p2h.index')->with('success', "Data pemeriksaan P2H [{$trxNo}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
}
} }
@@ -147,6 +147,7 @@ class SupportTimesheetController extends Controller
$q->whereNotNull('parent_id') $q->whereNotNull('parent_id')
->orWhereDoesntHave('units'); ->orWhereDoesntHave('units');
}) })
->with(['parent.requiredSimperType', 'requiredSimperType'])
->orderBy('code') ->orderBy('code')
->get(); ->get();
@@ -154,6 +155,18 @@ class SupportTimesheetController extends Controller
->orderBy('name') ->orderBy('name')
->get(['id', 'nik', 'name', 'position', 'is_operator', 'employee_type', 'simper_expired_at']); ->get(['id', 'nik', 'name', 'position', 'is_operator', 'employee_type', 'simper_expired_at']);
// Pemetaan kualifikasi SIMPER: Unit ID => Daftar Operator ID yang memiliki izin SIMPER sah
$unitOperatorsMap = [];
foreach ($unitSupports as $u) {
$eligibleIds = [];
foreach ($operators as $op) {
if ($op->hasValidSimperForVehicle($u)) {
$eligibleIds[] = $op->id;
}
}
$unitOperatorsMap[$u->id] = $eligibleIds;
}
$shifts = self::SHIFTS; $shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES; $activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions(); $locationSuggestions = UnitManagementController::getAllLocationSuggestions();
@@ -178,6 +191,7 @@ class SupportTimesheetController extends Controller
'breakdownCount', 'breakdownCount',
'unitSupports', 'unitSupports',
'operators', 'operators',
'unitOperatorsMap',
'shifts', 'shifts',
'activityTypes', 'activityTypes',
'locationSuggestions', 'locationSuggestions',
@@ -254,8 +268,15 @@ class SupportTimesheetController extends Controller
'activity_type.required' => 'Kategori pekerjaan wajib diisi.', 'activity_type.required' => 'Kategori pekerjaan wajib diisi.',
]); ]);
$vehicle = Vehicle::findOrFail($validated['vehicle_id']); $vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
$operator = Employee::findOrFail($validated['operator_id']); $operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
if (!$operator->hasValidSimperForVehicle($vehicle)) {
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
return back()
->withInput()
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
}
$startMeter = (float) $validated['start_meter']; $startMeter = (float) $validated['start_meter'];
$endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null $endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null
@@ -263,21 +284,23 @@ class SupportTimesheetController extends Controller
: null; : null;
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null; $operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang'; $shift = $validated['shift'] ?: 'Shift Siang';
$timesheetNo = UnitSupportTimesheet::generateTimesheetNo(Carbon::parse($validated['date']));
$updaterName = auth()->user()?->name ?? 'Admin QMA'; $updaterName = auth()->user()?->name ?? 'Admin QMA';
$timesheetNo = null;
DB::transaction(function () use ( DB::transaction(function () use (
$validated, $validated,
$vehicle, $vehicle,
$operator, $operator,
$timesheetNo,
$startMeter, $startMeter,
$endMeter, $endMeter,
$operatingHours, $operatingHours,
$shift, $shift,
$updaterName $updaterName,
&$timesheetNo
) { ) {
// Generate nomor timesheet unik di dalam transaksi untuk meminimalkan bentrokan
$timesheetNo = UnitSupportTimesheet::generateTimesheetNo(Carbon::parse($validated['date']));
// 1. Simpan Data Timesheet Heavy Equipment // 1. Simpan Data Timesheet Heavy Equipment
$timesheet = UnitSupportTimesheet::create([ $timesheet = UnitSupportTimesheet::create([
'timesheet_no' => $timesheetNo, 'timesheet_no' => $timesheetNo,
@@ -401,6 +424,18 @@ class SupportTimesheetController extends Controller
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null; $operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang'; $shift = $validated['shift'] ?: 'Shift Siang';
$vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
$operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
if ((int) $timesheet->operator_id !== (int) $operator->id || (int) $timesheet->vehicle_id !== (int) $vehicle->id) {
if (!$operator->hasValidSimperForVehicle($vehicle)) {
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
return back()
->withInput()
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
}
}
$timesheet->update([ $timesheet->update([
'vehicle_id' => $validated['vehicle_id'], 'vehicle_id' => $validated['vehicle_id'],
'operator_id' => $validated['operator_id'], 'operator_id' => $validated['operator_id'],
@@ -1187,12 +1187,9 @@ class VehicleController extends Controller
} }
} }
if ($vehicle->isSupportCategory()) { // Berkas fisik foto tidak dihapus di sini karena data masuk ke Tong Sampah (Soft Delete).
foreach ($vehicle->units as $u) { // Berkas foto akan tetap aman sehingga jika dipulihkan (restore), foto unit tetap ada.
ImageCompressionService::deleteIfExists($u->photo_path); // Berkas fisik baru dihapus permanen ketika dieksekusi 'Hapus Permanen' di TrashService.
}
}
ImageCompressionService::deleteIfExists($vehicle->photo_path);
$code = $vehicle->code; $code = $vehicle->code;
$vehicle->delete(); $vehicle->delete();
@@ -67,6 +67,20 @@ class StoreVehicleActivityRequest extends FormRequest
// 1. Validasi SIMPER Pengemudi (BR-01 & BR-02) // 1. Validasi SIMPER Pengemudi (BR-01 & BR-02)
$driver = Employee::find($this->input('driver_id')); $driver = Employee::find($this->input('driver_id'));
if ($driver) { if ($driver) {
// Proteksi IDOR: Karyawan biasa tidak boleh memalsukan perjalanan atas nama karyawan lain yang memiliki akun sendiri
$user = $this->user();
if ($user) {
$userEmployee = $user->getOrCreateEmployee();
$isStaffAdmin = $user->isSuperAdmin() || $user->isPgAdmin() || $user->isGateOfficer() || $user->isHseAdmin() || $user->isQmaAdmin();
if (!$isStaffAdmin && $userEmployee && $driver->id !== $userEmployee->id && !empty($driver->user_id) && $driver->user_id !== $user->id) {
$validator->errors()->add(
'driver_id',
"Akses Ditolak: Anda tidak diizinkan mencatatkan aktivitas kendaraan atas nama karyawan lain ({$driver->name}). Gunakan akun pribadi Anda."
);
return;
}
}
if (!$driver->is_operator) { if (!$driver->is_operator) {
$validator->errors()->add( $validator->errors()->add(
'driver_id', 'driver_id',
+109 -8
View File
@@ -140,11 +140,12 @@ class Employee extends Model
return $this->hasValidSimper(); return $this->hasValidSimper();
} }
// 1. Jika kendaraan mensyaratkan spesifik required_simper_type_id // 1. Jika kendaraan atau parent category kendaraan mensyaratkan spesifik required_simper_type_id
if ($vehicle->required_simper_type_id) { $requiredTypeId = $vehicle->required_simper_type_id ?? $vehicle->parent?->required_simper_type_id;
if ($requiredTypeId) {
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->get(); $simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->get();
foreach ($simpers as $s) { foreach ($simpers as $s) {
if ($s->simper_type_id === $vehicle->required_simper_type_id && $s->isValid()) { if ($s->simper_type_id === $requiredTypeId && $s->isValid()) {
return true; return true;
} }
} }
@@ -159,23 +160,45 @@ class Employee extends Model
} }
if ($vehicle->isUnitSupport()) { if ($vehicle->isUnitSupport()) {
$catName = $vehicle->unit_category ?: $vehicle->parent?->unit_category;
$brandName = $vehicle->brand_type ?: $vehicle->parent?->brand_type;
// Cek apakah personil memiliki izin SIMPER dengan scope kategori alat berat ini (misal: 'Dump Truck', 'Excavator', dll.) // Cek apakah personil memiliki izin SIMPER dengan scope kategori alat berat ini (misal: 'Dump Truck', 'Excavator', dll.)
if ($vehicle->unit_category && $this->hasValidSimperForScope($vehicle->unit_category)) { if ($catName && $this->hasValidSimperForScope($catName)) {
return true; return true;
} }
if ($vehicle->brand_type && $this->hasValidSimperForScope($vehicle->brand_type)) { if ($brandName && $this->hasValidSimperForScope($brandName)) {
return true; return true;
} }
if ($vehicle->is_timesheet_mobile) { // Cek jika brand type mengandung kategori spesifik yang dimiliki SIMPER personil
if ($brandName) {
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->with('simperType')->get();
foreach ($simpers as $s) {
if ($s->isValid() && $s->simperType) {
foreach ($s->simperType->scopes as $scope) {
if (!in_array($scope, [SimperType::SCOPE_ALL, SimperType::SCOPE_LIGHT_VEHICLE, SimperType::SCOPE_UNIT_SUPPORT_MOBILE, SimperType::SCOPE_UNIT_SUPPORT_HEAVY], true)) {
if (stripos($brandName, $scope) !== false) {
return true;
}
}
}
}
}
}
$isMobile = $vehicle->is_timesheet_mobile
|| ($vehicle->parent && $vehicle->parent->is_timesheet_mobile)
|| str_starts_with(strtoupper($vehicle->code), 'DT')
|| (stripos($catName ?? '', 'Dump Truck') !== false);
if ($isMobile) {
return $this->hasValidSimperForType('SIMPER-DT') return $this->hasValidSimperForType('SIMPER-DT')
|| $this->hasValidSimperForType('SIMPER-HEAVY')
|| $this->hasValidSimperForScope('unit_support_mobile') || $this->hasValidSimperForScope('unit_support_mobile')
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL); || $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
} }
return $this->hasValidSimperForType('SIMPER-HEAVY') return $this->hasValidSimperForType('SIMPER-HEAVY')
|| $this->hasValidSimperForType('SIMPER-DT')
|| $this->hasValidSimperForScope('unit_support_heavy') || $this->hasValidSimperForScope('unit_support_heavy')
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL); || $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
} }
@@ -183,6 +206,84 @@ class Employee extends Model
return $this->hasValidSimper(); return $this->hasValidSimper();
} }
/**
* Cek apakah personil memiliki izin SIMPER aktif yang mencakup Heavy Equipment / Unit Support (Alat Berat atau Dump Truck).
*/
public function canOperateHeavyEquipment(): bool
{
$hasAnySimper = $this->relationLoaded('simpers') ? $this->simpers->isNotEmpty() : $this->simpers()->exists();
if ($hasAnySimper) {
$simpers = $this->relationLoaded('simpers')
? $this->simpers
: $this->simpers()->with('simperType')->get();
foreach ($simpers as $s) {
if ($s->isValid() && $s->simperType) {
$type = $s->simperType;
// Cakupan Universal (Semua Armada)
if ($type->coversScope(SimperType::SCOPE_ALL)) {
return true;
}
// Cakupan Heavy Equipment atau Mobile Unit Support (Dump Truck)
if ($type->coversScope(SimperType::SCOPE_UNIT_SUPPORT_HEAVY)
|| $type->coversScope(SimperType::SCOPE_UNIT_SUPPORT_MOBILE)
|| $type->code === 'SIMPER-HEAVY'
|| $type->code === 'SIMPER-DT') {
return true;
}
// Cakupan kategori spesifik (Excavator, Bulldozer, Crane, dll.)
foreach ($type->scopes as $scope) {
if ($scope !== SimperType::SCOPE_LIGHT_VEHICLE && $scope !== 'light_vehicle') {
return true;
}
}
}
}
return false;
}
// Fallback untuk driver/operator legacy: jika belum multi-simper, hanya jika ditandai is_operator
// dan posisinya mengandung kata 'operator', 'heavy', 'excavator', 'dt', dsb.
if ($this->is_operator && $this->hasValidSimper()) {
$pos = strtolower($this->position ?? '');
if (str_contains($pos, 'operator') || str_contains($pos, 'alat berat') || str_contains($pos, 'excavator') || str_contains($pos, 'dt') || str_contains($pos, 'dump truck')) {
return true;
}
}
return false;
}
/**
* Cek apakah personil memiliki izin SIMPER aktif untuk kendaraan ringan (Light Vehicle).
*/
public function canDriveLightVehicle(): bool
{
$hasAnySimper = $this->relationLoaded('simpers') ? $this->simpers->isNotEmpty() : $this->simpers()->exists();
if ($hasAnySimper) {
$simpers = $this->relationLoaded('simpers')
? $this->simpers
: $this->simpers()->with('simperType')->get();
foreach ($simpers as $s) {
if ($s->isValid() && $s->simperType) {
if ($s->simperType->coversScope(SimperType::SCOPE_ALL)
|| $s->simperType->coversScope(SimperType::SCOPE_LIGHT_VEHICLE)
|| $s->simperType->code === 'SIMPER-LV') {
return true;
}
}
}
return false;
}
return $this->hasValidSimper();
}
public function getPhotoUrlAttribute(): ?string public function getPhotoUrlAttribute(): ?string
{ {
$path = $this->photo_path; $path = $this->photo_path;
+12 -2
View File
@@ -62,6 +62,7 @@ class UnitSupportTimesheet extends Model
/** /**
* Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001). * Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001).
* Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records.
*/ */
public static function generateTimesheetNo(?Carbon $date = null): string public static function generateTimesheetNo(?Carbon $date = null): string
{ {
@@ -69,7 +70,8 @@ class UnitSupportTimesheet extends Model
$dateStr = $d->format('Ymd'); $dateStr = $d->format('Ymd');
$prefix = "TS-US-{$dateStr}-"; $prefix = "TS-US-{$dateStr}-";
$last = self::where('timesheet_no', 'like', "{$prefix}%") $last = self::withTrashed()
->where('timesheet_no', 'like', "{$prefix}%")
->orderByDesc('id') ->orderByDesc('id')
->first(); ->first();
@@ -78,6 +80,14 @@ class UnitSupportTimesheet extends Model
$seq = ((int) $matches[1]) + 1; $seq = ((int) $matches[1]) + 1;
} }
return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT); $candidate = $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
// Mitigasi bentrokan concurrency: cek apakah candidate sudah pernah digunakan (termasuk soft deletes)
while (self::withTrashed()->where('timesheet_no', $candidate)->exists()) {
$seq++;
$candidate = $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
}
return $candidate;
} }
} }
+2 -2
View File
@@ -87,7 +87,7 @@ class SimpleXlsxImporter
$sharedStrings = []; $sharedStrings = [];
$sharedXmlContent = $zip->getFromName('xl/sharedStrings.xml'); $sharedXmlContent = $zip->getFromName('xl/sharedStrings.xml');
if ($sharedXmlContent) { if ($sharedXmlContent) {
$xml = @simplexml_load_string($sharedXmlContent); $xml = @simplexml_load_string($sharedXmlContent, 'SimpleXMLElement', LIBXML_NONET);
if ($xml && isset($xml->si)) { if ($xml && isset($xml->si)) {
foreach ($xml->si as $si) { foreach ($xml->si as $si) {
if (isset($si->t)) { if (isset($si->t)) {
@@ -112,7 +112,7 @@ class SimpleXlsxImporter
return $rows; return $rows;
} }
$xml = @simplexml_load_string($sheetXmlContent); $xml = @simplexml_load_string($sheetXmlContent, 'SimpleXMLElement', LIBXML_NONET);
$zip->close(); $zip->close();
if (!$xml || !isset($xml->sheetData->row)) { if (!$xml || !isset($xml->sheetData->row)) {
+19
View File
@@ -17,6 +17,7 @@ use App\Models\UnitTransfer;
use App\Models\User; use App\Models\User;
use App\Models\Vehicle; use App\Models\Vehicle;
use App\Models\VehicleActivity; use App\Models\VehicleActivity;
use App\Services\ImageCompressionService;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -432,6 +433,24 @@ class TrashService
->forceDelete(); ->forceDelete();
} }
// Hapus berkas fisik saat benar-benar dihapus permanen dari tong sampah
if ($item instanceof Vehicle) {
ImageCompressionService::deleteIfExists($item->photo_path);
if (method_exists($item, 'isSupportCategory') && $item->isSupportCategory()) {
foreach ($item->units as $u) {
ImageCompressionService::deleteIfExists($u->photo_path);
}
}
}
if ($item instanceof Employee) {
ImageCompressionService::deleteIfExists($item->photo_path);
}
if ($item instanceof User) {
ImageCompressionService::deleteIfExists($item->photo_path ?? null);
}
$item->forceDelete(); $item->forceDelete();
}); });
+5 -1
View File
@@ -18,5 +18,9 @@ return Application::configure(basePath: dirname(__DIR__))
]); ]);
}) })
->withExceptions(function (Exceptions $exceptions): void { ->withExceptions(function (Exceptions $exceptions): void {
// $exceptions->render(function (\Illuminate\Http\Exceptions\PostTooLargeException $e, $request) {
$postMax = ini_get('post_max_size') ?: '256M';
$uploadMax = ini_get('upload_max_filesize') ?: '256M';
return back()->with('error', "Ukuran file yang Anda kirim terlalu besar dan melebihi batas konfigurasi server PHP (post_max_size: {$postMax}, upload_max_filesize: {$uploadMax}). Harap naikkan batas konfigurasi php.ini atau gunakan file yang lebih kecil.");
});
})->create(); })->create();
+14 -6
View File
@@ -5,8 +5,8 @@
@section('content') @section('content')
<div class="space-y-6"> <div class="space-y-6">
<!-- Header Halaman (Clean Minimalist) --> <!-- Header Halaman (Clean Minimalist) -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-2 border-b border-slate-100"> <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 pb-4 border-b border-slate-100">
<div> <div class="min-w-0 flex-1">
<h1 class="text-xl font-bold text-slate-900 tracking-tight"> <h1 class="text-xl font-bold text-slate-900 tracking-tight">
Backup &amp; Restore Sistem Backup &amp; Restore Sistem
</h1> </h1>
@@ -14,15 +14,15 @@
Pencadangan terenkripsi berformat <code>.kmh</code> khusus untuk sistem RKM-KMH. Langsung unduh ke komputer lokal dan hemat kapasitas disk VPS server. Pencadangan terenkripsi berformat <code>.kmh</code> khusus untuk sistem RKM-KMH. Langsung unduh ke komputer lokal dan hemat kapasitas disk VPS server.
</p> </p>
</div> </div>
<div class="flex flex-wrap items-center gap-2"> <div class="flex items-center gap-2.5 shrink-0 self-start md:self-auto">
<button type="button" <button type="button"
onclick="openDirectRestoreModal()" onclick="openDirectRestoreModal()"
class="px-3.5 py-2 rounded-xl border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 text-xs font-semibold transition shadow-2xs"> class="whitespace-nowrap px-4 py-2.5 rounded-xl border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 text-xs font-semibold transition shadow-2xs inline-flex items-center gap-1.5">
Pulihkan dari File .kmh Pulihkan dari File .kmh
</button> </button>
<button type="button" <button type="button"
onclick="openCreateBackupModal()" onclick="openCreateBackupModal()"
class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs"> class="whitespace-nowrap px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs inline-flex items-center gap-1.5">
Buat Backup Baru Buat Backup Baru
</button> </button>
</div> </div>
@@ -444,7 +444,7 @@
</div> </div>
<p class="text-xs font-bold text-slate-800" id="directRestoreFileName">Tarik &amp; Letakkan file .kmh di sini</p> <p class="text-xs font-bold text-slate-800" id="directRestoreFileName">Tarik &amp; Letakkan file .kmh di sini</p>
<p class="text-[11px] text-slate-400 mt-1">atau <span class="text-amber-700 font-semibold underline">klik untuk memilih dari komputer Anda</span></p> <p class="text-[11px] text-slate-400 mt-1">atau <span class="text-amber-700 font-semibold underline">klik untuk memilih dari komputer Anda</span></p>
<p class="text-[10px] text-slate-400 mt-1.5">Format didukung: .kmh terenkripsi (Maks. 200 MB)</p> <p class="text-[10px] text-slate-400 mt-1.5">Format didukung: .kmh terenkripsi (Batas upload server: {{ $maxUploadHuman ?? '256 MB' }})</p>
</div> </div>
<div id="directRestoreFileDisplay" class="hidden mt-1 p-3 rounded-xl bg-amber-50 border border-amber-200 text-left"> <div id="directRestoreFileDisplay" class="hidden mt-1 p-3 rounded-xl bg-amber-50 border border-amber-200 text-left">
@@ -752,6 +752,14 @@
function handleDirectRestoreFileChange(input) { function handleDirectRestoreFileChange(input) {
if (input.files && input.files[0]) { if (input.files && input.files[0]) {
const file = input.files[0]; const file = input.files[0];
const maxBytes = {{ $maxUploadBytes ?? 268435456 }};
if (file.size > maxBytes) {
const fileMb = (file.size / (1024 * 1024)).toFixed(1);
const limitMb = (maxBytes / (1024 * 1024)).toFixed(0);
alert(`Peringatan: Ukuran file (${fileMb} MB) melebihi batas upload PHP server (${limitMb} MB). Mohon sesuaikan pengaturan php.ini server Anda.`);
input.value = '';
return;
}
const sizeHuman = (file.size / (1024 * 1024)).toFixed(2) + ' MB'; const sizeHuman = (file.size / (1024 * 1024)).toFixed(2) + ' MB';
document.getElementById('directRestorePillName').textContent = file.name; document.getElementById('directRestorePillName').textContent = file.name;
document.getElementById('directRestorePillSize').textContent = sizeHuman; document.getElementById('directRestorePillSize').textContent = sizeHuman;
+13 -1
View File
@@ -312,9 +312,16 @@
<p class="text-xs text-slate-500">Catatan mobilisasi kendaraan yang pernah Anda isi di sistem.</p> <p class="text-xs text-slate-500">Catatan mobilisasi kendaraan yang pernah Anda isi di sistem.</p>
</div> </div>
</div> </div>
<span class="text-xs font-semibold text-slate-400 self-start sm:self-center"> <div class="flex items-center gap-3 self-start sm:self-center">
<span class="text-xs font-semibold text-slate-400">
{{ $myRecentActivities->count() }} Perjalanan Terbaru {{ $myRecentActivities->count() }} Perjalanan Terbaru
</span> </span>
<a href="{{ route('employee.history') }}"
class="inline-flex items-center text-xs font-bold text-[#1b5e20] hover:underline">
<span>Lihat Seluruh Riwayat</span>
<i class="fa-solid fa-arrow-right text-[10px] ml-1"></i>
</a>
</div>
</div> </div>
<div class="overflow-x-auto -mx-5 sm:mx-0"> <div class="overflow-x-auto -mx-5 sm:mx-0">
@@ -411,6 +418,11 @@
<p class="text-[11px] text-slate-400 mt-1 max-w-sm mx-auto"> <p class="text-[11px] text-slate-400 mt-1 max-w-sm mx-auto">
Catatan mobilisasi unit kendaraan ringan (LV) yang Anda kendarai akan otomatis muncul di sini setelah Anda mengisi formulir perjalanan. Catatan mobilisasi unit kendaraan ringan (LV) yang Anda kendarai akan otomatis muncul di sini setelah Anda mengisi formulir perjalanan.
</p> </p>
<div class="mt-3">
<a href="{{ route('employee.history') }}" class="text-xs font-bold text-[#1b5e20] hover:underline">
Buka Halaman Riwayat Saya &rarr;
</a>
</div>
</div> </div>
@endif @endif
</div> </div>
+637
View File
@@ -0,0 +1,637 @@
@extends('layouts.app')
@section('title', 'Riwayat Aktivitas - Sistem RKM | PT Kerinci Merangin Hidro')
@section('content')
<div class="w-full space-y-6">
<!-- Header Halaman Bersih & Minimalis -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-200">
<div>
<div class="flex items-center space-x-2 text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">
<span>Portal Karyawan</span>
<span>&bull;</span>
<span class="text-[#1b5e20] font-bold">Catatan Operasional</span>
</div>
<h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
Riwayat Aktivitas Saya
</h1>
<p class="text-xs sm:text-sm text-slate-500 mt-1">
Rekap seluruh aktivitas pemeriksaan kelaikan P2H, timesheet alat berat, dan mobilisasi kendaraan Anda.
</p>
</div>
<div class="flex items-center gap-2 self-start sm:self-center">
<a href="{{ route('employee.dashboard') }}"
class="px-3.5 py-2 text-xs font-bold text-slate-700 bg-white border border-slate-300 rounded-xl hover:bg-slate-50 transition shadow-2xs">
&larr; Kembali ke Dashboard
</a>
</div>
</div>
<!-- Ringkasan KPI Pribadi Karyawan (Tanpa Ikon Berlebih, Tipografi Bersih) -->
<div class="grid grid-cols-1 {{ ($canP2h && $canTimesheet && $canTrips) ? 'sm:grid-cols-3' : (($canP2h || $canTimesheet) && ($canTrips || ($canP2h && $canTimesheet)) ? 'sm:grid-cols-2' : 'sm:grid-cols-1') }} gap-4">
@if($canP2h)
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">P2H Heavy Equipment</p>
<div class="mt-2 flex items-baseline justify-between">
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['p2h_total']) }}</span>
<span class="text-xs font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
{{ $stats['p2h_good'] }} Layak
</span>
</div>
<p class="text-xs text-slate-500 mt-2">
{{ $stats['p2h_defects'] }} catatan memiliki temuan kerusakan
</p>
</div>
@endif
@if($canTimesheet)
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Timesheet Alat Berat</p>
<div class="mt-2 flex items-baseline justify-between">
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['timesheet_hours'], 1, ',', '.') }} Jam</span>
<span class="text-xs font-semibold text-slate-700 bg-slate-100 px-2 py-0.5 rounded border border-slate-200">
{{ number_format($stats['timesheet_total']) }} Sesi
</span>
</div>
<p class="text-xs text-slate-500 mt-2">
Total akumulasi jam operasi alat berat
</p>
</div>
@endif
@if($canTrips)
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Perjalanan Gerbang (LV)</p>
<div class="mt-2 flex items-baseline justify-between">
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['trip_distance'], 0, ',', '.') }} KM</span>
<span class="text-xs font-semibold text-blue-700 bg-blue-50 px-2 py-0.5 rounded border border-blue-200">
{{ number_format($stats['trip_total']) }} Trip
</span>
</div>
<p class="text-xs text-slate-500 mt-2">
Jarak kumulatif mobilisasi kendaraan dinas
</p>
</div>
@endif
</div>
<!-- Tab Navigasi Dinamis Berdasarkan Hak Akses & Riwayat -->
<div class="bg-white border border-slate-200 rounded-2xl shadow-2xs overflow-hidden">
<!-- Header Tab -->
<div class="border-b border-slate-200 px-5 pt-3 bg-slate-50/50">
<div class="flex space-x-6 overflow-x-auto no-scrollbar">
@if($canP2h)
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'p2h'])) }}"
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'p2h' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
<span>P2H Heavy Equipment</span>
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'p2h' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
{{ $p2hCount }}
</span>
</a>
@endif
@if($canTimesheet)
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'timesheet'])) }}"
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'timesheet' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
<span>Timesheet Heavy Equipment</span>
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'timesheet' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
{{ $timesheetCount }}
</span>
</a>
@endif
@if($canTrips)
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'trips'])) }}"
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'trips' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
<span>Mobilisasi & Pos Gerbang (LV)</span>
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'trips' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
{{ $tripCount }}
</span>
</a>
@endif
</div>
</div>
<!-- Filter Bar Bersih -->
<div class="p-5 border-b border-slate-100 bg-white">
<form method="GET" action="{{ route('employee.history') }}" class="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-3">
<input type="hidden" name="tab" value="{{ $activeTab }}">
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2.5 flex-1">
<!-- Kata Kunci Pencarian -->
<div class="sm:col-span-2 md:col-span-1">
<input type="text"
name="search"
value="{{ $search }}"
placeholder="Cari transaksi, kode unit..."
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition">
</div>
<!-- Dari Tanggal -->
<div>
<input type="date"
name="date_from"
value="{{ $dateFrom }}"
title="Dari Tanggal"
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
</div>
<!-- Sampai Tanggal -->
<div>
<input type="date"
name="date_to"
value="{{ $dateTo }}"
title="Sampai Tanggal"
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
</div>
<!-- Filter Status Sesuai Tab Aktif -->
<div>
<select name="status" class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
<option value="">Semua Status</option>
@if($activeTab === 'p2h')
<option value="pending" {{ $status === 'pending' ? 'selected' : '' }}>Menunggu Approval QMA</option>
<option value="approved" {{ $status === 'approved' ? 'selected' : '' }}>Disetujui</option>
<option value="rejected" {{ $status === 'rejected' ? 'selected' : '' }}>Ditolak</option>
<option value="good" {{ $status === 'good' ? 'selected' : '' }}>Kondisi: Layak Jalan</option>
<option value="has_defect" {{ $status === 'has_defect' ? 'selected' : '' }}>Kondisi: Ada Temuan</option>
@elseif($activeTab === 'timesheet')
<option value="completed" {{ $status === 'completed' ? 'selected' : '' }}>Selesai</option>
<option value="running" {{ $status === 'running' ? 'selected' : '' }}>Sedang Berjalan</option>
@elseif($activeTab === 'trips')
<option value="approved" {{ $status === 'approved' ? 'selected' : '' }}>Disetujui Satpam</option>
<option value="pending" {{ $status === 'pending' ? 'selected' : '' }}>Menunggu Validasi</option>
<option value="rejected" {{ $status === 'rejected' ? 'selected' : '' }}>Ditolak Satpam</option>
<option value="cancelled" {{ $status === 'cancelled' ? 'selected' : '' }}>Dibatalkan</option>
@endif
</select>
</div>
</div>
<!-- Tombol Filter & Reset -->
<div class="flex items-center gap-2 flex-shrink-0">
<button type="submit"
class="px-4 py-2 bg-[#1b5e20] hover:bg-[#144918] text-white font-bold text-xs rounded-xl shadow-2xs transition">
Terapkan Filter
</button>
@if($search || $dateFrom || $dateTo || $status)
<a href="{{ route('employee.history', ['tab' => $activeTab]) }}"
class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-semibold rounded-xl transition">
Reset
</a>
@endif
</div>
</form>
</div>
<!-- ========================================================== -->
<!-- TAB 1: RIWAYAT P2H HEAVY EQUIPMENT -->
<!-- ========================================================== -->
@if($activeTab === 'p2h')
@if(isset($p2hRecords) && $p2hRecords->isNotEmpty())
<div class="overflow-x-auto">
<table class="w-full text-xs text-left min-w-[760px]">
<thead>
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
<th class="py-3 px-4">Waktu Inspeksi</th>
<th class="py-3 px-4">No. Transaksi</th>
<th class="py-3 px-4">Unit Alat Berat</th>
<th class="py-3 px-4">Shift & Odometer</th>
<th class="py-3 px-4 text-center">Kelaikan Operasi</th>
<th class="py-3 px-4 text-center">Status QMA</th>
<th class="py-3 px-4 text-right">Aksi</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700">
@foreach($p2hRecords as $rec)
<tr class="hover:bg-slate-50/60 transition">
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-slate-900 block">{{ $rec->inspected_at ? $rec->inspected_at->format('d/m/Y') : '-' }}</span>
<span class="text-[11px] text-slate-400 block">{{ $rec->inspected_at ? $rec->inspected_at->format('H:i') . ' WIB' : '-' }}</span>
</td>
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
{{ $rec->transaction_no }}
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $rec->vehicle->code ?? '-' }}</span>
<span class="text-[11px] text-slate-500 block truncate max-w-[160px]">{{ $rec->vehicle->brand_type ?? '-' }}</span>
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-medium text-slate-800 block">Shift {{ $rec->shift }}</span>
<span class="text-[11px] font-mono text-slate-500 block">HM: {{ number_format($rec->start_hm, 1) }}</span>
</td>
<td class="py-3 px-4 text-center whitespace-nowrap">
@if($rec->summary_condition === 'good')
<span class="inline-block px-2.5 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
Layak Jalan
</span>
@else
<span class="inline-block px-2.5 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200" title="{{ $rec->defect_count }} temuan kerusakan">
Ada Temuan ({{ $rec->defect_count }})
</span>
@endif
</td>
<td class="py-3 px-4 text-center whitespace-nowrap">
@if($rec->validation_status === 'approved')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200" title="Disetujui oleh: {{ $rec->validator->name ?? 'Admin QMA' }}">
Disetujui
</span>
@elseif($rec->validation_status === 'rejected')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-rose-50 text-rose-700 border border-rose-200" title="Alasan: {{ $rec->validation_notes }}">
Ditolak
</span>
@else
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
Menunggu QMA
</span>
@endif
</td>
<td class="py-3 px-4 text-right whitespace-nowrap space-x-1">
<button type="button"
onclick="viewP2hDetail({{ $rec->id }})"
class="px-2.5 py-1 text-[11px] font-semibold text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition cursor-pointer">
Detail
</button>
<a href="{{ route('employee.history.p2h_pdf', $rec->id) }}"
target="_blank"
class="px-2.5 py-1 text-[11px] font-semibold text-rose-700 bg-rose-50 border border-rose-200 rounded-lg hover:bg-rose-100 transition">
PDF
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Pagination Links -->
<div class="p-4 border-t border-slate-100 bg-white">
{{ $p2hRecords->links() }}
</div>
@else
<div class="py-12 px-4 text-center">
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat P2H Heavy Equipment</p>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
Data pemeriksaan kelaikan unit yang pernah Anda kerjakan akan otomatis tampil di tabel ini.
</p>
@can('employee.p2h')
<div class="mt-4">
<a href="{{ route('p2h.index') }}" class="px-4 py-2 bg-[#1b5e20] text-white text-xs font-bold rounded-xl hover:bg-[#144918] transition inline-block">
Mulai Pemeriksaan P2H Sekarang
</a>
</div>
@endcan
</div>
@endif
<!-- ========================================================== -->
<!-- TAB 2: RIWAYAT TIMESHEET ALAT BERAT -->
<!-- ========================================================== -->
@elseif($activeTab === 'timesheet')
@if(isset($timesheetRecords) && $timesheetRecords->isNotEmpty())
<div class="overflow-x-auto">
<table class="w-full text-xs text-left min-w-[760px]">
<thead>
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
<th class="py-3 px-4">Tanggal & Shift</th>
<th class="py-3 px-4">No. Timesheet</th>
<th class="py-3 px-4">Unit Alat Berat</th>
<th class="py-3 px-4 text-right">Odometer (HM / KM)</th>
<th class="py-3 px-4 text-right">Jam Operasi</th>
<th class="py-3 px-4">Lokasi & Aktivitas</th>
<th class="py-3 px-4 text-center">Status</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700">
@foreach($timesheetRecords as $ts)
<tr class="hover:bg-slate-50/60 transition">
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-slate-900 block">{{ $ts->date ? $ts->date->format('d/m/Y') : '-' }}</span>
<span class="text-[11px] text-slate-500 block font-medium">Shift {{ $ts->shift }}</span>
</td>
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
{{ $ts->timesheet_no }}
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $ts->vehicle->code ?? '-' }}</span>
<span class="text-[11px] text-slate-500 block truncate max-w-[150px]">{{ $ts->vehicle->brand_type ?? '-' }}</span>
</td>
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
<span class="text-slate-900 font-semibold block">{{ number_format($ts->start_meter, 1) }} &rarr; {{ number_format($ts->end_meter, 1) }}</span>
<span class="text-[10px] text-slate-400 block">{{ strtoupper($ts->meter_type ?? 'HM') }}</span>
</td>
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
<span class="font-bold text-slate-900 block">{{ number_format($ts->operating_hours, 1) }} Jam</span>
@if($ts->standby_hours > 0 || $ts->breakdown_hours > 0)
<span class="text-[10px] text-slate-400 block">
Stb: {{ number_format($ts->standby_hours, 1) }} | BD: {{ number_format($ts->breakdown_hours, 1) }}
</span>
@endif
</td>
<td class="py-3 px-4">
<span class="font-bold text-slate-800 block truncate max-w-[180px]">{{ $ts->location ?? '-' }}</span>
<span class="text-[11px] text-slate-500 block truncate max-w-[200px]">{{ $ts->task_description ?? '-' }}</span>
</td>
<td class="py-3 px-4 text-center whitespace-nowrap">
@if($ts->status === 'completed')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
Selesai
</span>
@else
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200">
Berjalan
</span>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Pagination Links -->
<div class="p-4 border-t border-slate-100 bg-white">
{{ $timesheetRecords->links() }}
</div>
@else
<div class="py-12 px-4 text-center">
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat Timesheet Alat Berat</p>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
Data jam kerja dan catatan operasional operator heavy equipment akan tampil di sini setelah dicatat.
</p>
</div>
@endif
<!-- ========================================================== -->
<!-- TAB 3: RIWAYAT MOBILISASI & POS GERBANG (LV) -->
<!-- ========================================================== -->
@elseif($activeTab === 'trips')
@if(isset($tripRecords) && $tripRecords->isNotEmpty())
<div class="overflow-x-auto">
<table class="w-full text-xs text-left min-w-[760px]">
<thead>
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
<th class="py-3 px-4">Waktu</th>
<th class="py-3 px-4">No. Transaksi</th>
<th class="py-3 px-4">Unit Kendaraan</th>
<th class="py-3 px-4">Pos Gerbang & Arah</th>
<th class="py-3 px-4 text-right">Odometer & Jarak</th>
<th class="py-3 px-4">Keperluan</th>
<th class="py-3 px-4 text-center">Status Satpam</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700">
@foreach($tripRecords as $act)
<tr class="hover:bg-slate-50/60 transition">
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-slate-900 block">{{ $act->recorded_at ? $act->recorded_at->format('d/m/Y') : '-' }}</span>
<span class="text-[11px] text-slate-400 block">{{ $act->recorded_at ? $act->recorded_at->format('H:i') . ' WIB' : '-' }}</span>
</td>
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
{{ $act->transaction_no }}
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $act->vehicle->code ?? '-' }}</span>
<span class="text-[11px] text-slate-500 block truncate max-w-[160px]">
{{ $act->vehicle->brand_type ?? '-' }} &bull; {{ $act->vehicle->license_plate ?? 'Tanpa Plat' }}
</span>
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span class="font-bold text-slate-800 block">{{ $act->gate->name ?? 'Pos Gerbang' }}</span>
@if($act->direction === 'in')
<span class="inline-block mt-0.5 px-1.5 py-0.2 rounded text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
MASUK
</span>
@else
<span class="inline-block mt-0.5 px-1.5 py-0.2 rounded text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200">
KELUAR
</span>
@endif
</td>
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
<span class="font-bold text-slate-900 block">{{ number_format($act->current_km, 0, ',', '.') }} KM</span>
<span class="text-[11px] text-emerald-700 font-semibold block">+{{ number_format($act->distance, 0, ',', '.') }} KM</span>
</td>
<td class="py-3 px-4">
<span class="text-slate-700 block truncate max-w-[180px]" title="{{ $act->purpose }}">
{{ $act->purpose ?: '-' }}
</span>
</td>
<td class="py-3 px-4 text-center whitespace-nowrap">
@if($act->validation_status === 'approved')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200" title="Divalidasi oleh: {{ $act->securityGuard->name ?? 'Satpam' }}">
Disetujui
</span>
@elseif($act->validation_status === 'cancelled')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-slate-100 text-slate-700 border border-slate-200" title="{{ $act->rejection_note }}">
Dibatalkan
</span>
@elseif($act->validation_status === 'rejected')
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-rose-50 text-rose-700 border border-rose-200" title="Alasan: {{ $act->rejection_note }}">
Ditolak
</span>
@else
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
Menunggu Satpam
</span>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Pagination Links -->
<div class="p-4 border-t border-slate-100 bg-white">
{{ $tripRecords->links() }}
</div>
@else
<div class="py-12 px-4 text-center">
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat Perjalanan Pos Gerbang</p>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
Catatan mobilisasi kendaraan ringan (LV) Anda yang melewati pos penjagaan satpam akan dicatat di sini.
</p>
</div>
@endif
@else
<div class="py-12 px-4 text-center">
<p class="text-sm font-bold text-slate-700">Tidak Ada Modul Riwayat yang Tersedia</p>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
Akun Anda saat ini belum memiliki hak akses operasional yang aktif.
</p>
</div>
@endif
</div>
</div>
<!-- ========================================================== -->
<!-- MODAL DETAIL INSPEKSI P2H (DESAIN BERSIH TANPA IKON BERLEBIH) -->
<!-- ========================================================== -->
<div id="p2hDetailModal" class="fixed inset-0 z-50 hidden overflow-y-auto bg-slate-900/40 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-2xl shadow-xl border border-slate-200 w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh]">
<!-- Modal Header -->
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
<div>
<h3 class="text-base font-bold text-slate-900" id="modalTrxNo">Detail Lembar P2H</h3>
<p class="text-xs text-slate-500 mt-0.5" id="modalSubTitle">Hasil pemeriksaan kelaikan unit alat berat</p>
</div>
<button type="button"
onclick="closeP2hDetailModal()"
class="text-slate-400 hover:text-slate-700 text-lg font-bold p-1 cursor-pointer">
&times;
</button>
</div>
<!-- Modal Body Scrollable -->
<div class="p-6 overflow-y-auto space-y-4 text-xs">
<!-- Metadata Grid -->
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3 p-3 bg-slate-50 rounded-xl border border-slate-100">
<div>
<span class="text-[10px] text-slate-400 uppercase font-bold block">Unit Alat Berat</span>
<span class="font-bold text-[#1b5e20] text-xs font-mono" id="modalUnitCode">-</span>
<span class="text-[11px] text-slate-600 block truncate" id="modalUnitName">-</span>
</div>
<div>
<span class="text-[10px] text-slate-400 uppercase font-bold block">Shift & Odometer</span>
<span class="font-bold text-slate-800 text-xs block" id="modalShift">-</span>
<span class="text-[11px] font-mono text-slate-600 block" id="modalHm">-</span>
</div>
<div>
<span class="text-[10px] text-slate-400 uppercase font-bold block">Waktu Inspeksi</span>
<span class="font-semibold text-slate-800 text-xs block" id="modalTime">-</span>
</div>
<div>
<span class="text-[10px] text-slate-400 uppercase font-bold block">Status Approval</span>
<span class="inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded" id="modalStatusBadge">-</span>
</div>
</div>
<!-- Catatan Umum -->
<div id="modalGeneralNotesContainer" class="p-3 bg-amber-50/60 rounded-xl border border-amber-200/60 hidden">
<span class="text-[11px] font-bold text-amber-900 block mb-0.5">Catatan Operator:</span>
<p class="text-xs text-amber-800" id="modalGeneralNotes"></p>
</div>
<!-- Tabel Checklist Items -->
<div>
<p class="font-bold text-slate-800 mb-2 uppercase text-[10px] tracking-wider text-slate-400">Daftar Pemeriksaan Komponen:</p>
<div class="border border-slate-200 rounded-xl overflow-hidden">
<table class="w-full text-left text-xs">
<thead>
<tr class="bg-slate-50 text-slate-600 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
<th class="py-2.5 px-3">Bagian</th>
<th class="py-2.5 px-3">Komponen / Item</th>
<th class="py-2.5 px-3 text-center">Kondisi</th>
<th class="py-2.5 px-3">Catatan Temuan</th>
</tr>
</thead>
<tbody id="modalItemsTableBody" class="divide-y divide-slate-100">
<!-- Injected via JavaScript -->
</tbody>
</table>
</div>
</div>
</div>
<!-- Modal Footer -->
<div class="px-6 py-3 border-t border-slate-100 bg-slate-50/50 flex items-center justify-between">
<a id="modalDownloadPdfBtn" href="#" target="_blank" class="px-3.5 py-1.5 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl transition shadow-2xs">
Cetak Lembar PDF
</a>
<button type="button"
onclick="closeP2hDetailModal()"
class="px-4 py-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-semibold rounded-xl transition cursor-pointer">
Tutup
</button>
</div>
</div>
</div>
<script>
function viewP2hDetail(recordId) {
const modal = document.getElementById('p2hDetailModal');
const pdfBtn = document.getElementById('modalDownloadPdfBtn');
const tableBody = document.getElementById('modalItemsTableBody');
pdfBtn.href = "{{ url('/karyawan/riwayat/p2h') }}/" + recordId + "/pdf";
tableBody.innerHTML = '<tr><td colspan="4" class="py-4 text-center text-slate-400">Memuat data...</td></tr>';
modal.classList.remove('hidden');
fetch("{{ url('/karyawan/riwayat/p2h') }}/" + recordId)
.then(res => {
if (!res.ok) throw new Error('Gagal memuat detail data.');
return res.json();
})
.then(data => {
document.getElementById('modalTrxNo').textContent = 'P2H: ' + data.transaction_no;
document.getElementById('modalSubTitle').textContent = data.template_name;
document.getElementById('modalUnitCode').textContent = data.vehicle_code;
document.getElementById('modalUnitName').textContent = data.vehicle_name;
document.getElementById('modalShift').textContent = 'Shift ' + data.shift;
document.getElementById('modalHm').textContent = 'HM: ' + (data.start_hm || '0');
document.getElementById('modalTime').textContent = data.inspected_at || '-';
const badge = document.getElementById('modalStatusBadge');
if (data.validation_status === 'approved') {
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-emerald-50 text-emerald-700 border border-emerald-200';
badge.textContent = 'Disetujui';
} else if (data.validation_status === 'rejected') {
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-rose-50 text-rose-700 border border-rose-200';
badge.textContent = 'Ditolak';
} else {
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-amber-50 text-amber-800 border border-amber-200';
badge.textContent = 'Menunggu QMA';
}
const notesContainer = document.getElementById('modalGeneralNotesContainer');
if (data.general_notes && data.general_notes.trim() !== '') {
notesContainer.classList.remove('hidden');
document.getElementById('modalGeneralNotes').textContent = data.general_notes;
} else {
notesContainer.classList.add('hidden');
}
if (data.items && data.items.length > 0) {
tableBody.innerHTML = data.items.map(item => {
const isGood = item.condition === 'baik' || item.condition === 'good' || item.condition === 'ok';
const condBadge = isGood
? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">Baik (OK)</span>'
: '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-50 text-rose-700 border border-rose-200">Rusak (Defect)</span>';
return `
<tr class="hover:bg-slate-50/50">
<td class="py-2.5 px-3 text-slate-500 font-medium">${item.section || '-'}</td>
<td class="py-2.5 px-3 font-semibold text-slate-800">${item.item_name || '-'}</td>
<td class="py-2.5 px-3 text-center">${condBadge}</td>
<td class="py-2.5 px-3 text-slate-600">${item.notes || '-'}</td>
</tr>
`;
}).join('');
} else {
tableBody.innerHTML = '<tr><td colspan="4" class="py-3 text-center text-slate-400">Tidak ada komponen checklist tercatat.</td></tr>';
}
})
.catch(err => {
tableBody.innerHTML = '<tr><td colspan="4" class="py-4 text-center text-rose-500">' + err.message + '</td></tr>';
});
}
function closeP2hDetailModal() {
document.getElementById('p2hDetailModal').classList.add('hidden');
}
// Tutup modal jika klik di luar box
document.getElementById('p2hDetailModal').addEventListener('click', function(e) {
if (e.target === this) {
closeP2hDetailModal();
}
});
</script>
@endsection
+16 -3
View File
@@ -166,7 +166,7 @@
<nav class="space-y-1"> <nav class="space-y-1">
@if(auth()->user()->isSuperAdmin()) @if(auth()->user()->isSuperAdmin())
<a href="{{ route('admin.dashboard') }}" <a href="{{ route('admin.dashboard') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}"> class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"> <svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7" rx="2"></rect> <rect x="3" y="3" width="7" height="7" rx="2"></rect>
<rect x="14" y="3" width="7" height="7" rx="2"></rect> <rect x="14" y="3" width="7" height="7" rx="2"></rect>
@@ -501,6 +501,12 @@
<span>Timesheet</span> <span>Timesheet</span>
</a> </a>
@endcan @endcan
<a href="{{ route('employee.history') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('employee.history*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-clock-rotate-left text-base w-5 text-center"></i>
<span>Riwayat Saya</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
@@ -569,7 +575,7 @@
<div> <div>
<nav class="space-y-1"> <nav class="space-y-1">
@if(auth()->user()->isSuperAdmin()) @if(auth()->user()->isSuperAdmin())
<a href="{{ route('admin.dashboard') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}"> <a href="{{ route('admin.dashboard') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"> <svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7" rx="2"></rect> <rect x="3" y="3" width="7" height="7" rx="2"></rect>
<rect x="14" y="3" width="7" height="7" rx="2"></rect> <rect x="14" y="3" width="7" height="7" rx="2"></rect>
@@ -881,6 +887,11 @@
<span>Timesheet</span> <span>Timesheet</span>
</a> </a>
@endcan @endcan
<a href="{{ route('employee.history') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('employee.history*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-clock-rotate-left w-5 text-center"></i>
<span>Riwayat Saya</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
@@ -929,7 +940,7 @@
<i class="fa-solid fa-bars text-base"></i> <i class="fa-solid fa-bars text-base"></i>
</button> </button>
<h1 class="text-lg sm:text-xl font-bold text-slate-900 tracking-tight"> <h1 class="text-lg sm:text-xl font-bold text-slate-900 tracking-tight">
@if(request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard')) @if(request()->routeIs('admin.dashboard'))
Dashboard Admin Dashboard Admin
@elseif(request()->routeIs('admin.users.*')) @elseif(request()->routeIs('admin.users.*'))
Kelola Pengguna Kelola Pengguna
@@ -987,6 +998,8 @@
Log Verifikasi Gerbang Log Verifikasi Gerbang
@elseif(request()->routeIs('employee.dashboard')) @elseif(request()->routeIs('employee.dashboard'))
Dashboard Karyawan Dashboard Karyawan
@elseif(request()->routeIs('employee.history*'))
Riwayat Aktivitas
@elseif(request()->routeIs('p2h.*')) @elseif(request()->routeIs('p2h.*'))
Pemeriksaan P2H Pemeriksaan P2H
@elseif(request()->routeIs('timesheet.*') || request()->routeIs('mobilisasi.*')) @elseif(request()->routeIs('timesheet.*') || request()->routeIs('mobilisasi.*'))
+58
View File
@@ -205,6 +205,12 @@
<a href="{{ route('qma.p2h.export_single_excel', $rec->id) }}" class="w-7 h-7 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 flex items-center justify-center transition border border-emerald-200 shadow-2xs" title="Download Lembar P2H (Excel)"> <a href="{{ route('qma.p2h.export_single_excel', $rec->id) }}" class="w-7 h-7 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 flex items-center justify-center transition border border-emerald-200 shadow-2xs" title="Download Lembar P2H (Excel)">
<i class="fa-solid fa-file-excel text-xs"></i> <i class="fa-solid fa-file-excel text-xs"></i>
</a> </a>
<button type="button"
onclick="openDeleteP2hModal({{ $rec->id }}, '{{ $rec->transaction_no }}', '{{ $rec->vehicle->code ?? '' }}')"
class="w-7 h-7 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-600 flex items-center justify-center transition border border-rose-200 shadow-2xs cursor-pointer"
title="Hapus Pemeriksaan P2H">
<i class="fa-regular fa-trash-can text-xs"></i>
</button>
</div> </div>
</td> </td>
</tr> </tr>
@@ -312,12 +318,64 @@ function closeGuideModal() {
document.addEventListener('keydown', function(e) { document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') { if (e.key === 'Escape') {
closeGuideModal(); closeGuideModal();
closeDeleteP2hModal();
const exportMenu = document.getElementById('exportMenuP2h'); const exportMenu = document.getElementById('exportMenuP2h');
if (exportMenu) exportMenu.style.display = 'none'; if (exportMenu) exportMenu.style.display = 'none';
} }
}); });
function openDeleteP2hModal(id, trxNo, unitCode) {
document.getElementById('deleteP2hForm').action = `/qma/p2h-records/${id}`;
document.getElementById('deleteP2hTxNo').textContent = trxNo;
document.getElementById('deleteP2hUnitCode').textContent = unitCode || '-';
const modal = document.getElementById('deleteP2hModal');
if (modal) {
modal.classList.remove('hidden');
modal.style.display = 'block';
}
}
function closeDeleteP2hModal() {
const modal = document.getElementById('deleteP2hModal');
if (modal) {
modal.classList.add('hidden');
modal.style.display = 'none';
}
}
</script> </script>
<!-- ========================================================================= -->
<!-- MODAL POPUP: HAPUS PEMERIKSAAN P2H -->
<!-- ========================================================================= -->
<div id="deleteP2hModal" class="hidden fixed inset-0 z-50 overflow-y-auto" style="display: none;">
<div class="fixed inset-0 bg-slate-900/60 backdrop-blur-xs transition-opacity" onclick="closeDeleteP2hModal()"></div>
<div class="flex min-h-full items-center justify-center p-4">
<div class="relative w-full max-w-md bg-white rounded-2xl shadow-xl border border-slate-100 p-6 text-center transform transition-all">
<div class="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100">
<i class="fa-solid fa-triangle-exclamation text-xl"></i>
</div>
<h3 class="text-sm font-bold text-slate-900 mb-1">Hapus Data Pemeriksaan P2H?</h3>
<p class="text-xs text-slate-500 mb-4 leading-relaxed">
Apakah Anda yakin ingin menghapus inspeksi P2H <span id="deleteP2hTxNo" class="font-mono font-bold text-rose-600">-</span> untuk unit <span id="deleteP2hUnitCode" class="font-bold text-slate-800">-</span>? Data akan dipindahkan ke <strong>Tong Sampah</strong> dan dapat dipulihkan sewaktu-waktu.
</p>
<form id="deleteP2hForm" method="POST" action="">
@csrf
@method('DELETE')
<div class="flex items-center justify-center space-x-3">
<button type="button" onclick="closeDeleteP2hModal()" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-semibold transition cursor-pointer">
Batal
</button>
<button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl text-xs font-bold transition shadow-xs cursor-pointer">
Ya, Hapus
</button>
</div>
</form>
</div>
</div>
</div>
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- MODAL POPUP: PANDUAN HALAMAN (LOG P2H HEAVY EQUIPMENT) --> <!-- MODAL POPUP: PANDUAN HALAMAN (LOG P2H HEAVY EQUIPMENT) -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
+66
View File
@@ -25,6 +25,15 @@
<span>Ekspor Excel (.xlsx)</span> <span>Ekspor Excel (.xlsx)</span>
</a> </a>
<!-- Tombol Hapus P2H -->
<button type="button"
onclick="openDeleteP2hModal({{ $record->id }}, '{{ $record->transaction_no }}', '{{ $record->vehicle->code ?? '' }}')"
class="inline-flex items-center space-x-1.5 text-xs font-bold text-rose-700 bg-rose-50 hover:bg-rose-100 border border-rose-200 px-3 py-1.5 rounded-xl transition shadow-xs cursor-pointer"
title="Hapus Pemeriksaan P2H">
<i class="fa-regular fa-trash-can text-[13px] text-rose-600"></i>
<span>Hapus P2H</span>
</button>
<!-- Badge Status Validasi --> <!-- Badge Status Validasi -->
<div> <div>
@if($record->isPending()) @if($record->isPending())
@@ -230,6 +239,63 @@
</div> </div>
</div> </div>
<!-- MODAL POPUP: HAPUS PEMERIKSAAN P2H -->
<div id="deleteP2hModal" class="hidden fixed inset-0 z-50 overflow-y-auto" style="display: none;">
<div class="fixed inset-0 bg-slate-900/60 backdrop-blur-xs transition-opacity" onclick="closeDeleteP2hModal()"></div>
<div class="flex min-h-full items-center justify-center p-4">
<div class="relative w-full max-w-md bg-white rounded-2xl shadow-xl border border-slate-100 p-6 text-center transform transition-all">
<div class="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100">
<i class="fa-solid fa-triangle-exclamation text-xl"></i>
</div>
<h3 class="text-sm font-bold text-slate-900 mb-1">Hapus Data Pemeriksaan P2H?</h3>
<p class="text-xs text-slate-500 mb-4 leading-relaxed">
Apakah Anda yakin ingin menghapus inspeksi P2H <span id="deleteP2hTxNo" class="font-mono font-bold text-rose-600">-</span> untuk unit <span id="deleteP2hUnitCode" class="font-bold text-slate-800">-</span>? Data akan dipindahkan ke <strong>Tong Sampah</strong> dan dapat dipulihkan sewaktu-waktu.
</p>
<form id="deleteP2hForm" method="POST" action="">
@csrf
@method('DELETE')
<div class="flex items-center justify-center space-x-3">
<button type="button" onclick="closeDeleteP2hModal()" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-semibold transition cursor-pointer">
Batal
</button>
<button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl text-xs font-bold transition shadow-xs cursor-pointer">
Ya, Hapus
</button>
</div>
</form>
</div>
</div>
</div>
<script>
function openDeleteP2hModal(id, trxNo, unitCode) {
document.getElementById('deleteP2hForm').action = `/qma/p2h-records/${id}`;
document.getElementById('deleteP2hTxNo').textContent = trxNo;
document.getElementById('deleteP2hUnitCode').textContent = unitCode || '-';
const modal = document.getElementById('deleteP2hModal');
if (modal) {
modal.classList.remove('hidden');
modal.style.display = 'block';
}
}
function closeDeleteP2hModal() {
const modal = document.getElementById('deleteP2hModal');
if (modal) {
modal.classList.add('hidden');
modal.style.display = 'none';
}
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
closeDeleteP2hModal();
}
});
</script>
<style> <style>
@media print { @media print {
.no-print, header, nav, aside, #mobileDrawer, #topNavbar, .sidebar-container { .no-print, header, nav, aside, #mobileDrawer, #topNavbar, .sidebar-container {
+95 -34
View File
@@ -100,32 +100,26 @@
</div> </div>
</div> </div>
<!-- Kotak Pencarian & Filter Status Timesheet (Tanpa Card Wrapper, Format Persis HSE Employees) --> <!-- Kotak Pencarian & Filter Status Timesheet -->
<form method="GET" action="{{ url()->current() }}" id="timesheetFilterForm" class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2.5 sm:gap-3"> <form method="GET" action="{{ url()->current() }}" id="timesheetFilterForm" class="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-2.5 sm:gap-3 flex-wrap">
<!-- Pencarian Cepat di Kiri dengan Tombol Cari --> <!-- Pencarian Cepat di Kiri -->
<div class="relative w-full sm:max-w-md flex items-center"> <div class="relative w-full lg:w-72 xl:w-80 flex-shrink-0">
<span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400 z-10"> <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
<i class="fa-solid fa-magnifying-glass text-xs"></i> <i class="fa-solid fa-magnifying-glass text-xs"></i>
</span> </span>
<input type="text" <input type="text"
name="search" name="search"
id="timesheetSearchInput" id="timesheetSearchInput"
value="{{ request('search') }}" value="{{ request('search') }}"
placeholder="Cari No. TS, nama/NIK operator, atau lokasi..." placeholder="Cari No. TS, nama/NIK operator, lokasi..."
autocomplete="off" autocomplete="off"
class="w-full text-xs pl-10 pr-20 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition"> class="w-full text-xs pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition">
<button type="submit"
id="timesheetSearchBtn"
class="absolute right-1.5 inset-y-1.5 px-3 bg-[#1b5e20] hover:bg-[#144918] active:scale-95 text-white font-bold text-xs rounded-lg flex items-center gap-1.5 transition shadow-sm cursor-pointer z-10">
<span>Cari</span>
</button>
</div> </div>
<!-- Filter di Kanan (Pada Mobile: Sejajar Grid di Bawah Search Bar) --> <!-- Filter di Kanan -->
<div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-2 sm:gap-2.5 w-full sm:w-auto"> <div class="flex flex-wrap items-center justify-start lg:justify-end gap-2 sm:gap-2.5 w-full lg:w-auto">
<div class="grid grid-cols-2 sm:flex sm:items-center sm:gap-2.5 w-full sm:w-auto">
<!-- Filter Rentang Tanggal Compact --> <!-- Filter Rentang Tanggal Compact -->
<div class="col-span-2 sm:col-auto flex items-center gap-1.5 bg-white border border-slate-200 rounded-xl px-2.5 py-2 shadow-sm"> <div class="flex items-center gap-1.5 bg-white border border-slate-200 rounded-xl px-2.5 py-2 shadow-sm">
<i class="fa-regular fa-calendar text-slate-400 text-xs flex-shrink-0"></i> <i class="fa-regular fa-calendar text-slate-400 text-xs flex-shrink-0"></i>
<input type="date" <input type="date"
name="start_date" name="start_date"
@@ -145,7 +139,7 @@
<!-- Filter Heavy Equipment --> <!-- Filter Heavy Equipment -->
<select name="vehicle_id" <select name="vehicle_id"
onchange="this.form.submit()" onchange="this.form.submit()"
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate"> class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate max-w-[200px]">
<option value="">Semua Heavy Equipment</option> <option value="">Semua Heavy Equipment</option>
@foreach($unitSupports as $u) @foreach($unitSupports as $u)
<option value="{{ $u->id }}" {{ request('vehicle_id') == $u->id ? 'selected' : '' }}> <option value="{{ $u->id }}" {{ request('vehicle_id') == $u->id ? 'selected' : '' }}>
@@ -157,7 +151,7 @@
<!-- Filter Shift --> <!-- Filter Shift -->
<select name="shift" <select name="shift"
onchange="this.form.submit()" onchange="this.form.submit()"
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate"> class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
<option value="">Semua Shift</option> <option value="">Semua Shift</option>
@foreach($shifts as $s) @foreach($shifts as $s)
<option value="{{ $s }}" {{ request('shift') === $s ? 'selected' : '' }}>{{ $s }}</option> <option value="{{ $s }}" {{ request('shift') === $s ? 'selected' : '' }}>{{ $s }}</option>
@@ -167,7 +161,7 @@
<!-- Filter Jenis Operator (Karyawan / Sukon) --> <!-- Filter Jenis Operator (Karyawan / Sukon) -->
<select name="operator_type" <select name="operator_type"
onchange="this.form.submit()" onchange="this.form.submit()"
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate"> class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
<option value="">Semua Personil</option> <option value="">Semua Personil</option>
<option value="Karyawan" {{ request('operator_type') === 'Karyawan' ? 'selected' : '' }}>Karyawan</option> <option value="Karyawan" {{ request('operator_type') === 'Karyawan' ? 'selected' : '' }}>Karyawan</option>
<option value="Sukon" {{ request('operator_type') === 'Sukon' ? 'selected' : '' }}>Sukon</option> <option value="Sukon" {{ request('operator_type') === 'Sukon' ? 'selected' : '' }}>Sukon</option>
@@ -176,19 +170,18 @@
<!-- Filter Tampilan Per Halaman --> <!-- Filter Tampilan Per Halaman -->
<select name="per_page" <select name="per_page"
onchange="this.form.submit()" onchange="this.form.submit()"
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate"> class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
<option value="15" {{ request('per_page', '15') == '15' ? 'selected' : '' }}>15 / Hal</option> <option value="15" {{ request('per_page', '15') == '15' ? 'selected' : '' }}>15 / Hal</option>
<option value="50" {{ request('per_page', '50') == '50' ? 'selected' : '' }}>50 / Hal</option> <option value="50" {{ request('per_page', '50') == '50' ? 'selected' : '' }}>50 / Hal</option>
<option value="100" {{ request('per_page', '100') == '100' ? 'selected' : '' }}>Semua (100)</option> <option value="100" {{ request('per_page', '100') == '100' ? 'selected' : '' }}>Semua (100)</option>
</select> </select>
</div>
<!-- Tombol Reset Filter --> <!-- Tombol Reset Filter -->
<div id="timesheetResetContainer"> <div id="timesheetResetContainer">
@if(request()->anyFilled(['search', 'vehicle_id', 'shift', 'operator_type', 'per_page']) || (request('start_date') && request('start_date') !== now()->toDateString()) || (request('end_date') && request('end_date') !== now()->toDateString())) @if(request()->anyFilled(['search', 'vehicle_id', 'shift', 'operator_type', 'per_page']) || (request('start_date') && request('start_date') !== now()->toDateString()) || (request('end_date') && request('end_date') !== now()->toDateString()))
<a href="{{ url()->current() }}" <a href="{{ url()->current() }}"
id="timesheetResetBtn" id="timesheetResetBtn"
class="text-xs text-rose-600 hover:text-rose-700 font-semibold flex items-center justify-center sm:justify-start space-x-1.5 transition whitespace-nowrap py-1 sm:py-0 sm:ml-2"> class="text-xs text-rose-600 hover:text-rose-700 font-semibold flex items-center justify-center sm:justify-start space-x-1.5 transition whitespace-nowrap py-1 sm:py-0 sm:ml-1">
<i class="fa-solid fa-rotate-left text-[11px]"></i> <i class="fa-solid fa-rotate-left text-[11px]"></i>
<span>Reset Filter</span> <span>Reset Filter</span>
</a> </a>
@@ -571,7 +564,7 @@
id="addOperatorSelect" id="addOperatorSelect"
required required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition"> class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="">-- Pilih Operator --</option> <option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
@foreach($operators as $op) @foreach($operators as $op)
@php @php
$opType = $op->employee_type ?: 'Karyawan'; $opType = $op->employee_type ?: 'Karyawan';
@@ -587,7 +580,7 @@
@endforeach @endforeach
</select> </select>
<p id="addOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between"> <p id="addOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
<span>Total personil: {{ count($operators) }}</span> <span>Total personil: - (Pilih unit terlebih dahulu)</span>
<span class="text-emerald-700 font-semibold" id="addOperatorCurrentFilterText">Filter: Semua</span> <span class="text-emerald-700 font-semibold" id="addOperatorCurrentFilterText">Filter: Semua</span>
</p> </p>
</div> </div>
@@ -903,7 +896,7 @@
id="editOperatorSelect" id="editOperatorSelect"
required required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition"> class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="">-- Pilih Operator --</option> <option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
@foreach($operators as $op) @foreach($operators as $op)
@php @php
$opType = $op->employee_type ?: 'Karyawan'; $opType = $op->employee_type ?: 'Karyawan';
@@ -919,7 +912,7 @@
@endforeach @endforeach
</select> </select>
<p id="editOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between"> <p id="editOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
<span>Total personil: {{ count($operators) }}</span> <span>Total personil: - (Pilih unit terlebih dahulu)</span>
<span class="text-emerald-700 font-semibold" id="editOperatorCurrentFilterText">Filter: Semua</span> <span class="text-emerald-700 font-semibold" id="editOperatorCurrentFilterText">Filter: Semua</span>
</p> </p>
</div> </div>
@@ -1175,13 +1168,17 @@
<script> <script>
window.unitSupportsData = @json($unitSupports); window.unitSupportsData = @json($unitSupports);
window.allOperatorsData = @json($operators); window.allOperatorsData = @json($operators);
window.unitOperatorsMap = @json($unitOperatorsMap);
// Filter Segmented Operator (Semua / Karyawan / Sukon) // Filter Segmented Operator (Semua / Karyawan / Sukon) & Sinkronisasi Kualifikasi SIMPER Alat Berat
function filterOperatorSelect(type, mode, preserveSelectedId) { function filterOperatorSelect(type, mode, preserveSelectedId) {
const selectId = mode === 'edit' ? 'editOperatorSelect' : 'addOperatorSelect'; const selectId = mode === 'edit' ? 'editOperatorSelect' : 'addOperatorSelect';
const select = document.getElementById(selectId); const select = document.getElementById(selectId);
if (!select) return; if (!select) return;
type = type || 'all';
select.setAttribute('data-active-filter', type);
// Update button states // Update button states
const types = ['all', 'Karyawan', 'Sukon']; const types = ['all', 'Karyawan', 'Sukon'];
types.forEach(t => { types.forEach(t => {
@@ -1201,36 +1198,91 @@
filterText.textContent = `Filter: ${type === 'all' ? 'Semua' : type}`; filterText.textContent = `Filter: ${type === 'all' ? 'Semua' : type}`;
} }
const vehSelect = document.getElementById(`${mode}VehicleSelect`);
const selectedVehicleId = vehSelect ? vehSelect.value : null;
const currentVal = preserveSelectedId !== undefined ? String(preserveSelectedId) : select.value; const currentVal = preserveSelectedId !== undefined ? String(preserveSelectedId) : select.value;
const options = select.querySelectorAll('option'); const options = select.querySelectorAll('option');
let visibleCount = 0; let visibleCount = 0;
// 1. Jika belum ada unit Heavy Equipment yang dipilih
if (!selectedVehicleId) {
options.forEach(opt => { options.forEach(opt => {
if (!opt.value) { if (!opt.value) {
opt.textContent = '-- Pilih Heavy Equipment Terlebih Dahulu --';
opt.hidden = false;
} else {
opt.hidden = true;
}
});
select.value = '';
const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
if (countHelp) {
const spanFirst = countHelp.querySelector('span:first-child');
if (spanFirst) {
spanFirst.textContent = 'Total personil: - (Pilih unit terlebih dahulu)';
spanFirst.className = 'text-slate-400';
}
}
return;
}
// 2. Dapatkan daftar ID operator yang kualifikasi SIMPER-nya aktif untuk unit ini
const eligibleMap = window.unitOperatorsMap || {};
const eligibleIds = eligibleMap[selectedVehicleId] || [];
const eligibleSet = new Set(eligibleIds.map(String));
if (preserveSelectedId !== undefined && preserveSelectedId !== null && preserveSelectedId !== '') {
eligibleSet.add(String(preserveSelectedId));
}
const hasEligible = eligibleSet.size > 0;
options.forEach(opt => {
if (!opt.value) {
if (!hasEligible) {
opt.textContent = '-- Tidak ada operator dengan SIMPER untuk unit ini --';
} else {
opt.textContent = `-- Pilih Operator (${eligibleSet.size} Memenuhi SIMPER) --`;
}
opt.hidden = false; opt.hidden = false;
return; return;
} }
const opId = String(opt.value);
const isEligible = eligibleSet.has(opId);
const optType = opt.getAttribute('data-type') || 'Karyawan'; const optType = opt.getAttribute('data-type') || 'Karyawan';
let match = false;
let typeMatch = false;
if (type === 'all') { if (type === 'all') {
match = true; typeMatch = true;
} else if (type === 'Karyawan') { } else if (type === 'Karyawan') {
match = optType === 'Karyawan'; typeMatch = optType === 'Karyawan';
} else if (type === 'Sukon') { } else if (type === 'Sukon') {
match = optType === 'Sukon'; typeMatch = optType === 'Sukon';
} else { } else {
match = optType.toLowerCase() === type.toLowerCase(); typeMatch = optType.toLowerCase() === type.toLowerCase();
} }
const match = isEligible && typeMatch;
opt.hidden = !match; opt.hidden = !match;
if (match) visibleCount++; if (match) visibleCount++;
}); });
// Update total count // Update total count & status
const countHelp = document.getElementById(`${mode}OperatorCountHelp`); const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
if (countHelp) { if (countHelp) {
const spanFirst = countHelp.querySelector('span:first-child'); const spanFirst = countHelp.querySelector('span:first-child');
if (spanFirst) spanFirst.textContent = `Total personil: ${visibleCount}`; if (spanFirst) {
if (!hasEligible) {
spanFirst.textContent = 'Total personil: 0 (Tidak ada SIMPER yang cocok)';
spanFirst.className = 'text-rose-600 font-semibold';
} else {
spanFirst.textContent = `Total personil: ${visibleCount} dari ${eligibleSet.size} operator SIMPER aktif`;
spanFirst.className = 'text-slate-500';
}
}
} }
// Restore or reset selection // Restore or reset selection
@@ -1241,6 +1293,8 @@
} else if (preserveSelectedId === undefined) { } else if (preserveSelectedId === undefined) {
select.value = ''; select.value = '';
} }
} else {
select.value = '';
} }
} }
@@ -1498,6 +1552,7 @@
vehicleSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>'; vehicleSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
if (counterBadge) counterBadge.classList.add('hidden'); if (counterBadge) counterBadge.classList.add('hidden');
if (previewEl) previewEl.classList.add('hidden'); if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
return; return;
} else if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') { } else if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
filteredUnits = allUnits; filteredUnits = allUnits;
@@ -1566,6 +1621,7 @@
} else { } else {
defaultPrompt.selected = true; defaultPrompt.selected = true;
if (previewEl) previewEl.classList.add('hidden'); if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
} }
} }
@@ -1620,6 +1676,11 @@
if (locSelect && locSelect.value === 'ALL' && finalLoc && !finalLoc.value) { if (locSelect && locSelect.value === 'ALL' && finalLoc && !finalLoc.value) {
finalLoc.value = unitLocation; finalLoc.value = unitLocation;
} }
// Otomatis filter operator sesuai izin SIMPER aktif untuk alat berat ini
const opSelect = document.getElementById(`${prefix}OperatorSelect`);
const currentOpFilter = opSelect ? (opSelect.getAttribute('data-active-filter') || 'all') : 'all';
filterOperatorSelect(currentOpFilter, prefix);
} }
function updateMeterUnitLabels(prefix) { function updateMeterUnitLabels(prefix) {
+7 -10
View File
@@ -48,13 +48,6 @@ Route::prefix('gate-activity')->name('vehicle.activity.')->group(function () {
// Group Terproteksi Autentikasi Sistem // Group Terproteksi Autentikasi Sistem
Route::middleware('auth')->group(function () { Route::middleware('auth')->group(function () {
// Backward Compatibility: Rute Super Admin Legacy -> Admin Dashboard Baru
Route::prefix('superadmin')->name('superadmin.')->middleware('role:super_admin')->group(function () {
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 - Kelola Karyawan & SIMPER // 2. Modul HSE: Admin HSE - Kelola Karyawan & SIMPER
Route::prefix('hse')->name('hse.')->group(function () { Route::prefix('hse')->name('hse.')->group(function () {
Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard')->middleware('permission:hse.employees.view'); Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard')->middleware('permission:hse.employees.view');
@@ -146,6 +139,7 @@ Route::middleware('auth')->group(function () {
Route::get('/p2h-records/{id}/export-excel', [P2hInspectionController::class, 'exportSingleExcel'])->name('p2h.export_single_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view'); Route::get('/p2h-records/{id}/export-excel', [P2hInspectionController::class, 'exportSingleExcel'])->name('p2h.export_single_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view');
Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve')->middleware('permission:qma.p2h.approve|qma.vehicles.edit'); Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve')->middleware('permission:qma.p2h.approve|qma.vehicles.edit');
Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.p2h.approve|qma.vehicles.edit'); Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.p2h.approve|qma.vehicles.edit');
Route::delete('/p2h-records/{id}', [P2hInspectionController::class, 'destroy'])->name('p2h.destroy')->middleware('permission:qma.vehicles.delete|qma.p2h.approve|qma.vehicles.edit');
// Master 28 Template Checksheet P2H & Kelola Pertanyaan // Master 28 Template Checksheet P2H & Kelola Pertanyaan
Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.p2h.templates|qma.vehicles.view'); Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.p2h.templates|qma.vehicles.view');
@@ -187,8 +181,11 @@ Route::middleware('auth')->group(function () {
Route::post('/{code}', [P2hFormController::class, 'store'])->middleware('throttle:30,1')->name('store'); 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/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::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}/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'); Route::post('/karyawan/aktivitas/{id}/cancel', [\App\Http\Controllers\Employee\DashboardController::class, 'cancelActivity'])->name('employee.activity.cancel');
@@ -221,10 +218,10 @@ Route::middleware('auth')->group(function () {
// Backup & Restore Sistem (Database & Media) // Backup & Restore Sistem (Database & Media)
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index'); Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store'); Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file'); Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1');
Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download'); Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download');
Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload'); Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload');
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore'); Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1');
Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy'); Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy');
// Tong Sampah / Recycle Bin & Retensi Otomatis // Tong Sampah / Recycle Bin & Retensi Otomatis
+398
View File
@@ -0,0 +1,398 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\Gate;
use App\Models\P2hRecord;
use App\Models\P2hRecordItem;
use App\Models\P2hTemplate;
use App\Models\UnitSupportTimesheet;
use App\Models\User;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use Carbon\Carbon;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class EmployeeHistoryTest extends TestCase
{
use RefreshDatabase;
protected User $userA;
protected Employee $empA;
protected User $userB;
protected Employee $empB;
protected Vehicle $heavyEquipment;
protected Vehicle $lightVehicle;
protected Gate $gate;
protected P2hTemplate $template;
protected function setUp(): void
{
parent::setUp();
$this->seed(RolePermissionSeeder::class);
// Karyawan / Operator A
$this->userA = User::create([
'name' => 'Operator Alex Test',
'username' => 'operator_alex',
'email' => '[email protected]',
'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' => '[email protected]',
'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,
]
);
// Berikan SIMPER Heavy Equipment untuk Operator A & B
$simperHeavy = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-HEAVY'],
[
'name' => 'Heavy Equipment',
'scopes' => ['unit_support_heavy', 'Excavator'],
'is_active' => true,
]
);
\App\Models\EmployeeSimper::create([
'employee_id' => $this->empA->id,
'simper_type_id' => $simperHeavy->id,
'status' => 'active',
'expired_at' => Carbon::now()->addMonths(6),
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $this->empB->id,
'simper_type_id' => $simperHeavy->id,
'status' => 'active',
'expired_at' => Carbon::now()->addMonths(6),
]);
}
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' => '[email protected]',
'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);
}
public function test_employee_with_only_lv_simper_does_not_see_heavy_equipment(): void
{
$simperLv = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-LV'],
[
'name' => 'Light Vehicle Only',
'scopes' => ['light_vehicle'],
'is_active' => true,
]
);
$userDriver = User::create([
'name' => 'Driver Doni LV Only',
'username' => 'driver_doni',
'email' => '[email protected]',
'password' => Hash::make('password123'),
'role' => 'employee',
]);
$empDriver = $userDriver->getOrCreateEmployee();
$empDriver->update(['is_operator' => true]);
\App\Models\EmployeeSimper::create([
'employee_id' => $empDriver->id,
'simper_type_id' => $simperLv->id,
'status' => 'active',
'expired_at' => Carbon::now()->addMonths(6),
]);
$response = $this->actingAs($userDriver)->get(route('employee.history'));
$response->assertStatus(200);
$response->assertSee('Mobilisasi');
$response->assertSee('Pos Gerbang');
$response->assertDontSee('P2H Heavy Equipment');
$response->assertDontSee('Timesheet Heavy Equipment');
}
}
+39
View File
@@ -734,6 +734,45 @@ class P2hInspectionTest extends TestCase
$this->assertCount(4, $itemsAfterDelete); $this->assertCount(4, $itemsAfterDelete);
$this->assertEquals([1, 2, 3, 4], $itemsAfterDelete->pluck('sequence')->all()); $this->assertEquals([1, 2, 3, 4], $itemsAfterDelete->pluck('sequence')->all());
} }
/**
* Admin QMA dapat menghapus data riwayat pemeriksaan P2H (Soft Delete ke Tong Sampah).
*/
public function test_qma_admin_can_soft_delete_p2h_record(): void
{
$record = P2hRecord::create([
'transaction_no' => 'P2H-TEST-DEL-001',
'vehicle_id' => $this->supportVehicle->id,
'employee_id' => $this->operatorEmp->id,
'template_id' => $this->template->id,
'shift' => 'Shift Siang',
'start_hm' => 1500.0,
'summary_condition' => 'normal',
'validation_status' => 'pending',
'inspected_at' => Carbon::now(),
]);
$item = \App\Models\P2hRecordItem::create([
'p2h_record_id' => $record->id,
'section' => 'Bagian A',
'title' => 'Cek Oli Mesin',
'question_type' => 'choice',
'condition_status' => 'baik',
]);
$response = $this->actingAs($this->qmaAdmin)
->delete(route('qma.p2h.destroy', $record->id));
$response->assertRedirect(route('qma.p2h.index'));
$response->assertSessionHas('success');
$this->assertSoftDeleted('p2h_records', ['id' => $record->id]);
$this->assertSoftDeleted('p2h_record_items', ['id' => $item->id]);
// Pastikan muncul di TrashService
$trashItems = app(\App\Services\TrashService::class)->getTrashedItems('p2h_records');
$this->assertTrue(collect($trashItems->items())->contains('id', $record->id));
}
} }
@@ -139,6 +139,11 @@ class PhotoUploadAndCompressionTest extends TestCase
$deleteResponse->assertRedirect(); $deleteResponse->assertRedirect();
$this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]); $this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]);
// Foto tetap dipertahankan saat soft delete agar dapat dipulihkan dari Trash/Recycle Bin
Storage::disk('public')->assertExists($photoPath);
// Ketika dihapus permanen melalui TrashService, file fisik baru terhapus
app(\App\Services\TrashService::class)->forceDeleteItem('vehicles', $vehicle->id);
Storage::disk('public')->assertMissing($photoPath); Storage::disk('public')->assertMissing($photoPath);
} }
+128
View File
@@ -3,6 +3,8 @@
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\Employee; use App\Models\Employee;
use App\Models\EmployeeSimper;
use App\Models\SimperType;
use App\Models\UnitSupportTimesheet; use App\Models\UnitSupportTimesheet;
use App\Models\User; use App\Models\User;
use App\Models\Vehicle; use App\Models\Vehicle;
@@ -47,6 +49,7 @@ class QmaSupportTimesheetTest extends TestCase
$this->supportUnit = Vehicle::create([ $this->supportUnit = Vehicle::create([
'code' => 'EX01', 'code' => 'EX01',
'category' => 'unit_support', 'category' => 'unit_support',
'unit_category' => 'Excavator',
'brand_type' => 'Komatsu PC200-8 Excavator', 'brand_type' => 'Komatsu PC200-8 Excavator',
'status' => 'Operation', 'status' => 'Operation',
'site_status' => 'inside_site', 'site_status' => 'inside_site',
@@ -61,6 +64,7 @@ class QmaSupportTimesheetTest extends TestCase
'department' => 'Civil Construction', 'department' => 'Civil Construction',
'is_operator' => true, 'is_operator' => true,
'is_driver' => true, 'is_driver' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]); ]);
} }
@@ -547,4 +551,128 @@ class QmaSupportTimesheetTest extends TestCase
$responseKaryawan->assertSee('TS-KARYAWAN-001'); $responseKaryawan->assertSee('TS-KARYAWAN-001');
$responseKaryawan->assertDontSee('TS-SUKON-001'); $responseKaryawan->assertDontSee('TS-SUKON-001');
} }
/**
* Index memuat peta kualifikasi operator per alat berat (unitOperatorsMap).
*/
public function test_index_passes_unit_operators_map_matching_equipment_simper(): void
{
$simperEx = SimperType::create([
'code' => 'SIMPER-EXCAVATOR',
'name' => 'SIMPER Alat Excavator',
'category_scope' => 'Excavator',
'is_active' => true,
]);
$simperDt = SimperType::create([
'code' => 'SIMPER-DT-ONLY',
'name' => 'SIMPER Khusus DT',
'category_scope' => 'unit_support_mobile',
'is_active' => true,
]);
$opEx = Employee::create([
'nik' => 'OP-EX-001',
'name' => 'Operator Khusus Excavator',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opEx->id,
'simper_type_id' => $simperEx->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$opDt = Employee::create([
'nik' => 'OP-DT-001',
'name' => 'Driver Khusus Dump Truck',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opDt->id,
'simper_type_id' => $simperDt->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$unitDumpTruck = Vehicle::create([
'code' => 'DT99',
'category' => 'unit_support',
'unit_category' => 'Dump Truck',
'brand_type' => 'Mitsubishi Fuso 220PS',
'is_timesheet_mobile' => true,
'status' => 'Operation',
'site_status' => 'inside_site',
'location' => 'Adit 1',
'current_km' => 500.0,
]);
$response = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.index'));
$response->assertStatus(200);
$response->assertViewHas('unitOperatorsMap');
$map = $response->viewData('unitOperatorsMap');
$this->assertIsArray($map);
// Unit EX01 harus memuat $opEx dan TIDAK memuat $opDt
$this->assertContains($opEx->id, $map[$this->supportUnit->id]);
$this->assertNotContains($opDt->id, $map[$this->supportUnit->id]);
// Unit DT99 harus memuat $opDt dan TIDAK memuat $opEx
$this->assertContains($opDt->id, $map[$unitDumpTruck->id]);
$this->assertNotContains($opEx->id, $map[$unitDumpTruck->id]);
}
/**
* Operator dengan SIMPER Dump Truck ditolak saat menginput timesheet alat berat Excavator.
*/
public function test_store_fails_when_dump_truck_operator_attempts_excavator_timesheet(): void
{
$simperDt = SimperType::create([
'code' => 'SIMPER-DT-ONLY2',
'name' => 'SIMPER Khusus DT 2',
'category_scope' => 'unit_support_mobile',
'is_active' => true,
]);
$opDt = Employee::create([
'nik' => 'OP-DT-002',
'name' => 'Driver DT Saja',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opDt->id,
'simper_type_id' => $simperDt->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$data = [
'vehicle_id' => $this->supportUnit->id, // Excavator
'operator_id' => $opDt->id,
'date' => Carbon::today()->toDateString(),
'shift' => 'Shift Siang',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1258.00,
'location' => 'Main Dam',
'activity_type' => 'Galian Material',
'status' => 'Operation',
];
$response = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $data);
$response->assertRedirect();
$response->assertSessionHas('error');
$this->assertDatabaseMissing('unit_support_timesheets', [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $opDt->id,
]);
}
} }
+108
View File
@@ -556,4 +556,112 @@ class SuperAdminRbacTest extends TestCase
$this->assertEquals('Operator Turbin', $employee->position); $this->assertEquals('Operator Turbin', $employee->position);
$this->assertFalse((bool)$employee->is_operator); $this->assertFalse((bool)$employee->is_operator);
} }
public function test_super_admin_cannot_delete_employee_core_role(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
$employeeRole = Role::where('name', 'employee')->first();
$this->assertNotNull($employeeRole);
$response = $this->actingAs($superAdmin)->delete(route('admin.roles.destroy', $employeeRole->id));
$response->assertRedirect(route('admin.roles.index'));
$response->assertSessionHas('error');
$this->assertDatabaseHas('roles', ['name' => 'employee']);
}
public function test_unauthorized_employee_cannot_impersonate_another_employee_trip(): void
{
$gate = Gate::create([
'code' => 'GT-01',
'name' => 'Main Gate',
'is_active' => true,
]);
$vehicle = \App\Models\Vehicle::create([
'code' => 'LV-SEC-01',
'category' => 'light_vehicle',
'brand_type' => 'Toyota Hilux',
'license_plate' => 'BH 1111 XX',
'status' => 'Operation',
'current_km' => 1000,
]);
// User A (Karyawan A)
$userA = User::factory()->create([
'username' => 'EMP-AAA',
'name' => 'Karyawan A',
'role' => 'employee',
]);
$userA->assignRole('employee');
$empA = $userA->getOrCreateEmployee();
// User B (Karyawan B yang sah sebagai driver)
$userB = User::factory()->create([
'username' => 'EMP-BBB',
'name' => 'Karyawan B',
'role' => 'employee',
]);
$userB->assignRole('employee');
$empB = $userB->getOrCreateEmployee();
// Karyawan A mencoba submit atas nama Karyawan B
$response = $this->actingAs($userA)->post(route('vehicle.activity.store', ['code' => $vehicle->code]), [
'driver_id' => $empB->id,
'gate_id' => $gate->id,
'direction' => 'out',
'current_km' => 1010,
'purpose' => 'Test Tampering',
]);
$response->assertSessionHasErrors('driver_id');
$this->assertDatabaseMissing('vehicle_activities', [
'vehicle_id' => $vehicle->id,
'driver_id' => $empB->id,
'current_km' => 1010,
]);
}
public function test_timesheet_concurrency_generator_avoids_duplicate_numbers(): void
{
$today = now();
$dateStr = $today->format('Ymd');
$expectedNo1 = "TS-US-{$dateStr}-0001";
$no1 = \App\Models\UnitSupportTimesheet::generateTimesheetNo($today);
$this->assertEquals($expectedNo1, $no1);
// Simulasikan ada record yang sudah dibuat dengan nomor tersebut
$vehicle = \App\Models\Vehicle::create([
'code' => 'HE-CONC-01',
'category' => 'unit_support',
'brand_type' => 'Excavator PC200',
'status' => 'Operation',
'current_km' => 500,
]);
$emp = \App\Models\Employee::create([
'nik' => 'OP-CONC-01',
'name' => 'Operator Concurrency',
'is_operator' => true,
]);
\App\Models\UnitSupportTimesheet::create([
'timesheet_no' => $expectedNo1,
'vehicle_id' => $vehicle->id,
'operator_id' => $emp->id,
'date' => $today->toDateString(),
'shift' => 'Shift Siang',
'meter_type' => 'HM',
'start_meter' => 100,
'end_meter' => 108,
'operating_hours' => 8,
'location' => 'Pit A',
'activity_type' => 'Galian',
'status' => 'Operation',
]);
// Generator harus mendeteksi nomor 0001 sudah ada dan otomatis menghasilkan 0002
$no2 = \App\Models\UnitSupportTimesheet::generateTimesheetNo($today);
$this->assertEquals("TS-US-{$dateStr}-0002", $no2);
}
} }
+32
View File
@@ -310,4 +310,36 @@ class TrashAndAutoDeleteTest extends TestCase
'id' => $freshActivity->id, 'id' => $freshActivity->id,
]); ]);
} }
public function test_vehicle_photo_preserved_on_soft_delete_and_restored(): void
{
$vehicle = Vehicle::create([
'code' => 'LV-PHOTO-01',
'category' => 'light_vehicle',
'brand_type' => 'Hilux',
'license_plate' => 'BH 9999 AA',
'status' => 'Operation',
'current_km' => 500,
'photo_path' => 'vehicles/dummy_photo.jpg',
]);
// Simulasikan penghapusan kendaraan
$this->actingAs($this->superAdmin)
->delete(route('qma.vehicles.destroy', $vehicle->id));
$this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]);
// Verifikasi photo_path masih tersimpan di record
$trashed = Vehicle::onlyTrashed()->find($vehicle->id);
$this->assertNotNull($trashed);
$this->assertEquals('vehicles/dummy_photo.jpg', $trashed->photo_path);
// Pulihkan dari tong sampah
$this->actingAs($this->superAdmin)
->post(route('admin.trash.restore', ['category' => 'vehicles', 'id' => $vehicle->id]));
$restored = Vehicle::find($vehicle->id);
$this->assertNotNull($restored);
$this->assertEquals('vehicles/dummy_photo.jpg', $restored->photo_path);
}
} }