From 6e5ae727f93c26692baf3ce112d5cd0fff745555 Mon Sep 17 00:00:00 2001 From: Ray1111-aa Date: Fri, 16 Oct 2026 11:02:28 +0700 Subject: [PATCH] penambahan fitur ekspor di hse, qma, dan pg --- .../Controllers/Hse/EmployeeController.php | 170 ++++- .../Pg/SecurityGuardController.php | 159 ++++- .../Pg/VerificationLogController.php | 228 ++++++- .../Controllers/Qma/ActivityLogController.php | 486 +++++++++++++- .../Qma/P2hInspectionController.php | 446 ++++++++++++- .../Controllers/Qma/VehicleController.php | 599 +++++++++++++++++- app/Services/PgTablePdfExporter.php | 207 ++++++ app/Services/QmaTablePdfExporter.php | 207 ++++++ app/Services/SimperPdfExporter.php | 227 +++++++ app/Services/SimpleXlsxExporter.php | 203 ++++++ app/Services/VehiclePdfExporter.php | 199 ++++++ composer.json | 1 + composer.lock | 48 +- config/rbac_permissions.php | 30 + database/seeders/P2hTemplateSeeder.php | 224 ++++--- database/seeders/RolePermissionSeeder.php | 8 + resources/views/hse/employees_index.blade.php | 61 +- resources/views/layouts/app.blade.php | 20 +- resources/views/pg/guards_index.blade.php | 48 +- .../views/pg/verification_logs.blade.php | 46 +- resources/views/qma/activity_log.blade.php | 50 +- .../views/qma/activity_summary.blade.php | 50 +- resources/views/qma/p2h_index.blade.php | 58 +- resources/views/qma/p2h_summary.blade.php | 50 +- resources/views/qma/vehicles_lv.blade.php | 50 +- .../views/qma/vehicles_support.blade.php | 50 +- .../qma/vehicles_support_units.blade.php | 60 +- routes/web.php | 52 +- tests/Feature/HseSimperExportTest.php | 112 ++++ tests/Feature/PgExportTest.php | 262 ++++++++ tests/Feature/QmaActivityAndP2hExportTest.php | 236 +++++++ tests/Feature/QmaSummaryExportTest.php | 235 +++++++ tests/Feature/QmaVehicleExportTest.php | 230 +++++++ tests/Feature/SuperAdminRbacTest.php | 21 +- 34 files changed, 4964 insertions(+), 169 deletions(-) create mode 100644 app/Services/PgTablePdfExporter.php create mode 100644 app/Services/QmaTablePdfExporter.php create mode 100644 app/Services/SimperPdfExporter.php create mode 100644 app/Services/SimpleXlsxExporter.php create mode 100644 app/Services/VehiclePdfExporter.php create mode 100644 tests/Feature/HseSimperExportTest.php create mode 100644 tests/Feature/PgExportTest.php create mode 100644 tests/Feature/QmaActivityAndP2hExportTest.php create mode 100644 tests/Feature/QmaSummaryExportTest.php create mode 100644 tests/Feature/QmaVehicleExportTest.php diff --git a/app/Http/Controllers/Hse/EmployeeController.php b/app/Http/Controllers/Hse/EmployeeController.php index e0c56cf..2bf8b84 100644 --- a/app/Http/Controllers/Hse/EmployeeController.php +++ b/app/Http/Controllers/Hse/EmployeeController.php @@ -5,8 +5,12 @@ namespace App\Http\Controllers\Hse; use App\Http\Controllers\Controller; use App\Models\Employee; use App\Models\User; +use App\Services\SimperPdfExporter; +use App\Services\SimpleXlsxExporter; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Http\Response; use Illuminate\Support\Facades\Hash; use Illuminate\View\View; @@ -62,9 +66,9 @@ class EmployeeController extends Controller } /** - * Tampilkan daftar master karyawan HSE & status SIMPER. + * Helper query builder untuk memfilter master data karyawan & status SIMPER. */ - public function index(Request $request): View + private function getFilteredEmployees(Request $request): Builder { $query = Employee::query(); @@ -114,11 +118,171 @@ class EmployeeController extends Controller } } - $employees = $query->orderBy('name')->paginate(20)->withQueryString(); + return $query->orderBy('name'); + } + + /** + * Tampilkan daftar master karyawan HSE & status SIMPER. + */ + public function index(Request $request): View + { + $employees = $this->getFilteredEmployees($request)->paginate(20)->withQueryString(); return view('hse.employees_index', compact('employees')); } + /** + * Ekspor data master SIMPER karyawan ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $employees = $this->getFilteredEmployees($request)->get(); + + $today = now()->translatedFormat('d F Y, H:i'); + $driverFilter = match ($request->input('driver_status')) { + 'driver' => 'Driver', + 'non_driver' => 'Bukan Driver', + default => 'Semua Status Driver' + }; + $simperFilter = match ($request->input('simper_status')) { + 'valid' => 'Masih Berlaku (Aktif)', + 'expiring_soon' => 'Segera Habis (≤ 30 Hari)', + 'expired' => 'Kedaluwarsa (Expired)', + default => 'Semua Masa Berlaku' + }; + + $metaLines = [ + 'Filter: ' . $driverFilter . ' | ' . $simperFilter . ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total Data: ' . $employees->count() . ' Karyawan | Tanggal Dicetak: ' . $today . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'NIK' => 16, + 'Nama Lengkap' => 30, + 'Jabatan' => 24, + 'Unit Kerja' => 20, + 'Divisi' => 20, + 'Status Driver' => 16, + 'Masa Berlaku SIMPER' => 22, + 'Status SIMPER' => 24, + ]; + + $rows = []; + $now = now(); + $soon = now()->addDays(30); + + foreach ($employees as $idx => $emp) { + $isDriver = $emp->is_operator; + $expDate = $emp->simper_expired_at ? $emp->simper_expired_at->format('d/m/Y') : '-'; + + if (! $isDriver) { + $statusText = 'Bukan Driver'; + } elseif (! $emp->simper_expired_at) { + $statusText = 'Belum Ada SIMPER'; + } elseif ($emp->simper_expired_at->isPast() && ! $emp->simper_expired_at->isToday()) { + $statusText = 'Kedaluwarsa (Expired)'; + } elseif ($emp->simper_expired_at->lte($soon)) { + $statusText = 'Segera Habis (≤ 30 Hari)'; + } else { + $statusText = 'Masih Berlaku (Aktif)'; + } + + $rows[] = [ + $idx + 1, + $emp->nik, + $emp->name, + $emp->position ?: '-', + $emp->unit_kerja ?: '-', + $emp->division ?: '-', + $isDriver ? 'Driver' : 'Bukan Driver', + $expDate, + $statusText, + ]; + } + + $alignments = [ + 'center', // No + 'center', // NIK + 'left', // Nama + 'left', // Jabatan + 'left', // Unit Kerja + 'left', // Divisi + 'center', // Status Driver + 'center', // Masa Berlaku + 'center', // Status SIMPER + ]; + + $fileName = 'Laporan_Data_Simper_' . now()->format('Ymd_Hi') . '.xlsx'; + $binary = SimpleXlsxExporter::create( + 'LAPORAN DATA SIMPER & STATUS DRIVER KARYAWAN - PT KERINCI MERANGIN HIDRO', + $metaLines, + $headers, + $rows, + $alignments + ); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Tampilkan laporan resmi SIMPER ke format PDF (Pratinjau PDF Asli dengan Logo PT KMH). + */ + public function exportPdf(Request $request): Response + { + $employees = $this->getFilteredEmployees($request)->get(); + + $driverFilter = match ($request->input('driver_status')) { + 'driver' => 'Driver', + 'non_driver' => 'Bukan Driver', + default => 'Semua Status Driver' + }; + $simperFilter = match ($request->input('simper_status')) { + 'valid' => 'Masih Berlaku (Aktif)', + 'expiring_soon' => 'Segera Habis (≤ 30 Hari)', + 'expired' => 'Kedaluwarsa (Expired)', + default => 'Semua Masa Berlaku' + }; + + $totalActive = $employees->filter(fn ($e) => $e->is_operator && $e->hasValidSimper())->count(); + $totalExpired = $employees->filter(fn ($e) => $e->is_operator && ! $e->hasValidSimper())->count(); + $totalNonDriver = $employees->filter(fn ($e) => ! $e->is_operator)->count(); + + $metaLeft = [ + 'Kategori' => $driverFilter, + 'Tanggal Cetak' => now()->translatedFormat('d F Y, H:i') . ' WIB', + ]; + + $statusSummary = "{$totalActive} Aktif, {$totalExpired} Expired"; + if ($totalNonDriver > 0) { + $statusSummary .= ", {$totalNonDriver} Non-Driver"; + } + + $metaRight = [ + 'Total Karyawan' => $employees->count() . ' Orang', + 'Status SIMPER' => $statusSummary, + ]; + + $subtitle = 'Data Karyawan & Driver - ' . now()->translatedFormat('d F Y'); + + $pdfBinary = SimperPdfExporter::generate($employees, $metaLeft, $metaRight, $subtitle); + $fileName = 'Laporan_Daftar_Simper_' . now()->format('Ymd_Hi') . '.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', + ]); + } + /** * Simpan data karyawan baru beserta izin SIMPER (Form modal tambah karyawan). */ diff --git a/app/Http/Controllers/Pg/SecurityGuardController.php b/app/Http/Controllers/Pg/SecurityGuardController.php index 05bfe07..bea5fa2 100644 --- a/app/Http/Controllers/Pg/SecurityGuardController.php +++ b/app/Http/Controllers/Pg/SecurityGuardController.php @@ -6,18 +6,21 @@ use App\Http\Controllers\Controller; use App\Models\Gate; use App\Models\SecurityGuard; use App\Models\User; +use App\Services\PgTablePdfExporter; +use App\Services\SimpleXlsxExporter; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\View\View; +use Symfony\Component\HttpFoundation\Response; class SecurityGuardController extends Controller { /** - * Tampilkan daftar petugas Satpam beserta daftar pos gerbang. + * Bangun query petugas Satpam berdasarkan filter request. */ - public function index(Request $request): View + protected function getGuardsQuery(Request $request) { $query = SecurityGuard::with(['gate', 'user']); @@ -43,7 +46,16 @@ class SecurityGuardController extends Controller $query->where('gate_id', (int) $request->input('gate_id')); } - $guards = $query->orderBy('team') + return $query; + } + + /** + * Tampilkan daftar petugas Satpam beserta daftar pos gerbang. + */ + public function index(Request $request): View + { + $guards = $this->getGuardsQuery($request) + ->orderBy('team') ->orderBy('name') ->paginate(20) ->withQueryString(); @@ -53,6 +65,147 @@ class SecurityGuardController extends Controller return view('pg.guards_index', compact('guards', 'gates')); } + /** + * Ekspor data petugas Satpam ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $guards = $this->getGuardsQuery($request) + ->orderBy('team') + ->orderBy('name') + ->get(); + + $filters = []; + if ($request->filled('search')) { + $filters[] = "Pencarian: \"{$request->input('search')}\""; + } + if ($request->filled('team')) { + $filters[] = "Regu {$request->input('team')}"; + } + if ($request->filled('gate_id')) { + $gate = Gate::find($request->input('gate_id')); + $filters[] = "Pos: " . ($gate ? $gate->name : 'ID ' . $request->input('gate_id')); + } + $filterDesc = empty($filters) ? 'Semua Petugas Satpam' : implode(' | ', $filters); + + $metaLines = [ + 'Sistem: Modul Private Guard (PG) - PT Kerinci Merangin Hidro', + 'Filter: ' . $filterDesc, + 'Tanggal Cetak: ' . now()->translatedFormat('d F Y H:i') . ' WIB', + 'Total Data: ' . $guards->count() . ' Personil Satpam', + ]; + + $headers = [ + 'No' => 6, + 'ID Satpam' => 16, + 'Nama Lengkap' => 28, + 'Regu' => 14, + 'Penempatan Pos' => 24, + 'Status' => 14, + 'Username Akun' => 18, + ]; + + $rows = []; + foreach ($guards as $idx => $g) { + $badge = $g->badge_id ?? ('SEC-' . str_pad($g->id, 3, '0', STR_PAD_LEFT)); + $rows[] = [ + $idx + 1, + $badge, + $g->name, + 'Regu ' . $g->team, + $g->gate ? $g->gate->name : 'Belum Ditentukan', + $g->is_active ? 'Aktif' : 'Nonaktif', + $g->user ? $g->user->username : ($g->badge_id ?? '-'), + ]; + } + + $alignments = ['center', 'center', 'left', 'center', 'left', 'center', 'center']; + $xlsxContent = SimpleXlsxExporter::create('DATA PETUGAS SATPAM - PT KMH', $metaLines, $headers, $rows, $alignments); + + $fileName = 'data_satpam_' . date('Ymd_His') . '.xlsx'; + + return response($xlsxContent, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Cache-Control' => 'max-age=0', + ]); + } + + /** + * Ekspor data petugas Satpam ke format PDF (preview langsung di browser). + */ + public function exportPdf(Request $request): Response + { + $guards = $this->getGuardsQuery($request) + ->orderBy('team') + ->orderBy('name') + ->get(); + + $teamDesc = $request->filled('team') ? 'Regu ' . $request->input('team') : 'Semua Regu'; + $gateDesc = 'Semua Penempatan'; + if ($request->filled('gate_id')) { + $gate = Gate::find($request->input('gate_id')); + $gateDesc = $gate ? $gate->name : 'ID ' . $request->input('gate_id'); + } + + $metaLeft = [ + 'Modul' => 'Data Petugas Satpam Lapangan', + 'Filter Regu' => $teamDesc, + 'Pos Gerbang' => $gateDesc, + ]; + + if ($request->filled('search')) { + $metaLeft['Pencarian'] = '"' . $request->input('search') . '"'; + } + + $metaRight = [ + 'Tanggal Cetak' => now()->translatedFormat('d M Y, H:i') . ' WIB', + 'Total Personil' => $guards->count() . ' Orang', + 'Dicetak Oleh' => auth()->user()->name ?? 'Administrator PG', + ]; + + $columns = [ + ['title' => 'NO', 'width' => 12, 'align' => 'C', 'bold' => true], + ['title' => 'ID SATPAM', 'width' => 32, 'align' => 'C', 'bold' => true], + ['title' => 'NAMA LENGKAP', 'width' => 70, 'align' => 'L', 'bold' => true, 'max_char' => 38], + ['title' => 'REGU', 'width' => 28, 'align' => 'C', 'is_status' => true], + ['title' => 'PENEMPATAN POS', 'width' => 65, 'align' => 'L', 'max_char' => 34], + ['title' => 'STATUS', 'width' => 28, 'align' => 'C', 'is_status' => true], + ['title' => 'USERNAME AKUN', 'width' => 32, 'align' => 'C'], + ]; + + $rows = []; + foreach ($guards as $idx => $g) { + $badge = $g->badge_id ?? ('SEC-' . str_pad($g->id, 3, '0', STR_PAD_LEFT)); + $rows[] = [ + $idx + 1, + $badge, + $g->name, + 'Regu ' . $g->team, + $g->gate ? $g->gate->name : 'Belum Ditentukan', + $g->is_active ? 'Aktif' : 'Nonaktif', + $g->user ? $g->user->username : ($g->badge_id ?? '-'), + ]; + } + + $pdfContent = PgTablePdfExporter::generate( + 'Laporan Data Petugas Satpam', + 'Rekapitulasi Personil Jaga & Penempatan Pos Gerbang', + 'MODUL PRIVATE GUARD (PG) - RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'laporan_data_satpam_' . date('Ymd_His') . '.pdf'; + + return response($pdfContent, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="' . $fileName . '"', + ]); + } + /** * Simpan data petugas Satpam baru dan otomatis buatkan akun login pos. */ diff --git a/app/Http/Controllers/Pg/VerificationLogController.php b/app/Http/Controllers/Pg/VerificationLogController.php index 02eb4ef..b4fc650 100644 --- a/app/Http/Controllers/Pg/VerificationLogController.php +++ b/app/Http/Controllers/Pg/VerificationLogController.php @@ -6,16 +6,19 @@ use App\Http\Controllers\Controller; use App\Models\Gate; use App\Models\SecurityGuard; use App\Models\VehicleActivity; +use App\Services\PgTablePdfExporter; +use App\Services\SimpleXlsxExporter; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\View\View; +use Symfony\Component\HttpFoundation\Response; class VerificationLogController extends Controller { /** - * Tampilkan rekapitulasi audit dan log riwayat verifikasi gerbang oleh petugas Satpam. + * Bangun query log verifikasi gerbang berdasarkan filter request. */ - public function index(Request $request): View + protected function getVerificationLogsQuery(Request $request) { $query = VehicleActivity::with(['vehicle', 'driver', 'gate', 'securityGuard']) ->orderByRaw('COALESCE(validated_at, recorded_at) DESC'); @@ -86,10 +89,229 @@ class VerificationLogController extends Controller }); } - $activities = $query->paginate(20)->withQueryString(); + return $query; + } + + /** + * Tampilkan rekapitulasi audit dan log riwayat verifikasi gerbang oleh petugas Satpam. + */ + public function index(Request $request): View + { + $activities = $this->getVerificationLogsQuery($request)->paginate(20)->withQueryString(); $gates = Gate::where('is_active', true)->orderBy('name')->get(); $guards = SecurityGuard::orderBy('name')->get(); + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + return view('pg.verification_logs', compact('activities', 'gates', 'guards', 'startDate', 'endDate')); } + + /** + * Ekspor data log verifikasi gerbang ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $activities = $this->getVerificationLogsQuery($request)->get(); + + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + $period = ($startDate && $endDate) ? "{$startDate} s/d {$endDate}" : ($startDate ? "Sejak {$startDate}" : 'Semua Periode'); + + $filters = ["Periode: {$period}"]; + if ($request->filled('team')) { + $filters[] = "Regu {$request->input('team')}"; + } + if ($request->filled('security_guard_id')) { + $guard = SecurityGuard::find($request->input('security_guard_id')); + $filters[] = "Satpam: " . ($guard ? $guard->name : 'ID ' . $request->input('security_guard_id')); + } + if ($request->filled('gate_id')) { + $gate = Gate::find($request->input('gate_id')); + $filters[] = "Pos: " . ($gate ? $gate->name : 'ID ' . $request->input('gate_id')); + } + if ($request->filled('direction')) { + $filters[] = "Arah: " . ($request->input('direction') === 'in' ? 'Masuk' : 'Keluar'); + } + if ($request->filled('status')) { + $filters[] = "Status: " . ucfirst($request->input('status')); + } + if ($request->filled('search')) { + $filters[] = "Pencarian: \"{$request->input('search')}\""; + } + + $metaLines = [ + 'Sistem: Modul Private Guard (PG) - PT Kerinci Merangin Hidro', + 'Filter: ' . implode(' | ', $filters), + 'Tanggal Cetak: ' . now()->translatedFormat('d F Y H:i') . ' WIB', + 'Total Data: ' . $activities->count() . ' Riwayat Perlintasan Gerbang', + ]; + + $headers = [ + 'No' => 6, + 'Waktu Verifikasi' => 20, + 'No. Transaksi' => 20, + 'Petugas Satpam' => 24, + 'Regu' => 12, + 'Pos Gerbang' => 20, + 'Plat Nomor' => 16, + 'Merek & Tipe' => 24, + 'Driver' => 24, + 'NIK Driver' => 16, + 'Arah' => 12, + 'Odometer (KM)' => 16, + 'Jarak (KM)' => 14, + 'Status' => 14, + 'Catatan Tolak' => 28, + ]; + + $rows = []; + foreach ($activities as $idx => $item) { + $validatedTime = $item->validated_at ?? $item->recorded_at; + $waktu = $validatedTime ? $validatedTime->format('d/m/Y H:i') : '-'; + $satpam = $item->securityGuard ? $item->securityGuard->name : '-'; + $regu = $item->securityGuard ? 'Regu ' . $item->securityGuard->team : '-'; + $pos = $item->gate ? $item->gate->name : '-'; + $plat = $item->vehicle ? $item->vehicle->license_plate : '-'; + $merek = $item->vehicle ? ($item->vehicle->brand_type . ' (' . $item->vehicle->code . ')') : '-'; + $driver = $item->driver ? $item->driver->name : '-'; + $nik = $item->driver ? ($item->driver->nik ?? '-') : '-'; + $arah = ($item->direction === 'in') ? 'Masuk' : 'Keluar'; + $status = match($item->validation_status) { + 'approved' => 'Disetujui', + 'rejected' => 'Ditolak', + default => 'Menunggu', + }; + + $rows[] = [ + $idx + 1, + $waktu, + $item->transaction_no, + $satpam, + $regu, + $pos, + $plat, + $merek, + $driver, + $nik, + $arah, + (int) $item->current_km, + $item->distance > 0 ? (int) $item->distance : 0, + $status, + $item->rejection_note ?? '-', + ]; + } + + $alignments = ['center', 'center', 'center', 'left', 'center', 'left', 'center', 'left', 'left', 'center', 'center', 'right', 'right', 'center', 'left']; + $xlsxContent = SimpleXlsxExporter::create('LOG AKTIVITAS GERBANG - PT KMH', $metaLines, $headers, $rows, $alignments); + + $fileName = 'log_aktivitas_gerbang_' . date('Ymd_His') . '.xlsx'; + + return response($xlsxContent, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Cache-Control' => 'max-age=0', + ]); + } + + /** + * Ekspor data log verifikasi gerbang ke format PDF (preview langsung di browser). + */ + public function exportPdf(Request $request): Response + { + $activities = $this->getVerificationLogsQuery($request)->get(); + + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + $period = ($startDate && $endDate) ? "{$startDate} s/d {$endDate}" : ($startDate ? "Sejak {$startDate}" : 'Semua Periode'); + + $gateDesc = 'Semua Pos'; + if ($request->filled('gate_id')) { + $gate = Gate::find($request->input('gate_id')); + $gateDesc = $gate ? $gate->name : 'ID ' . $request->input('gate_id'); + } + + $metaLeft = [ + 'Modul' => 'Log Verifikasi Pos Gerbang', + 'Periode Tanggal' => $period, + 'Pos Gerbang' => $gateDesc, + ]; + + if ($request->filled('team')) { + $metaLeft['Regu Satpam'] = 'Regu ' . $request->input('team'); + } + + if ($request->filled('direction')) { + $metaLeft['Arah Gerbang'] = ($request->input('direction') === 'in') ? 'Masuk' : 'Keluar'; + } + + $metaRight = [ + 'Tanggal Cetak' => now()->translatedFormat('d M Y, H:i') . ' WIB', + 'Total Transaksi' => $activities->count() . ' Record', + 'Dicetak Oleh' => auth()->user()->name ?? 'Administrator PG', + ]; + + $columns = [ + ['title' => 'NO', 'width' => 9, 'align' => 'C', 'bold' => true], + ['title' => 'WAKTU', 'width' => 26, 'align' => 'C'], + ['title' => 'NO. TRANSAKSI', 'width' => 28, 'align' => 'C', 'bold' => true], + ['title' => 'PETUGAS SATPAM', 'width' => 34, 'align' => 'L', 'max_char' => 20], + ['title' => 'POS GERBANG', 'width' => 28, 'align' => 'L', 'max_char' => 16], + ['title' => 'KENDARAAN', 'width' => 35, 'align' => 'L', 'max_char' => 20], + ['title' => 'DRIVER / NIK', 'width' => 35, 'align' => 'L', 'max_char' => 20], + ['title' => 'ARAH', 'width' => 16, 'align' => 'C', 'is_status' => true], + ['title' => 'ODOMETER', 'width' => 22, 'align' => 'R'], + ['title' => 'STATUS', 'width' => 34, 'align' => 'C', 'is_status' => true, 'max_char' => 22], + ]; + + $rows = []; + foreach ($activities as $idx => $item) { + $validatedTime = $item->validated_at ?? $item->recorded_at; + $waktu = $validatedTime ? $validatedTime->format('d/m/Y H:i') : '-'; + $satpam = $item->securityGuard ? $item->securityGuard->name : '-'; + $pos = $item->gate ? $item->gate->name : '-'; + $kendaraan = $item->vehicle ? ($item->vehicle->license_plate . ' (' . $item->vehicle->code . ')') : '-'; + $driver = $item->driver ? ($item->driver->name . ' - ' . ($item->driver->nik ?? '')) : '-'; + $arah = ($item->direction === 'in') ? 'Masuk' : 'Keluar'; + $status = match($item->validation_status) { + 'approved' => 'Disetujui', + 'rejected' => 'Ditolak' . ($item->rejection_note ? ' (' . $item->rejection_note . ')' : ''), + default => 'Menunggu', + }; + $odometer = number_format($item->current_km ?? 0, 0, ',', '.') . ' KM'; + + $rows[] = [ + $idx + 1, + $waktu, + $item->transaction_no, + $satpam, + $pos, + $kendaraan, + $driver, + $arah, + $odometer, + $status, + ]; + } + + $pdfContent = PgTablePdfExporter::generate( + 'Laporan Log Riwayat Verifikasi Gerbang', + 'Rekapitulasi Audit Lalu Lintas Kendaraan Masuk & Keluar Pos Gerbang', + 'MODUL PRIVATE GUARD (PG) - RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'log_verifikasi_gerbang_' . date('Ymd_His') . '.pdf'; + + return response($pdfContent, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="' . $fileName . '"', + ]); + } } diff --git a/app/Http/Controllers/Qma/ActivityLogController.php b/app/Http/Controllers/Qma/ActivityLogController.php index 25734f3..1b965a2 100644 --- a/app/Http/Controllers/Qma/ActivityLogController.php +++ b/app/Http/Controllers/Qma/ActivityLogController.php @@ -5,21 +5,25 @@ namespace App\Http\Controllers\Qma; use App\Http\Controllers\Controller; use App\Models\Gate; use App\Models\VehicleActivity; +use App\Services\QmaTablePdfExporter; +use App\Services\SimpleXlsxExporter; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; +use Illuminate\Http\Response; use Illuminate\View\View; class ActivityLogController extends Controller { /** - * Tampilkan Log Aktivitas QMA 10 Kolom lengkap dengan filter tanggal dan gate. + * Helper query builder untuk log aktivitas kendaraan dengan seluruh filter aktif. */ - public function index(Request $request): View + private function getFilteredActivityQuery(Request $request): Builder { $query = VehicleActivity::with(['vehicle', 'driver', 'gate', 'securityGuard']) ->latest('recorded_at'); - // Filter Rentang Tanggal (Default Hari Ini) + // Filter Rentang Tanggal (Default Hari Ini jika tidak diisi) $today = Carbon::today()->toDateString(); $startDate = $request->input('start_date', $today); $endDate = $request->input('end_date', $today); @@ -64,12 +68,225 @@ class ActivityLogController extends Controller $query->where('validation_status', $request->input('status')); } - $activities = $query->paginate(20)->withQueryString(); + return $query; + } + + /** + * Tampilkan Log Aktivitas QMA 10 Kolom lengkap dengan filter tanggal dan gate. + */ + public function index(Request $request): View + { + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + + $activities = $this->getFilteredActivityQuery($request)->paginate(20)->withQueryString(); $gates = Gate::where('is_active', true)->orderBy('name')->get(); return view('qma.activity_log', compact('activities', 'gates', 'startDate', 'endDate')); } + /** + * Ekspor Log Aktivitas Kendaraan (Timesheet LV) ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $activities = $this->getFilteredActivityQuery($request)->get(); + + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + + $gateText = 'Semua Gerbang'; + if ($request->filled('gate_id')) { + $gateObj = Gate::find($request->input('gate_id')); + if ($gateObj) $gateText = $gateObj->name; + } + + $dirText = $request->filled('direction') ? ($request->input('direction') === 'in' ? 'Masuk (In)' : 'Keluar (Out)') : 'Semua Arah'; + $statusText = $request->filled('status') ? ($request->input('status') === 'approved' ? 'Disetujui PG' : 'Menunggu PG') : 'Semua Status'; + $printedAt = now()->translatedFormat('d F Y, H:i'); + + $metaLines = [ + 'Periode: ' . Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y') . + ' | Gerbang: ' . $gateText . ' | Arah: ' . $dirText . ' | Status: ' . $statusText, + 'Total Data: ' . $activities->count() . ' Catatan Pergerakan | Tanggal Dicetak: ' . $printedAt . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Tanggal & Waktu' => 20, + 'Kode LV' => 14, + 'Unit Kendaraan' => 28, + 'No. Polisi' => 16, + 'Penanggung Jawab' => 22, + 'Pengemudi (Driver)' => 26, + 'Pos Gerbang' => 20, + 'Arah' => 12, + 'KM Lalu' => 14, + 'KM Kini' => 14, + 'Selisih KM' => 14, + 'Aktivitas / Keperluan' => 34, + 'Status PG' => 18, + 'Petugas Security' => 22, + ]; + + $rows = []; + foreach ($activities as $idx => $act) { + $formattedDate = $act->recorded_at ? $act->recorded_at->translatedFormat('d/m/Y H:i') . ' WIB' : '-'; + $vehicleCode = $act->vehicle?->code ?: '-'; + $vehicleUnit = $act->vehicle?->brand_type ?: '-'; + $plat = $act->vehicle?->license_plate ?: '-'; + $dept = $act->vehicle?->department ?: ($act->vehicle?->division ?: '-'); + $driverName = $act->driver ? $act->driver->name . ' (' . $act->driver->nik . ')' : '-'; + $gateName = $act->gate?->name ?: '-'; + $direction = strtoupper($act->direction ?: '-'); + $prevKm = $act->previous_km !== null ? number_format($act->previous_km, 0, ',', '.') : '-'; + $currKm = $act->current_km !== null ? number_format($act->current_km, 0, ',', '.') : '-'; + $diffKm = $act->distance !== null ? number_format($act->distance, 0, ',', '.') : '-'; + $purpose = $act->purpose ?: '-'; + $statusPg = $act->validation_status === 'approved' ? 'Disetujui' : ($act->validation_status === 'rejected' ? 'Ditolak' : 'Menunggu PG'); + $guard = $act->securityGuard?->name ?: '-'; + + $rows[] = [ + $idx + 1, + $formattedDate, + $vehicleCode, + $vehicleUnit, + $plat, + $dept, + $driverName, + $gateName, + $direction, + $prevKm, + $currKm, + $diffKm, + $purpose, + $statusPg, + $guard, + ]; + } + + $alignments = ['center', 'center', 'center', 'left', 'center', 'left', 'left', 'center', 'center', 'right', 'right', 'right', 'left', 'center', 'left']; + $title = 'LAPORAN TIMESHEET & LOG AKTIVITAS LIGHT VEHICLE - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Timesheet_LV_' . now()->format('Ymd_Hi') . '.xlsx'; + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor Log Aktivitas Kendaraan (Timesheet LV) ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportPdf(Request $request): Response + { + $activities = $this->getFilteredActivityQuery($request)->get(); + + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + + $gateText = 'Semua Gerbang'; + if ($request->filled('gate_id')) { + $gateObj = Gate::find($request->input('gate_id')); + if ($gateObj) $gateText = $gateObj->name; + } + + $dirText = $request->filled('direction') ? ($request->input('direction') === 'in' ? 'Masuk (In)' : 'Keluar (Out)') : 'Semua Arah'; + $statusText = $request->filled('status') ? ($request->input('status') === 'approved' ? 'Disetujui PG' : 'Menunggu PG') : 'Semua Status'; + $dateRangeStr = Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y'); + + $totalKm = $activities->sum('distance'); + $inCount = $activities->where('direction', 'in')->count(); + $outCount = $activities->where('direction', 'out')->count(); + + $metaLeft = [ + 'Periode Tanggal' => $dateRangeStr, + 'Pos Gerbang' => $gateText, + 'Arah / Status' => "Arah: {$dirText} | Status: {$statusText}", + ]; + + $metaRight = [ + 'Total Catatan' => $activities->count() . ' Pergerakan Armada', + 'Total Jarak Tempuh' => number_format($totalKm, 1, ',', '.') . ' KM', + 'Rincian Arah' => "{$inCount} Masuk, {$outCount} Keluar", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 8, 'align' => 'C'], + ['title' => 'TANGGAL & JAM', 'width' => 25, 'align' => 'C'], + ['title' => 'KODE LV', 'width' => 16, 'align' => 'C', 'bold' => true], + ['title' => 'UNIT KENDARAAN', 'width' => 34, 'align' => 'L', 'max_char' => 22], + ['title' => 'DRIVER (PENGEMUDI)', 'width' => 30, 'align' => 'L', 'max_char' => 18], + ['title' => 'GERBANG', 'width' => 22, 'align' => 'C', 'max_char' => 14], + ['title' => 'AKSES', 'width' => 16, 'align' => 'C', 'is_status' => true], + ['title' => 'KM LALU', 'width' => 18, 'align' => 'R'], + ['title' => 'KM KINI', 'width' => 18, 'align' => 'R'], + ['title' => 'JARAK', 'width' => 16, 'align' => 'R'], + ['title' => 'AKTIVITAS / KEPERLUAN', 'width' => 42, 'align' => 'L', 'max_char' => 30], + ['title' => 'STATUS PG', 'width' => 22, 'align' => 'C', 'is_status' => true], + ]; + + $rows = []; + foreach ($activities as $idx => $act) { + $formattedDate = $act->recorded_at ? $act->recorded_at->translatedFormat('d/m/y H:i') : '-'; + $vehicleCode = $act->vehicle?->code ?: '-'; + $vehicleUnit = $act->vehicle?->brand_type ?: '-'; + $driverName = $act->driver?->name ?: '-'; + $gateName = $act->gate?->name ?: '-'; + $direction = strtoupper($act->direction ?: '-'); + $prevKm = $act->previous_km !== null ? number_format($act->previous_km, 0, ',', '.') : '-'; + $currKm = $act->current_km !== null ? number_format($act->current_km, 0, ',', '.') : '-'; + $diffKm = $act->distance !== null ? number_format($act->distance, 0, ',', '.') . ' KM' : '-'; + $purpose = $act->purpose ?: '-'; + $statusPg = $act->validation_status === 'approved' ? 'Disetujui' : ($act->validation_status === 'rejected' ? 'Ditolak' : 'Menunggu PG'); + + $rows[] = [ + $idx + 1, + $formattedDate, + $vehicleCode, + $vehicleUnit, + $driverName, + $gateName, + $direction, + $prevKm, + $currKm, + $diffKm, + $purpose, + $statusPg, + ]; + } + + $title = 'Laporan Timesheet & Aktivitas Light Vehicle (LV)'; + $subtitle = 'Log Pergerakan Armada Gerbang Proyek KMH - Periode: ' . $dateRangeStr; + $pdfBinary = QmaTablePdfExporter::generate( + $title, + $subtitle, + 'LOG AKTIVITAS RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_Timesheet_LV_' . now()->format('Ymd_Hi') . '.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', + ]); + } + /** * Tampilkan Summary Aktivitas Kendaraan (Rekapitulasi Armada, Driver, Pos Gerbang & Statistik). */ @@ -173,4 +390,265 @@ class ActivityLogController extends Controller 'gates' )); } + + /** + * Ekspor Rekapitulasi Summary Aktivitas Kendaraan ke format Excel (.xlsx). + */ + public function exportSummaryExcel(Request $request): Response + { + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + $type = $request->input('type'); + $gateId = $request->input('gate_id'); + + $query = VehicleActivity::query(); + + if ($startDate && $endDate) { + $start = Carbon::parse($startDate)->startOfDay(); + $end = Carbon::parse($endDate)->endOfDay(); + $query->whereBetween('recorded_at', [$start, $end]); + } elseif ($startDate) { + $query->where('recorded_at', '>=', Carbon::parse($startDate)->startOfDay()); + } elseif ($endDate) { + $query->where('recorded_at', '<=', Carbon::parse($endDate)->endOfDay()); + } + + if ($request->filled('gate_id')) { + $query->where('gate_id', $gateId); + } + + if ($request->filled('type')) { + $type = $request->input('type'); + $query->whereHas('vehicle', function ($q) use ($type) { + if ($type === 'lv' || $type === 'light_vehicle') { + $q->where('category', 'light_vehicle'); + } elseif ($type === 'support' || $type === 'unit_support') { + $q->where('category', 'unit_support'); + } + }); + } + + $vehicleSummaries = (clone $query) + ->selectRaw("vehicle_id, COUNT(*) as total_trips, SUM(CASE WHEN direction = 'in' THEN 1 ELSE 0 END) as in_trips, SUM(CASE WHEN direction = 'out' THEN 1 ELSE 0 END) as out_trips, SUM(distance) as total_km") + ->groupBy('vehicle_id') + ->with('vehicle') + ->orderByDesc('total_km') + ->get(); + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $vehicleSummaries = $vehicleSummaries->filter(function ($item) use ($search) { + $veh = $item->vehicle; + if (!$veh) return false; + $haystack = strtolower(($veh->code ?? '') . ' ' . ($veh->brand_type ?? '') . ' ' . ($veh->license_plate ?? '') . ' ' . ($veh->ownership ?? '') . ' ' . ($veh->division ?? '')); + return str_contains($haystack, strtolower($search)); + })->values(); + } + + $gateText = 'Semua Gerbang'; + if ($request->filled('gate_id')) { + $g = Gate::find($gateId); + if ($g) $gateText = $g->name; + } + + $typeText = 'Semua Armada'; + if ($type === 'lv' || $type === 'light_vehicle') $typeText = 'Light Vehicle'; + elseif ($type === 'support' || $type === 'unit_support') $typeText = 'Unit Support'; + + $totalKmAll = $vehicleSummaries->sum('total_km'); + $totalTripsAll = $vehicleSummaries->sum('total_trips'); + $dateRangeStr = Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y'); + $printedAt = now()->translatedFormat('d F Y, H:i'); + + $metaLines = [ + 'Periode: ' . $dateRangeStr . ' | Kategori Armada: ' . $typeText . ' | Gerbang: ' . $gateText . + ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total: ' . $vehicleSummaries->count() . ' Unit Aktif | Akumulasi Trip: ' . number_format($totalTripsAll, 0, ',', '.') . ' Trip | Total Jarak: ' . number_format($totalKmAll, 1, ',', '.') . ' KM | Dicetak: ' . $printedAt . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode Unit' => 16, + 'Unit / Merek' => 30, + 'No. Polisi' => 16, + 'Kategori' => 18, + 'Penanggung Jawab' => 24, + 'Divisi' => 20, + 'Trip Masuk' => 14, + 'Trip Keluar' => 14, + 'Total Trip' => 14, + 'Total Jarak (KM)' => 18, + 'Odometer Terkini' => 18, + ]; + + $rows = []; + foreach ($vehicleSummaries as $idx => $vs) { + $veh = $vs->vehicle; + $rows[] = [ + $idx + 1, + $veh?->code ?: '-', + $veh?->brand_type ?: '-', + $veh?->license_plate ?: '-', + $veh?->isLightVehicle() ? 'Light Vehicle' : 'Unit Support', + $veh?->ownership ?: '-', + $veh?->division ?: ($veh?->department ?: '-'), + (int) $vs->in_trips, + (int) $vs->out_trips, + (int) $vs->total_trips, + number_format($vs->total_km, 1, ',', '.'), + $veh?->current_km !== null ? number_format($veh->current_km, 0, ',', '.') . ' KM' : '-', + ]; + } + + $alignments = ['center', 'center', 'left', 'center', 'center', 'left', 'left', 'center', 'center', 'center', 'right', 'right']; + $title = 'LAPORAN REKAPITULASI SUMMARY AKTIVITAS PER KENDARAAN - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Summary_Aktivitas_Kendaraan_' . now()->format('Ymd_Hi') . '.xlsx'; + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor Rekapitulasi Summary Aktivitas Kendaraan ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportSummaryPdf(Request $request): Response + { + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', $today); + $endDate = $request->input('end_date', $today); + $type = $request->input('type'); + $gateId = $request->input('gate_id'); + + $query = VehicleActivity::query(); + + if ($startDate && $endDate) { + $start = Carbon::parse($startDate)->startOfDay(); + $end = Carbon::parse($endDate)->endOfDay(); + $query->whereBetween('recorded_at', [$start, $end]); + } elseif ($startDate) { + $query->where('recorded_at', '>=', Carbon::parse($startDate)->startOfDay()); + } elseif ($endDate) { + $query->where('recorded_at', '<=', Carbon::parse($endDate)->endOfDay()); + } + + if ($request->filled('gate_id')) { + $query->where('gate_id', $gateId); + } + + if ($request->filled('type')) { + $type = $request->input('type'); + $query->whereHas('vehicle', function ($q) use ($type) { + if ($type === 'lv' || $type === 'light_vehicle') { + $q->where('category', 'light_vehicle'); + } elseif ($type === 'support' || $type === 'unit_support') { + $q->where('category', 'unit_support'); + } + }); + } + + $vehicleSummaries = (clone $query) + ->selectRaw("vehicle_id, COUNT(*) as total_trips, SUM(CASE WHEN direction = 'in' THEN 1 ELSE 0 END) as in_trips, SUM(CASE WHEN direction = 'out' THEN 1 ELSE 0 END) as out_trips, SUM(distance) as total_km") + ->groupBy('vehicle_id') + ->with('vehicle') + ->orderByDesc('total_km') + ->get(); + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $vehicleSummaries = $vehicleSummaries->filter(function ($item) use ($search) { + $veh = $item->vehicle; + if (!$veh) return false; + $haystack = strtolower(($veh->code ?? '') . ' ' . ($veh->brand_type ?? '') . ' ' . ($veh->license_plate ?? '') . ' ' . ($veh->ownership ?? '') . ' ' . ($veh->division ?? '')); + return str_contains($haystack, strtolower($search)); + })->values(); + } + + $gateText = 'Semua Gerbang'; + if ($request->filled('gate_id')) { + $g = Gate::find($gateId); + if ($g) $gateText = $g->name; + } + + $typeText = 'Semua Armada'; + if ($type === 'lv' || $type === 'light_vehicle') $typeText = 'Light Vehicle'; + elseif ($type === 'support' || $type === 'unit_support') $typeText = 'Unit Support'; + + $totalKmAll = $vehicleSummaries->sum('total_km'); + $totalTripsAll = $vehicleSummaries->sum('total_trips'); + $dateRangeStr = Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y'); + + $metaLeft = [ + 'Periode Tanggal' => $dateRangeStr, + 'Kategori Armada' => $typeText, + 'Pos Gerbang' => $gateText, + ]; + + $metaRight = [ + 'Armada Beroperasi' => $vehicleSummaries->count() . ' Unit Aktif', + 'Akumulasi Trip' => number_format($totalTripsAll, 0, ',', '.') . ' Pergerakan', + 'Total Jarak Tempuh' => number_format($totalKmAll, 1, ',', '.') . ' KM', + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE UNIT', 'width' => 22, 'align' => 'C', 'bold' => true], + ['title' => 'UNIT / MEREK', 'width' => 48, 'align' => 'L', 'max_char' => 30], + ['title' => 'NO. POLISI', 'width' => 22, 'align' => 'C'], + ['title' => 'KATEGORI', 'width' => 26, 'align' => 'C'], + ['title' => 'PENANGGUNG JAWAB', 'width' => 40, 'align' => 'L', 'max_char' => 26], + ['title' => 'MASUK', 'width' => 18, 'align' => 'C'], + ['title' => 'KELUAR', 'width' => 18, 'align' => 'C'], + ['title' => 'TOTAL TRIP', 'width' => 20, 'align' => 'C', 'bold' => true], + ['title' => 'TOTAL JARAK', 'width' => 25, 'align' => 'R', 'bold' => true], + ['title' => 'ODOMETER', 'width' => 18, 'align' => 'R'], + ]; + + $rows = []; + foreach ($vehicleSummaries as $idx => $vs) { + $veh = $vs->vehicle; + $rows[] = [ + $idx + 1, + $veh?->code ?: '-', + $veh?->brand_type ?: '-', + $veh?->license_plate ?: '-', + $veh?->isLightVehicle() ? 'Light Vehicle' : 'Unit Support', + $veh?->ownership ?: '-', + (int) $vs->in_trips, + (int) $vs->out_trips, + (int) $vs->total_trips, + number_format($vs->total_km, 1, ',', '.') . ' KM', + $veh?->current_km !== null ? number_format($veh->current_km, 0, ',', '.') : '-', + ]; + } + + $title = 'Laporan Summary Aktivitas per Armada Kendaraan'; + $subtitle = 'Rekapitulasi Pergerakan, Frekuensi Trip, dan Jarak Tempuh - Periode: ' . $dateRangeStr; + $pdfBinary = QmaTablePdfExporter::generate( + $title, + $subtitle, + 'SUMMARY AKTIVITAS RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_Summary_Aktivitas_Kendaraan_' . now()->format('Ymd_Hi') . '.pdf'; + + return response($pdfBinary, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="' . $fileName . '"', + 'Content-Length' => strlen($pdfBinary), + 'Cache-Control' => 'private, max-age=0, must-revalidate', + 'Pragma' => 'public', + ]); + } } diff --git a/app/Http/Controllers/Qma/P2hInspectionController.php b/app/Http/Controllers/Qma/P2hInspectionController.php index ad26439..232f9df 100644 --- a/app/Http/Controllers/Qma/P2hInspectionController.php +++ b/app/Http/Controllers/Qma/P2hInspectionController.php @@ -5,18 +5,22 @@ namespace App\Http\Controllers\Qma; use App\Http\Controllers\Controller; use App\Models\P2hRecord; use App\Models\Vehicle; +use App\Services\QmaTablePdfExporter; +use App\Services\SimpleXlsxExporter; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Http\Response; use Illuminate\Support\Facades\Auth; use Illuminate\View\View; class P2hInspectionController extends Controller { /** - * Tampilkan riwayat dan log pemeriksaan P2H Unit Support untuk Admin QMA. + * Helper query builder untuk riwayat pemeriksaan P2H Unit Support dengan filter aktif. */ - public function index(Request $request): View + private function getFilteredP2hQuery(Request $request): Builder { $query = P2hRecord::with(['vehicle', 'employee', 'template', 'validator']); @@ -45,7 +49,15 @@ class P2hInspectionController extends Controller }); } - $records = $query->orderByDesc('inspected_at')->paginate(15)->withQueryString(); + return $query->orderByDesc('inspected_at'); + } + + /** + * Tampilkan riwayat dan log pemeriksaan P2H Unit Support untuk Admin QMA. + */ + public function index(Request $request): View + { + $records = $this->getFilteredP2hQuery($request)->paginate(15)->withQueryString(); // Statistik Ringkasan P2H $totalP2h = P2hRecord::count(); @@ -64,6 +76,191 @@ class P2hInspectionController extends Controller )); } + /** + * Ekspor Riwayat Pemeriksaan P2H Unit Support ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $records = $this->getFilteredP2hQuery($request)->get(); + + $dateFilter = $request->filled('date') ? Carbon::parse($request->input('date'))->translatedFormat('d F Y') : 'Semua Tanggal'; + $statusFilter = $request->filled('validation_status') ? + ($request->input('validation_status') === 'approved' ? 'Disetujui QMA' : + ($request->input('validation_status') === 'rejected' ? 'Ditolak' : 'Menunggu Review')) : 'Semua Status'; + $condFilter = $request->filled('summary_condition') ? + ($request->input('summary_condition') === 'has_defect' ? 'Ada Kerusakan' : 'Normal') : 'Semua Kondisi'; + $printedAt = now()->translatedFormat('d F Y, H:i'); + + $metaLines = [ + 'Filter: Tanggal: ' . $dateFilter . ' | Status QMA: ' . $statusFilter . ' | Kondisi Fisik: ' . $condFilter . + ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total Data: ' . $records->count() . ' Form Pemeriksaan P2H | Tanggal Dicetak: ' . $printedAt . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Waktu Inspeksi' => 20, + 'No. Transaksi' => 22, + 'Kode Unit' => 16, + 'Kategori & Model Alat' => 30, + 'Operator (SIMPER)' => 28, + 'NIK' => 16, + 'Shift' => 14, + 'HM Awal Operasi' => 18, + 'Kondisi Fisik' => 20, + 'Jumlah Temuan' => 16, + 'Status QMA' => 20, + 'Catatan Inspeksi / Temuan' => 36, + 'Validator QMA' => 24, + ]; + + $rows = []; + foreach ($records as $idx => $rec) { + $waktu = $rec->inspected_at ? $rec->inspected_at->translatedFormat('d/m/Y H:i') . ' WIB' : '-'; + $unitCode = $rec->vehicle?->code ?: '-'; + $unitModel = $rec->vehicle?->brand_type ?: ($rec->vehicle?->unit_category ?: '-'); + $opName = $rec->employee?->name ?: '-'; + $opNik = $rec->employee?->nik ?: '-'; + $shift = $rec->shift ?: '-'; + $hm = $rec->start_hm !== null ? number_format($rec->start_hm, 1, ',', '.') . ' HM' : '-'; + $kondisi = $rec->hasDefects() ? 'Ada Kerusakan (' . $rec->defect_count . ' Item)' : 'Normal (Baik)'; + $defectCount = $rec->defect_count ?: '0'; + $statusQma = $rec->isApproved() ? 'Disetujui QMA' : ($rec->isRejected() ? 'Ditolak' : 'Menunggu Review'); + $notes = $rec->general_notes ?: ($rec->validation_notes ?: '-'); + $validator = $rec->validator?->name ?: '-'; + + $rows[] = [ + $idx + 1, + $waktu, + $rec->transaction_no ?: '-', + $unitCode, + $unitModel, + $opName, + $opNik, + $shift, + $hm, + $kondisi, + $defectCount, + $statusQma, + $notes, + $validator, + ]; + } + + $alignments = ['center', 'center', 'center', 'center', 'left', 'left', 'center', 'center', 'right', 'center', 'center', 'center', 'left', 'left']; + $title = 'LAPORAN PEMERIKSAAN HARIAN (P2H) ALAT BERAT & UNIT SUPPORT - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_P2H_Unit_Support_' . now()->format('Ymd_Hi') . '.xlsx'; + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor Riwayat Pemeriksaan P2H Unit Support ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportPdf(Request $request): Response + { + $records = $this->getFilteredP2hQuery($request)->get(); + + $dateFilter = $request->filled('date') ? Carbon::parse($request->input('date'))->translatedFormat('d F Y') : 'Semua Tanggal'; + $statusFilter = $request->filled('validation_status') ? + ($request->input('validation_status') === 'approved' ? 'Disetujui QMA' : + ($request->input('validation_status') === 'rejected' ? 'Ditolak' : 'Menunggu Review')) : 'Semua Status'; + $condFilter = $request->filled('summary_condition') ? + ($request->input('summary_condition') === 'has_defect' ? 'Ada Kerusakan' : 'Normal') : 'Semua Kondisi'; + + $approvedCount = $records->where('validation_status', 'approved')->count(); + $pendingCount = $records->where('validation_status', 'pending')->count(); + $rejectedCount = $records->where('validation_status', 'rejected')->count(); + $defectCount = $records->where('summary_condition', 'has_defect')->count(); + $normalCount = $records->where('summary_condition', '!=', 'has_defect')->count(); + + $metaLeft = [ + 'Filter Tanggal' => $dateFilter, + 'Status Approval' => $statusFilter, + 'Kondisi Fisik' => $condFilter, + ]; + + $metaRight = [ + 'Total Pemeriksaan' => $records->count() . ' Form P2H Terverifikasi', + 'Rincian Kondisi' => "{$normalCount} Normal, {$defectCount} Ada Kerusakan", + 'Rincian Status' => "{$approvedCount} Disetujui, {$pendingCount} Menunggu, {$rejectedCount} Ditolak", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 8, 'align' => 'C'], + ['title' => 'WAKTU', 'width' => 24, 'align' => 'C'], + ['title' => 'NO. TRANSAKSI', 'width' => 26, 'align' => 'C', 'bold' => true], + ['title' => 'KODE', 'width' => 16, 'align' => 'C', 'bold' => true], + ['title' => 'MODEL ALAT', 'width' => 34, 'align' => 'L', 'max_char' => 22], + ['title' => 'OPERATOR', 'width' => 32, 'align' => 'L', 'max_char' => 20], + ['title' => 'SHIFT', 'width' => 14, 'align' => 'C'], + ['title' => 'HM', 'width' => 18, 'align' => 'R'], + ['title' => 'KONDISI', 'width' => 28, 'align' => 'C', 'is_status' => true], + ['title' => 'STATUS QMA', 'width' => 25, 'align' => 'C', 'is_status' => true], + ['title' => 'VALIDATOR', 'width' => 22, 'align' => 'L', 'max_char' => 15], + ['title' => 'CATATAN', 'width' => 20, 'align' => 'L', 'max_char' => 14], + ]; + + $rows = []; + foreach ($records as $idx => $rec) { + $waktu = $rec->inspected_at ? $rec->inspected_at->translatedFormat('d/m/y H:i') : '-'; + $unitCode = $rec->vehicle?->code ?: '-'; + $unitModel = $rec->vehicle?->brand_type ?: '-'; + $opName = $rec->employee?->name ?: '-'; + $shift = $rec->shift ?: '-'; + $hm = $rec->start_hm !== null ? number_format($rec->start_hm, 1, ',', '.') : '-'; + $kondisi = $rec->hasDefects() ? 'Ada Kerusakan (' . $rec->defect_count . ')' : 'Normal (Baik)'; + $statusQma = $rec->isApproved() ? 'Disetujui QMA' : ($rec->isRejected() ? 'Ditolak' : 'Menunggu Review'); + $validator = $rec->validator?->name ?: '-'; + $notes = $rec->general_notes ?: ($rec->validation_notes ?: '-'); + + $rows[] = [ + $idx + 1, + $waktu, + $rec->transaction_no ?: '-', + $unitCode, + $unitModel, + $opName, + $shift, + $hm, + $kondisi, + $statusQma, + $validator, + $notes, + ]; + } + + $title = 'Laporan Pemeriksaan Harian (P2H) Unit Support'; + $subtitle = 'Rekapitulasi Kelaikan Alat Berat & Unit Pendukung Lapangan - PT KMH'; + $pdfBinary = QmaTablePdfExporter::generate( + $title, + $subtitle, + 'P2H UNIT SUPPORT RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_P2H_Unit_Support_' . now()->format('Ymd_Hi') . '.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', + ]); + } + /** * Tampilkan Summary Pemeriksaan P2H Unit Support (Analitik, Rekapitulasi Alat Berat & Status). */ @@ -155,6 +352,249 @@ class P2hInspectionController extends Controller )); } + /** + * Helper untuk memproses data rekapitulasi summary P2H per unit support. + */ + private function getP2hSummaryData(Request $request): array + { + $today = Carbon::today()->toDateString(); + $startDate = $request->input('start_date', Carbon::now()->startOfMonth()->toDateString()); + $endDate = $request->input('end_date', $today); + $vehicleId = $request->input('vehicle_id'); + $validationStatus = $request->input('validation_status'); + $shift = $request->input('shift'); + $search = trim($request->input('search', '')); + + $query = P2hRecord::with(['vehicle', 'employee', 'template']); + + if ($startDate && $endDate) { + $start = Carbon::parse($startDate)->startOfDay(); + $end = Carbon::parse($endDate)->endOfDay(); + $query->whereBetween('inspected_at', [$start, $end]); + } elseif ($startDate) { + $query->where('inspected_at', '>=', Carbon::parse($startDate)->startOfDay()); + } elseif ($endDate) { + $query->where('inspected_at', '<=', Carbon::parse($endDate)->endOfDay()); + } + + if ($request->filled('vehicle_id')) { + $query->where('vehicle_id', $vehicleId); + } + + if ($request->filled('validation_status')) { + $query->where('validation_status', $validationStatus); + } + + if ($request->filled('shift')) { + $query->where('shift', $shift); + } + + if ($search !== '') { + $query->where(function ($q) use ($search) { + $q->where('transaction_no', 'like', "%{$search}%") + ->orWhereHas('vehicle', fn($v) => $v->where('code', 'like', "%{$search}%")->orWhere('brand_type', 'like', "%{$search}%")) + ->orWhereHas('employee', fn($e) => $e->where('name', 'like', "%{$search}%")->orWhere('nik', 'like', "%{$search}%")); + }); + } + + $records = $query->orderByDesc('inspected_at')->get(); + + $unitSummary = $records->groupBy('vehicle_id')->map(function ($group) { + $vehicle = $group->first()->vehicle; + return [ + 'vehicle' => $vehicle, + 'total' => $group->count(), + 'approved' => $group->where('validation_status', 'approved')->count(), + 'pending' => $group->where('validation_status', 'pending')->count(), + 'rejected' => $group->where('validation_status', 'rejected')->count(), + 'has_defect' => $group->where('summary_condition', 'has_defect')->count(), + 'good' => $group->where('summary_condition', 'good')->count(), + 'latest_hm' => $group->max('start_hm'), + 'latest_inspection' => $group->max('inspected_at'), + ]; + })->sortByDesc('total'); + + return [ + 'records' => $records, + 'unitSummary' => $unitSummary, + 'startDate' => $startDate, + 'endDate' => $endDate, + ]; + } + + /** + * Ekspor Rekapitulasi Summary P2H Unit Support ke format Excel (.xlsx). + */ + public function exportSummaryExcel(Request $request): Response + { + $data = $this->getP2hSummaryData($request); + $records = $data['records']; + $unitSummary = $data['unitSummary']; + $startDate = $data['startDate']; + $endDate = $data['endDate']; + + $dateRangeStr = Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y'); + $printedAt = now()->translatedFormat('d F Y, H:i'); + + $statusFilter = $request->filled('validation_status') ? + ($request->input('validation_status') === 'approved' ? 'Disetujui QMA' : + ($request->input('validation_status') === 'rejected' ? 'Ditolak' : 'Menunggu Approval')) : 'Semua Status'; + $shiftFilter = $request->filled('shift') ? $request->input('shift') : 'Semua Shift'; + + $totalP2hAll = $records->count(); + $totalApprovedAll = $records->where('validation_status', 'approved')->count(); + $totalDefectsAll = $records->where('summary_condition', 'has_defect')->count(); + + $metaLines = [ + 'Periode: ' . $dateRangeStr . ' | Status: ' . $statusFilter . ' | Shift: ' . $shiftFilter . + ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total: ' . $unitSummary->count() . ' Unit Alat Berat | Total Form: ' . $totalP2hAll . ' P2H (' . $totalApprovedAll . ' Disetujui, ' . $totalDefectsAll . ' Ada Kerusakan) | Dicetak: ' . $printedAt . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode Unit' => 16, + 'Model & Kategori Alat' => 32, + 'Kategori' => 20, + 'Total P2H' => 14, + 'Disetujui' => 14, + 'Menunggu' => 14, + 'Ditolak' => 14, + 'Temuan Rusak' => 16, + 'HM Terakhir' => 18, + 'Terakhir Diperiksa' => 22, + ]; + + $rows = []; + $idx = 1; + foreach ($unitSummary as $us) { + $veh = $us['vehicle']; + $latestInspection = $us['latest_inspection'] ? Carbon::parse($us['latest_inspection'])->translatedFormat('d/m/Y H:i') . ' WIB' : '-'; + $hm = $us['latest_hm'] !== null ? number_format($us['latest_hm'], 1, ',', '.') . ' HM' : '-'; + + $rows[] = [ + $idx++, + $veh?->code ?: '-', + $veh?->brand_type ?: '-', + $veh?->unit_category ?: 'Alat Berat', + (int) $us['total'], + (int) $us['approved'], + (int) $us['pending'], + (int) $us['rejected'], + (int) $us['has_defect'], + $hm, + $latestInspection, + ]; + } + + $alignments = ['center', 'center', 'left', 'left', 'center', 'center', 'center', 'center', 'center', 'right', 'center']; + $title = 'LAPORAN REKAPITULASI SUMMARY P2H UNIT SUPPORT - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Summary_P2H_Unit_Support_' . now()->format('Ymd_Hi') . '.xlsx'; + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor Rekapitulasi Summary P2H Unit Support ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportSummaryPdf(Request $request): Response + { + $data = $this->getP2hSummaryData($request); + $records = $data['records']; + $unitSummary = $data['unitSummary']; + $startDate = $data['startDate']; + $endDate = $data['endDate']; + + $dateRangeStr = Carbon::parse($startDate)->translatedFormat('d M Y') . ' s/d ' . Carbon::parse($endDate)->translatedFormat('d M Y'); + + $statusFilter = $request->filled('validation_status') ? + ($request->input('validation_status') === 'approved' ? 'Disetujui QMA' : + ($request->input('validation_status') === 'rejected' ? 'Ditolak' : 'Menunggu Approval')) : 'Semua Status'; + $shiftFilter = $request->filled('shift') ? $request->input('shift') : 'Semua Shift'; + + $totalApproved = $records->where('validation_status', 'approved')->count(); + $totalPending = $records->where('validation_status', 'pending')->count(); + $totalRejected = $records->where('validation_status', 'rejected')->count(); + $totalDefects = $records->where('summary_condition', 'has_defect')->count(); + + $metaLeft = [ + 'Periode Tanggal' => $dateRangeStr, + 'Status Approval' => $statusFilter, + 'Filter Shift' => $shiftFilter, + ]; + + $metaRight = [ + 'Unit Support Aktif' => $unitSummary->count() . ' Unit Alat Berat', + 'Total Pemeriksaan' => $records->count() . ' Form P2H Terkumpul', + 'Rincian Status' => "{$totalApproved} Disetujui, {$totalPending} Menunggu, {$totalRejected} Ditolak", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE UNIT', 'width' => 24, 'align' => 'C', 'bold' => true], + ['title' => 'MODEL & KATEGORI ALAT', 'width' => 65, 'align' => 'L', 'max_char' => 42], + ['title' => 'TOTAL P2H', 'width' => 22, 'align' => 'C', 'bold' => true], + ['title' => 'DISETUJUI', 'width' => 22, 'align' => 'C', 'is_status' => true], + ['title' => 'MENUNGGU', 'width' => 22, 'align' => 'C', 'is_status' => true], + ['title' => 'DITOLAK', 'width' => 20, 'align' => 'C', 'is_status' => true], + ['title' => 'TEMUAN', 'width' => 24, 'align' => 'C', 'is_status' => true], + ['title' => 'HM TERAKHIR', 'width' => 26, 'align' => 'R'], + ['title' => 'TERAKHIR DIPERIKSA', 'width' => 32, 'align' => 'C'], + ]; + + $rows = []; + $idx = 1; + foreach ($unitSummary as $us) { + $veh = $us['vehicle']; + $latestInspection = $us['latest_inspection'] ? Carbon::parse($us['latest_inspection'])->translatedFormat('d/m/y H:i') : '-'; + $hm = $us['latest_hm'] !== null ? number_format($us['latest_hm'], 1, ',', '.') : '-'; + $modelCat = ($veh?->brand_type ?: '-') . ($veh?->unit_category ? ' (' . $veh->unit_category . ')' : ''); + + $rows[] = [ + $idx++, + $veh?->code ?: '-', + $modelCat, + (int) $us['total'], + (int) $us['approved'], + (int) $us['pending'], + (int) $us['rejected'], + (int) $us['has_defect'], + $hm, + $latestInspection, + ]; + } + + $title = 'Laporan Summary Rekapitulasi P2H Unit Support'; + $subtitle = 'Kepatuhan & Kelayakan Operasional Alat Berat Lapangan - Periode: ' . $dateRangeStr; + $pdfBinary = QmaTablePdfExporter::generate( + $title, + $subtitle, + 'SUMMARY P2H RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_Summary_P2H_Unit_Support_' . now()->format('Ymd_Hi') . '.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', + ]); + } + /** * Tampilkan detail lembar pemeriksaan P2H (seluruh section & butir jawaban). */ diff --git a/app/Http/Controllers/Qma/VehicleController.php b/app/Http/Controllers/Qma/VehicleController.php index 50ccef3..09b8cfe 100644 --- a/app/Http/Controllers/Qma/VehicleController.php +++ b/app/Http/Controllers/Qma/VehicleController.php @@ -9,9 +9,13 @@ use App\Models\P2hRecord; use App\Models\P2hTemplate; use App\Models\Vehicle; use App\Models\VehicleActivity; +use App\Services\SimpleXlsxExporter; +use App\Services\VehiclePdfExporter; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Http\Response; use Illuminate\Support\Facades\DB; use Illuminate\Validation\Rule; use Illuminate\View\View; @@ -78,9 +82,9 @@ class VehicleController extends Controller } /** - * Halaman khusus pengelolaan armada Kendaraan Ringan (Light Vehicle / LV). + * Helper query builder untuk memfilter data Light Vehicle (LV). */ - public function indexLv(Request $request): View + private function getFilteredLvQuery(Request $request): Builder { $query = Vehicle::lightVehicles(); @@ -101,7 +105,15 @@ class VehicleController extends Controller }); } - $vehicles = $query->orderBy('code')->paginate(15)->withQueryString(); + return $query->orderBy('code'); + } + + /** + * Halaman khusus pengelolaan armada Kendaraan Ringan (Light Vehicle / LV). + */ + public function indexLv(Request $request): View + { + $vehicles = $this->getFilteredLvQuery($request)->paginate(15)->withQueryString(); // Statistik Ringkasan Khusus LV $totalLv = Vehicle::lightVehicles()->count(); @@ -122,6 +134,140 @@ class VehicleController extends Controller )); } + /** + * Ekspor data Light Vehicle ke format Excel (.xlsx). + */ + public function exportLvExcel(Request $request): Response + { + $vehicles = $this->getFilteredLvQuery($request)->get(); + + $today = now()->translatedFormat('d F Y, H:i'); + $statusFilter = $request->filled('status') ? 'Status: ' . $request->input('status') : 'Semua Status Operasional'; + $searchFilter = $request->filled('search') ? 'Pencarian: "' . $request->input('search') . '"' : ''; + + $metaLines = [ + 'Filter: ' . $statusFilter . ($searchFilter ? ' | ' . $searchFilter : ''), + 'Total Data: ' . $vehicles->count() . ' Unit LV | Tanggal Dicetak: ' . $today . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode LV' => 16, + 'Merek & Tipe' => 32, + 'No. Polisi' => 18, + 'Divisi' => 24, + 'Kepemilikan' => 20, + 'Odometer (KM)' => 20, + 'Status Operasional' => 22, + ]; + + $rows = []; + foreach ($vehicles as $idx => $v) { + $odo = $v->current_km ? number_format($v->current_km, 0, ',', '.') . ' KM' : '0 KM'; + $rows[] = [ + $idx + 1, + $v->code, + $v->brand_type ?: '-', + $v->license_plate ?: '-', + $v->division ?: '-', + $v->ownership ?: '-', + $odo, + $v->status ?: 'Standby', + ]; + } + + $alignments = ['center', 'center', 'left', 'center', 'left', 'left', 'center', 'center']; + + $fileName = 'Laporan_Data_Light_Vehicle_' . now()->format('Ymd_Hi') . '.xlsx'; + $binary = SimpleXlsxExporter::create( + 'LAPORAN DATA KENDARAAN RINGAN (LIGHT VEHICLE) - PT KERINCI MERANGIN HIDRO', + $metaLines, + $headers, + $rows, + $alignments + ); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor data Light Vehicle ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportLvPdf(Request $request): Response + { + $vehicles = $this->getFilteredLvQuery($request)->get(); + + $today = now()->translatedFormat('d F Y, H:i'); + $statusFilter = $request->filled('status') ? $request->input('status') : 'Semua Status Operasional'; + + $totalOp = $vehicles->where('status', 'Operation')->count(); + $totalSt = $vehicles->where('status', 'Standby')->count(); + $totalBd = $vehicles->where('status', 'Breakdown')->count(); + + $metaLeft = [ + 'Kategori' => 'Light Vehicle (LV)', + 'Status Operasional' => $statusFilter, + 'Tanggal Cetak' => $today . ' WIB', + ]; + + $metaRight = [ + 'Total Kendaraan' => $vehicles->count() . ' Unit LV', + 'Rincian Status' => "{$totalOp} Operation, {$totalSt} Standby, {$totalBd} Breakdown", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE LV', 'width' => 25, 'align' => 'C', 'bold' => true], + ['title' => 'MEREK & TIPE', 'width' => 64, 'align' => 'L', 'bold' => true, 'max_char' => 38], + ['title' => 'NO. POLISI', 'width' => 28, 'align' => 'C'], + ['title' => 'DIVISI', 'width' => 45, 'align' => 'L', 'max_char' => 28], + ['title' => 'KEPEMILIKAN', 'width' => 35, 'align' => 'L', 'max_char' => 22], + ['title' => 'ODOMETER', 'width' => 30, 'align' => 'C'], + ['title' => 'STATUS', 'width' => 30, 'align' => 'C', 'is_status' => true], + ]; + + $rows = []; + foreach ($vehicles as $idx => $v) { + $odo = $v->current_km ? number_format($v->current_km, 0, ',', '.') . ' KM' : '0 KM'; + $rows[] = [ + $idx + 1, + $v->code, + $v->brand_type ?: '-', + $v->license_plate ?: '-', + $v->division ?: '-', + $v->ownership ?: '-', + $odo, + $v->status ?: 'Standby', + ]; + } + + $subtitle = 'Armada Kendaraan Operasional Light Vehicle - ' . now()->translatedFormat('d F Y'); + $pdfBinary = VehiclePdfExporter::generate( + 'Laporan Data Light Vehicle (LV)', + $subtitle, + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_Light_Vehicle_' . now()->format('Ymd_Hi') . '.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', + ]); + } + /** * Halaman khusus pengelolaan Kategori Kendaraan Berat (Unit Support / Alat Berat). */ @@ -282,6 +428,453 @@ class VehicleController extends Controller )); } + /** + * Helper query builder untuk unit fisik alat berat (Unit Support Physical). + */ + private function getFilteredSupportPhysicalQuery(Request $request): Builder + { + $query = Vehicle::unitSupportPhysical()->with('parent'); + + if ($request->filled('status')) { + $query->where('status', $request->input('status')); + } + + if ($request->filled('unit_category')) { + $cat = $request->input('unit_category'); + $query->where(function ($q) use ($cat) { + $q->where('unit_category', $cat) + ->orWhereHas('parent', fn ($pq) => $pq->where('unit_category', $cat)); + }); + } + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function ($q) use ($search) { + $q->where('code', 'like', "%{$search}%") + ->orWhere('serial_number', 'like', "%{$search}%") + ->orWhere('brand_type', 'like', "%{$search}%") + ->orWhere('unit_category', 'like', "%{$search}%") + ->orWhere('location', 'like', "%{$search}%") + ->orWhere('license_plate', 'like', "%{$search}%") + ->orWhereHas('parent', function ($pq) use ($search) { + $pq->where('code', 'like', "%{$search}%") + ->orWhere('unit_category', 'like', "%{$search}%") + ->orWhere('brand_type', 'like', "%{$search}%"); + }); + }); + } + + return $query->orderBy('code'); + } + + /** + * Helper query builder untuk master kategori Unit Support. + */ + private function getFilteredSupportCategoriesQuery(Request $request): Builder + { + $query = Vehicle::unitSupportCategories()->withCount('units'); + + if ($request->filled('status')) { + $query->where('status', $request->input('status')); + } + + if ($request->filled('unit_category')) { + $query->where('unit_category', $request->input('unit_category')); + } + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function ($q) use ($search) { + $q->where('code', 'like', "%{$search}%") + ->orWhere('brand_type', 'like', "%{$search}%") + ->orWhere('unit_category', 'like', "%{$search}%") + ->orWhere('location', 'like', "%{$search}%") + ->orWhere('division', 'like', "%{$search}%"); + }); + } + + return $query->orderBy('code'); + } + + /** + * Ekspor data Unit Support ke format Excel (.xlsx). + */ + public function exportSupportExcel(Request $request): Response + { + $hasPhysical = Vehicle::unitSupportPhysical()->exists(); + $today = now()->translatedFormat('d F Y, H:i'); + + if ($hasPhysical) { + $units = $this->getFilteredSupportPhysicalQuery($request)->get(); + + $metaLines = [ + 'Filter: ' . ($request->filled('status') ? 'Status: ' . $request->input('status') : 'Semua Status') . + ($request->filled('unit_category') ? ' | Kategori: ' . $request->input('unit_category') : '') . + ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total Data: ' . $units->count() . ' Unit Fisik Alat Berat | Tanggal Dicetak: ' . $today . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode Unit' => 16, + 'Kategori Alat' => 28, + 'No. Seri / Rangka' => 24, + 'Tahun' => 12, + 'No. Polisi' => 18, + 'Lokasi Kerja' => 24, + 'Odometer (HM/KM)' => 20, + 'Dokumen Izin' => 20, + 'Status Operasional' => 22, + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $categoryName = $u->parent?->unit_category ?: ($u->parent?->brand_type ?: ($u->unit_category ?: 'Unit Support')); + $odo = $u->current_km ? number_format($u->current_km, 0, ',', '.') . ' HM' : '0 HM'; + $docs = trim(($u->silo_document ? 'SILO ' : '') . ($u->kir_document ? 'KIR ' : '')) ?: '-'; + + $rows[] = [ + $idx + 1, + $u->code, + $categoryName, + $u->serial_number ?: '-', + $u->production_year ?: '-', + $u->license_plate ?: '-', + $u->location ?: '-', + $odo, + $docs, + $u->status ?: 'Standby', + ]; + } + + $alignments = ['center', 'center', 'left', 'left', 'center', 'center', 'left', 'center', 'center', 'center']; + $title = 'LAPORAN DAFTAR UNIT FISIK ALAT BERAT (UNIT SUPPORT) - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Unit_Support_Lengkap_' . now()->format('Ymd_Hi') . '.xlsx'; + } else { + // Fallback ke master kategori jika unit fisik belum diinput + $categories = $this->getFilteredSupportCategoriesQuery($request)->get(); + + $metaLines = [ + 'Filter: ' . ($request->filled('status') ? 'Status: ' . $request->input('status') : 'Semua Status') . + ($request->filled('unit_category') ? ' | Kategori: ' . $request->input('unit_category') : ''), + 'Total Data: ' . $categories->count() . ' Kategori Alat Berat | Tanggal Dicetak: ' . $today . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode Kategori' => 16, + 'Kategori Alat Berat' => 30, + 'Merek & Tipe Model' => 30, + 'Total Unit Fisik' => 18, + 'Lokasi Operasional' => 24, + 'Status Operasional' => 22, + ]; + + $rows = []; + foreach ($categories as $idx => $cat) { + $rows[] = [ + $idx + 1, + $cat->code, + $cat->unit_category ?: $cat->brand_type, + $cat->brand_type ?: '-', + $cat->units_count . ' Unit', + $cat->location ?: '-', + $cat->status ?: 'Standby', + ]; + } + + $alignments = ['center', 'center', 'left', 'left', 'center', 'left', 'center']; + $title = 'LAPORAN MASTER KATEGORI ALAT BERAT (UNIT SUPPORT) - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Kategori_Unit_Support_' . now()->format('Ymd_Hi') . '.xlsx'; + } + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor data Unit Support ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportSupportPdf(Request $request): Response + { + $hasPhysical = Vehicle::unitSupportPhysical()->exists(); + $today = now()->translatedFormat('d F Y, H:i'); + $statusFilter = $request->filled('status') ? $request->input('status') : 'Semua Status Operasional'; + + if ($hasPhysical) { + $units = $this->getFilteredSupportPhysicalQuery($request)->get(); + + $totalOp = $units->where('status', 'Operation')->count(); + $totalSt = $units->where('status', 'Standby')->count(); + $totalBd = $units->where('status', 'Breakdown')->count(); + + $metaLeft = [ + 'Kategori' => 'Unit Support (Alat Berat Fisik)', + 'Status Operasional' => $statusFilter, + 'Tanggal Cetak' => $today . ' WIB', + ]; + + $metaRight = [ + 'Total Unit Fisik' => $units->count() . ' Unit Alat Berat', + 'Rincian Status' => "{$totalOp} Operation, {$totalSt} Standby, {$totalBd} Breakdown", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE UNIT', 'width' => 24, 'align' => 'C', 'bold' => true], + ['title' => 'KATEGORI ALAT', 'width' => 45, 'align' => 'L', 'bold' => true, 'max_char' => 26], + ['title' => 'NO. SERI / RANGKA', 'width' => 42, 'align' => 'L', 'max_char' => 24], + ['title' => 'THN', 'width' => 14, 'align' => 'C'], + ['title' => 'NO. POLISI', 'width' => 24, 'align' => 'C'], + ['title' => 'LOKASI KERJA', 'width' => 50, 'align' => 'L', 'max_char' => 28], + ['title' => 'ODOMETER', 'width' => 28, 'align' => 'C'], + ['title' => 'STATUS', 'width' => 30, 'align' => 'C', 'is_status' => true], + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $categoryName = $u->parent?->unit_category ?: ($u->parent?->brand_type ?: ($u->unit_category ?: 'Unit Support')); + $odo = $u->current_km ? number_format($u->current_km, 0, ',', '.') . ' HM' : '0 HM'; + + $rows[] = [ + $idx + 1, + $u->code, + $categoryName, + $u->serial_number ?: '-', + $u->production_year ?: '-', + $u->license_plate ?: '-', + $u->location ?: '-', + $odo, + $u->status ?: 'Standby', + ]; + } + + $title = 'Laporan Data Unit Support (Alat Berat)'; + $subtitle = 'Daftar Seluruh Unit Fisik Alat Berat Lapangan - ' . now()->translatedFormat('d F Y'); + $fileName = 'Laporan_Unit_Support_' . now()->format('Ymd_Hi') . '.pdf'; + } else { + $categories = $this->getFilteredSupportCategoriesQuery($request)->get(); + + $totalOp = $categories->where('status', 'Operation')->count(); + $totalSt = $categories->where('status', 'Standby')->count(); + $totalBd = $categories->where('status', 'Breakdown')->count(); + + $metaLeft = [ + 'Kategori' => 'Master Kategori Unit Support', + 'Status Operasional' => $statusFilter, + 'Tanggal Cetak' => $today . ' WIB', + ]; + + $metaRight = [ + 'Total Kategori' => $categories->count() . ' Kategori Alat', + 'Rincian Status' => "{$totalOp} Operation, {$totalSt} Standby, {$totalBd} Breakdown", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE', 'width' => 25, 'align' => 'C', 'bold' => true], + ['title' => 'KATEGORI ALAT BERAT', 'width' => 64, 'align' => 'L', 'bold' => true, 'max_char' => 38], + ['title' => 'MEREK & MODEL', 'width' => 55, 'align' => 'L', 'max_char' => 32], + ['title' => 'TOTAL UNIT', 'width' => 28, 'align' => 'C', 'bold' => true], + ['title' => 'LOKASI OPERASIONAL', 'width' => 55, 'align' => 'L', 'max_char' => 32], + ['title' => 'STATUS', 'width' => 30, 'align' => 'C', 'is_status' => true], + ]; + + $rows = []; + foreach ($categories as $idx => $cat) { + $rows[] = [ + $idx + 1, + $cat->code, + $cat->unit_category ?: $cat->brand_type, + $cat->brand_type ?: '-', + $cat->units_count . ' Unit', + $cat->location ?: '-', + $cat->status ?: 'Standby', + ]; + } + + $title = 'Laporan Master Kategori Unit Support'; + $subtitle = 'Master 28 Kategori Alat Berat Proyek KMH - ' . now()->translatedFormat('d F Y'); + $fileName = 'Laporan_Kategori_Unit_Support_' . now()->format('Ymd_Hi') . '.pdf'; + } + + $pdfBinary = VehiclePdfExporter::generate($title, $subtitle, $metaLeft, $metaRight, $columns, $rows); + + 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', + ]); + } + + /** + * Ekspor data unit fisik khusus kategori tertentu ke format Excel (.xlsx). + */ + public function exportSupportUnitsExcel(Request $request, int $id): Response + { + $category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id); + $query = $category->units(); + + if ($request->filled('status')) { + $query->where('status', $request->input('status')); + } + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function ($q) use ($search) { + $q->where('code', 'like', "%{$search}%") + ->orWhere('serial_number', 'like', "%{$search}%") + ->orWhere('license_plate', 'like', "%{$search}%") + ->orWhere('location', 'like', "%{$search}%"); + }); + } + + $units = $query->orderBy('code')->get(); + $today = now()->translatedFormat('d F Y, H:i'); + + $metaLines = [ + 'Kategori: ' . ($category->unit_category ?: $category->brand_type) . ' (' . $category->code . ')' . + ($request->filled('status') ? ' | Status: ' . $request->input('status') : '') . + ($request->filled('search') ? ' | Pencarian: "' . $request->input('search') . '"' : ''), + 'Total Data: ' . $units->count() . ' Unit Fisik | Tanggal Dicetak: ' . $today . ' WIB', + ]; + + $headers = [ + 'No' => 6, + 'Kode Unit' => 16, + 'No. Seri / Rangka' => 24, + 'Tahun' => 12, + 'No. Polisi' => 18, + 'Lokasi Kerja' => 24, + 'Odometer (HM/KM)' => 20, + 'Dokumen Izin' => 20, + 'Status Operasional' => 22, + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $odo = $u->current_km ? number_format($u->current_km, 0, ',', '.') . ' HM' : '0 HM'; + $docs = trim(($u->silo_document ? 'SILO ' : '') . ($u->kir_document ? 'KIR ' : '')) ?: '-'; + + $rows[] = [ + $idx + 1, + $u->code, + $u->serial_number ?: '-', + $u->production_year ?: '-', + $u->license_plate ?: '-', + $u->location ?: '-', + $odo, + $docs, + $u->status ?: 'Standby', + ]; + } + + $alignments = ['center', 'center', 'left', 'center', 'center', 'left', 'center', 'center', 'center']; + $title = 'LAPORAN UNIT FISIK ' . strtoupper($category->unit_category ?: $category->brand_type) . ' - PT KERINCI MERANGIN HIDRO'; + $fileName = 'Laporan_Unit_' . preg_replace('/[^A-Za-z0-9_-]/', '_', $category->code) . '_' . now()->format('Ymd_Hi') . '.xlsx'; + + $binary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, $alignments); + + return response($binary, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($binary), + 'Cache-Control' => 'max-age=0, no-cache, no-store, must-revalidate', + 'Pragma' => 'public', + ]); + } + + /** + * Ekspor data unit fisik khusus kategori tertentu ke format PDF (Pratinjau Asli dengan Logo PT KMH). + */ + public function exportSupportUnitsPdf(Request $request, int $id): Response + { + $category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id); + $query = $category->units(); + + if ($request->filled('status')) { + $query->where('status', $request->input('status')); + } + + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function ($q) use ($search) { + $q->where('code', 'like', "%{$search}%") + ->orWhere('serial_number', 'like', "%{$search}%") + ->orWhere('license_plate', 'like', "%{$search}%") + ->orWhere('location', 'like', "%{$search}%"); + }); + } + + $units = $query->orderBy('code')->get(); + $today = now()->translatedFormat('d F Y, H:i'); + $statusFilter = $request->filled('status') ? $request->input('status') : 'Semua Status Operasional'; + + $totalOp = $units->where('status', 'Operation')->count(); + $totalSt = $units->where('status', 'Standby')->count(); + $totalBd = $units->where('status', 'Breakdown')->count(); + + $metaLeft = [ + 'Kategori Alat' => ($category->unit_category ?: $category->brand_type) . ' (' . $category->code . ')', + 'Status Operasional' => $statusFilter, + 'Tanggal Cetak' => $today . ' WIB', + ]; + + $metaRight = [ + 'Total Unit Fisik' => $units->count() . ' Unit Terdaftar', + 'Rincian Status' => "{$totalOp} Operation, {$totalSt} Standby, {$totalBd} Breakdown", + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C'], + ['title' => 'KODE UNIT', 'width' => 28, 'align' => 'C', 'bold' => true], + ['title' => 'NO. SERI / RANGKA', 'width' => 50, 'align' => 'L', 'max_char' => 30], + ['title' => 'TAHUN', 'width' => 18, 'align' => 'C'], + ['title' => 'NO. POLISI', 'width' => 28, 'align' => 'C'], + ['title' => 'LOKASI KERJA', 'width' => 65, 'align' => 'L', 'max_char' => 38], + ['title' => 'ODOMETER', 'width' => 34, 'align' => 'C'], + ['title' => 'STATUS', 'width' => 34, 'align' => 'C', 'is_status' => true], + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $odo = $u->current_km ? number_format($u->current_km, 0, ',', '.') . ' HM' : '0 HM'; + $rows[] = [ + $idx + 1, + $u->code, + $u->serial_number ?: '-', + $u->production_year ?: '-', + $u->license_plate ?: '-', + $u->location ?: '-', + $odo, + $u->status ?: 'Standby', + ]; + } + + $title = 'Laporan Unit Fisik ' . ($category->unit_category ?: $category->brand_type); + $subtitle = 'Kategori ' . $category->code . ' - ' . now()->translatedFormat('d F Y'); + $fileName = 'Laporan_Unit_' . preg_replace('/[^A-Za-z0-9_-]/', '_', $category->code) . '_' . now()->format('Ymd_Hi') . '.pdf'; + + $pdfBinary = VehiclePdfExporter::generate($title, $subtitle, $metaLeft, $metaRight, $columns, $rows); + + 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', + ]); + } + /** * Simpan penambahan unit fisik baru di bawah kategori Unit Support tertentu. */ diff --git a/app/Services/PgTablePdfExporter.php b/app/Services/PgTablePdfExporter.php new file mode 100644 index 0000000..84fdc7b --- /dev/null +++ b/app/Services/PgTablePdfExporter.php @@ -0,0 +1,207 @@ + 'NO', 'width' => 10, 'align' => 'C', 'bold' => true, 'max_char' => 20, 'is_status' => true], ...] + public int $totalRows = 0; + public string $logoPath = ''; + + public function Header(): void + { + // 1. Logo Perusahaan di Kiri Atas + if (!empty($this->logoPath) && file_exists($this->logoPath)) { + $this->Image($this->logoPath, 15, 10, 44); + } else { + $this->SetXY(15, 10); + $this->SetFont('Arial', 'B', 14); + $this->SetTextColor(27, 94, 32); + $this->Cell(60, 8, 'KERINCI HYDROPOWER', 0, 0, 'L'); + } + + // 2. Branding Sistem di Kanan Atas + $this->SetXY(170, 10); + $this->SetFont('Arial', 'B', 18); + $this->SetTextColor(27, 94, 32); // #1b5e20 Green + $this->Cell(112, 6, 'RKM-KMH', 0, 1, 'R'); + + $this->SetXY(170, 16); + $this->SetFont('Arial', 'B', 7.5); + $this->SetTextColor(71, 85, 105); // #475569 Slate + $this->Cell(112, 4, 'KERINCI HYDROPOWER 350 MW', 0, 1, 'R'); + + // 3. Banner Biru Gelap Navy (#06213f) + $this->SetY(24); + $this->SetFillColor(6, 33, 63); + $this->Rect(15, 24, 267, 16, 'F'); + + // Teks Judul di Kiri Banner + $this->SetXY(18, 26); + $this->SetFont('Arial', 'B', 13); + $this->SetTextColor(255, 255, 255); + $this->Cell(140, 6, $this->reportTitle, 0, 1, 'L'); + + $this->SetXY(18, 32); + $this->SetFont('Arial', '', 8); + $this->SetTextColor(203, 213, 225); // #cbd5e1 Slate + $this->Cell(140, 5, $this->subtitle, 0, 1, 'L'); + + // Teks Sub-sistem di Kanan Banner + $this->SetXY(160, 26); + $this->SetFont('Arial', 'B', 9); + $this->SetTextColor(255, 255, 255); + $this->Cell(119, 6, $this->systemTitle, 0, 1, 'R'); + + $this->SetXY(160, 32); + $this->SetFont('Arial', 'I', 7.5); + $this->SetTextColor(203, 213, 225); + $this->Cell(119, 5, 'Dicetak otomatis dari sistem', 0, 1, 'R'); + + // 4. Bagian Ringkasan Metadata (2 Kolom) + $metaY = 44; + $this->SetTextColor(51, 65, 85); + + // Kolom Kiri + foreach ($this->metaLeft as $k => $v) { + $this->SetXY(15, $metaY); + $this->SetFont('Arial', '', 8); + $this->Cell(32, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(85, 4.5, (string) $v, 0, 1); + $metaY += 5; + } + + // Kolom Kanan + $metaY2 = 44; + foreach ($this->metaRight as $k => $v) { + $this->SetXY(165, $metaY2); + $this->SetFont('Arial', '', 8); + $this->Cell(34, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(78, 4.5, (string) $v, 0, 1); + $metaY2 += 5; + } + + // Garis Pembatas Tipis + $divY = max($metaY, $metaY2) + 2; + $this->SetDrawColor(226, 232, 240); + $this->Line(15, $divY, 282, $divY); + + // 5. Header Tabel Solid Navy + $tableY = $divY + 3; + $this->SetXY(15, $tableY); + $this->SetFillColor(6, 33, 63); + $this->SetTextColor(255, 255, 255); + $this->SetFont('Arial', 'B', 7.5); + + foreach ($this->columns as $col) { + $this->Cell($col['width'], 7.5, $col['title'], 0, 0, $col['align'] ?? 'L', true); + } + $this->Ln(); + } + + public function Footer(): void + { + $this->SetY(-12); + $this->SetFont('Arial', '', 7.5); + $this->SetTextColor(148, 163, 184); + $this->Cell( + 180, + 5, + 'Menampilkan ' . $this->totalRows . ' data - Dokumen ini digenerate secara otomatis oleh Sistem RKM-KMH pada ' . now()->translatedFormat('d F Y') . '.', + 0, + 0, + 'L' + ); + $this->Cell(87, 5, 'Halaman ' . $this->PageNo() . ' dari {nb}', 0, 0, 'R'); + } + + /** + * Helper pembuatan file PDF seragam untuk seluruh modul tabel PG. + */ + public static function generate( + string $title, + string $subtitle, + string $systemTitle, + array $metaLeft, + array $metaRight, + array $columns, + array $rows + ): string { + $pdf = new self('L', 'mm', 'A4'); + $pdf->AliasNbPages(); + $pdf->reportTitle = $title; + $pdf->subtitle = $subtitle; + $pdf->systemTitle = $systemTitle; + $pdf->metaLeft = $metaLeft; + $pdf->metaRight = $metaRight; + $pdf->columns = $columns; + $pdf->totalRows = count($rows); + $pdf->logoPath = public_path('images/logo-kerinci.png'); + + $pdf->SetMargins(15, 10, 15); + $pdf->AddPage(); + $pdf->SetAutoPageBreak(true, 15); + + $fill = false; + foreach ($rows as $r) { + $pdf->SetFillColor(248, 250, 252); + $pdf->SetDrawColor(241, 245, 249); + $pdf->SetTextColor(15, 23, 42); + + foreach ($columns as $idx => $col) { + $val = (string) ($r[$idx] ?? '-'); + $align = $col['align'] ?? 'L'; + $width = $col['width']; + $isBold = !empty($col['bold']); + $isStatus = !empty($col['is_status']); + + if ($isStatus) { + $valLower = strtolower($val); + if (str_contains($valLower, 'nonaktif')) { + $pdf->SetTextColor(100, 116, 139); // Slate Gray #64748b + } elseif (str_contains($valLower, 'disetujui') || str_contains($valLower, 'approved') || str_contains($valLower, 'aktif') || str_contains($valLower, 'masuk') || $valLower === 'in') { + $pdf->SetTextColor(4, 120, 87); // Emerald Green #047857 + } elseif (str_contains($valLower, 'menunggu') || str_contains($valLower, 'pending') || str_contains($valLower, 'regu 2')) { + $pdf->SetTextColor(180, 83, 9); // Amber #b45309 + } elseif (str_contains($valLower, 'ditolak') || str_contains($valLower, 'rejected')) { + $pdf->SetTextColor(190, 18, 60); // Rose Red #be123c + } elseif (str_contains($valLower, 'keluar') || $valLower === 'out' || str_contains($valLower, 'regu 1')) { + $pdf->SetTextColor(29, 78, 216); // Blue #1d4ed8 + } elseif (str_contains($valLower, 'regu 3')) { + $pdf->SetTextColor(126, 34, 206); // Purple #7e22ce + } else { + $pdf->SetTextColor(100, 116, 139); + } + $pdf->SetFont('Arial', 'B', 7.5); + } else { + $pdf->SetTextColor(15, 23, 42); + $pdf->SetFont('Arial', $isBold ? 'B' : '', 7.5); + } + + $maxChar = !empty($col['max_char']) ? $col['max_char'] : 0; + if ($maxChar > 0 && mb_strlen($val) > $maxChar) { + $val = mb_strimwidth($val, 0, $maxChar, '...'); + } + + $displayVal = ($align === 'L' && !empty($val) && $val !== '-') ? ' ' . $val : $val; + $pdf->Cell($width, 6.5, $displayVal, 'B', 0, $align, $fill); + } + + $pdf->Ln(); + $fill = !$fill; + } + + return $pdf->Output('S'); + } +} diff --git a/app/Services/QmaTablePdfExporter.php b/app/Services/QmaTablePdfExporter.php new file mode 100644 index 0000000..cf74f53 --- /dev/null +++ b/app/Services/QmaTablePdfExporter.php @@ -0,0 +1,207 @@ + 'NO', 'width' => 10, 'align' => 'C', 'bold' => true, 'max_char' => 20, 'is_status' => true], ...] + public int $totalRows = 0; + public string $logoPath = ''; + + public function Header(): void + { + // 1. Logo Perusahaan di Kiri Atas + if (!empty($this->logoPath) && file_exists($this->logoPath)) { + $this->Image($this->logoPath, 15, 10, 44); + } else { + $this->SetXY(15, 10); + $this->SetFont('Arial', 'B', 14); + $this->SetTextColor(27, 94, 32); + $this->Cell(60, 8, 'KERINCI HYDROPOWER', 0, 0, 'L'); + } + + // 2. Branding Sistem di Kanan Atas + $this->SetXY(170, 10); + $this->SetFont('Arial', 'B', 18); + $this->SetTextColor(27, 94, 32); // #1b5e20 Green + $this->Cell(112, 6, 'RKM-KMH', 0, 1, 'R'); + + $this->SetXY(170, 16); + $this->SetFont('Arial', 'B', 7.5); + $this->SetTextColor(71, 85, 105); // #475569 Slate + $this->Cell(112, 4, 'KERINCI HYDROPOWER 350 MW', 0, 1, 'R'); + + // 3. Banner Biru Gelap Navy + $this->SetY(24); + $this->SetFillColor(6, 33, 63); // #06213f Dark Navy + $this->Rect(15, 24, 267, 16, 'F'); + + // Teks Judul di Kiri Banner + $this->SetXY(18, 26); + $this->SetFont('Arial', 'B', 13); + $this->SetTextColor(255, 255, 255); + $this->Cell(140, 6, $this->reportTitle, 0, 1, 'L'); + + $this->SetXY(18, 32); + $this->SetFont('Arial', '', 8); + $this->SetTextColor(203, 213, 225); // #cbd5e1 Slate + $this->Cell(140, 5, $this->subtitle, 0, 1, 'L'); + + // Teks Sub-sistem di Kanan Banner + $this->SetXY(160, 26); + $this->SetFont('Arial', 'B', 9); + $this->SetTextColor(255, 255, 255); + $this->Cell(119, 6, $this->systemTitle, 0, 1, 'R'); + + $this->SetXY(160, 32); + $this->SetFont('Arial', 'I', 7.5); + $this->SetTextColor(203, 213, 225); + $this->Cell(119, 5, 'Dicetak otomatis dari sistem', 0, 1, 'R'); + + // 4. Bagian Ringkasan Metadata (2 Kolom) + $metaY = 44; + $this->SetTextColor(51, 65, 85); + + // Kolom Kiri + foreach ($this->metaLeft as $k => $v) { + $this->SetXY(15, $metaY); + $this->SetFont('Arial', '', 8); + $this->Cell(32, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(85, 4.5, (string) $v, 0, 1); + $metaY += 5; + } + + // Kolom Kanan + $metaY2 = 44; + foreach ($this->metaRight as $k => $v) { + $this->SetXY(165, $metaY2); + $this->SetFont('Arial', '', 8); + $this->Cell(34, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(78, 4.5, (string) $v, 0, 1); + $metaY2 += 5; + } + + // Garis Pembatas Tipis + $divY = max($metaY, $metaY2) + 2; + $this->SetDrawColor(226, 232, 240); + $this->Line(15, $divY, 282, $divY); + + // 5. Header Tabel Solid Navy + $tableY = $divY + 3; + $this->SetXY(15, $tableY); + $this->SetFillColor(6, 33, 63); + $this->SetTextColor(255, 255, 255); + $this->SetFont('Arial', 'B', 7.5); + + foreach ($this->columns as $col) { + $this->Cell($col['width'], 7.5, $col['title'], 0, 0, $col['align'] ?? 'L', true); + } + $this->Ln(); + } + + public function Footer(): void + { + $this->SetY(-12); + $this->SetFont('Arial', '', 7.5); + $this->SetTextColor(148, 163, 184); + $this->Cell( + 180, + 5, + 'Menampilkan ' . $this->totalRows . ' data - Dokumen ini digenerate secara otomatis oleh Sistem RKM-KMH pada ' . now()->translatedFormat('d F Y') . '.', + 0, + 0, + 'L' + ); + $this->Cell(87, 5, 'Halaman ' . $this->PageNo() . ' dari {nb}', 0, 0, 'R'); + } + + /** + * Helper pembuatan file PDF seragam untuk seluruh modul tabel QMA. + */ + public static function generate( + string $title, + string $subtitle, + string $systemTitle, + array $metaLeft, + array $metaRight, + array $columns, + array $rows + ): string { + $pdf = new self('L', 'mm', 'A4'); + $pdf->AliasNbPages(); + $pdf->reportTitle = $title; + $pdf->subtitle = $subtitle; + $pdf->systemTitle = $systemTitle; + $pdf->metaLeft = $metaLeft; + $pdf->metaRight = $metaRight; + $pdf->columns = $columns; + $pdf->totalRows = count($rows); + $pdf->logoPath = public_path('images/logo-kerinci.png'); + + $pdf->SetMargins(15, 10, 15); + $pdf->AddPage(); + $pdf->SetAutoPageBreak(true, 15); + + $fill = false; + foreach ($rows as $r) { + $pdf->SetFillColor(248, 250, 252); + $pdf->SetDrawColor(241, 245, 249); + $pdf->SetTextColor(15, 23, 42); + + foreach ($columns as $idx => $col) { + $val = (string) ($r[$idx] ?? '-'); + $align = $col['align'] ?? 'L'; + $width = $col['width']; + $isBold = !empty($col['bold']); + $isStatus = !empty($col['is_status']); + + if ($isStatus) { + $valLower = strtolower($val); + if (str_contains($valLower, 'disetujui') || str_contains($valLower, 'approved') || str_contains($valLower, 'operation') || str_contains($valLower, 'normal') || str_contains($valLower, 'baik')) { + $pdf->SetTextColor(4, 120, 87); // Green #047857 + } elseif (str_contains($valLower, 'menunggu') || str_contains($valLower, 'pending') || str_contains($valLower, 'standby')) { + $pdf->SetTextColor(180, 83, 9); // Amber #b45309 + } elseif (str_contains($valLower, 'ditolak') || str_contains($valLower, 'rejected') || str_contains($valLower, 'breakdown') || str_contains($valLower, 'rusak') || str_contains($valLower, 'defect')) { + $pdf->SetTextColor(190, 18, 60); // Rose Red #be123c + } elseif (str_contains($valLower, 'masuk') || $valLower === 'in') { + $pdf->SetTextColor(4, 120, 87); // Green + } elseif (str_contains($valLower, 'keluar') || $valLower === 'out') { + $pdf->SetTextColor(29, 78, 216); // Blue #1d4ed8 + } elseif (str_contains($valLower, 'maintenance')) { + $pdf->SetTextColor(2, 132, 199); // Sky blue + } else { + $pdf->SetTextColor(100, 116, 139); + } + $pdf->SetFont('Arial', 'B', 7.5); + } else { + $pdf->SetTextColor(15, 23, 42); + $pdf->SetFont('Arial', $isBold ? 'B' : '', 7.5); + } + + $maxChar = !empty($col['max_char']) ? $col['max_char'] : 0; + if ($maxChar > 0 && mb_strlen($val) > $maxChar) { + $val = mb_strimwidth($val, 0, $maxChar, '...'); + } + + $displayVal = ($align === 'L' && !empty($val) && $val !== '-') ? ' ' . $val : $val; + $pdf->Cell($width, 6.5, $displayVal, 'B', 0, $align, $fill); + } + + $pdf->Ln(); + $fill = !$fill; + } + + return $pdf->Output('S'); + } +} diff --git a/app/Services/SimperPdfExporter.php b/app/Services/SimperPdfExporter.php new file mode 100644 index 0000000..338d4e0 --- /dev/null +++ b/app/Services/SimperPdfExporter.php @@ -0,0 +1,227 @@ +logoPath) && file_exists($this->logoPath)) { + $this->Image($this->logoPath, 15, 10, 44); + } else { + $this->SetXY(15, 10); + $this->SetFont('Arial', 'B', 14); + $this->SetTextColor(27, 94, 32); + $this->Cell(60, 8, 'KERINCI HYDROPOWER', 0, 0, 'L'); + } + + // 2. Branding Sistem di Kanan Atas + $this->SetXY(170, 10); + $this->SetFont('Arial', 'B', 18); + $this->SetTextColor(27, 94, 32); // #1b5e20 Green + $this->Cell(112, 6, 'RKM-KMH', 0, 1, 'R'); + + $this->SetXY(170, 16); + $this->SetFont('Arial', 'B', 7.5); + $this->SetTextColor(71, 85, 105); // #475569 Slate + $this->Cell(112, 4, 'KERINCI HYDROPOWER 350 MW', 0, 1, 'R'); + + // 3. Banner Biru Gelap Navy (Sesuai Referensi it.allrole.web.id) + $this->SetY(24); + $this->SetFillColor(6, 33, 63); // #06213f Dark Navy + $this->Rect(15, 24, 267, 16, 'F'); + + // Teks Judul di Kiri Banner + $this->SetXY(18, 26); + $this->SetFont('Arial', 'B', 13); + $this->SetTextColor(255, 255, 255); + $this->Cell(140, 6, $this->reportTitle, 0, 1, 'L'); + + $this->SetXY(18, 32); + $this->SetFont('Arial', '', 8); + $this->SetTextColor(203, 213, 225); // #cbd5e1 Slate + $this->Cell(140, 5, $this->subtitle, 0, 1, 'L'); + + // Teks Sub-sistem di Kanan Banner + $this->SetXY(160, 26); + $this->SetFont('Arial', 'B', 9); + $this->SetTextColor(255, 255, 255); + $this->Cell(119, 6, 'SISTEM KENDARAAN RKM-KMH', 0, 1, 'R'); + + $this->SetXY(160, 32); + $this->SetFont('Arial', 'I', 7.5); + $this->SetTextColor(203, 213, 225); + $this->Cell(119, 5, 'Dicetak otomatis dari sistem', 0, 1, 'R'); + + // 4. Bagian Ringkasan Metadata (2 Kolom) + $metaY = 44; + $this->SetTextColor(51, 65, 85); + + // Kolom Kiri + foreach ($this->metaLeft as $k => $v) { + $this->SetXY(15, $metaY); + $this->SetFont('Arial', '', 8); + $this->Cell(28, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(85, 4.5, $v, 0, 1); + $metaY += 5; + } + + // Kolom Kanan + $metaY2 = 44; + foreach ($this->metaRight as $k => $v) { + $this->SetXY(175, $metaY2); + $this->SetFont('Arial', '', 8); + $this->Cell(28, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(74, 4.5, $v, 0, 1); + $metaY2 += 5; + } + + // Garis Pembatas Tipis + $divY = max($metaY, $metaY2) + 2; + $this->SetDrawColor(226, 232, 240); + $this->Line(15, $divY, 282, $divY); + + // 5. Header Tabel Solid Navy + $tableY = $divY + 3; + $this->SetXY(15, $tableY); + $this->SetFillColor(6, 33, 63); + $this->SetTextColor(255, 255, 255); + $this->SetFont('Arial', 'B', 7.5); + + $cols = [ + ['NO', 10, 'C'], + ['NIK', 30, 'C'], + ['NAMA KARYAWAN', 62, 'L'], + ['JABATAN', 45, 'L'], + ['UNIT / DIVISI', 40, 'L'], + ['STATUS DRIVER', 26, 'C'], + ['MASA BERLAKU', 26, 'C'], + ['STATUS SIMPER', 28, 'C'], + ]; + + foreach ($cols as $col) { + $this->Cell($col[1], 7.5, $col[0], 0, 0, $col[2], true); + } + $this->Ln(); + } + + public function Footer(): void + { + $this->SetY(-12); + $this->SetFont('Arial', '', 7.5); + $this->SetTextColor(148, 163, 184); + $this->Cell( + 180, + 5, + 'Menampilkan ' . $this->totalRows . ' data - Dokumen ini digenerate secara otomatis oleh Sistem RKM-KMH pada ' . now()->translatedFormat('d F Y') . '.', + 0, + 0, + 'L' + ); + $this->Cell(87, 5, 'Halaman ' . $this->PageNo() . ' dari {nb}', 0, 0, 'R'); + } + + /** + * Generate real PDF binary string. + */ + public static function generate(Collection $employees, array $metaLeft, array $metaRight, string $subtitle): string + { + $pdf = new self('L', 'mm', 'A4'); + $pdf->AliasNbPages(); + $pdf->reportTitle = 'Laporan Data SIMPER'; + $pdf->subtitle = $subtitle; + $pdf->metaLeft = $metaLeft; + $pdf->metaRight = $metaRight; + $pdf->totalRows = $employees->count(); + $pdf->logoPath = public_path('images/logo-kerinci.png'); + + $pdf->SetMargins(15, 10, 15); + $pdf->AddPage(); + $pdf->SetAutoPageBreak(true, 15); + + $pdf->SetFont('Arial', '', 7.5); + $fill = false; + $soon = now()->addDays(30); + + foreach ($employees as $idx => $emp) { + $isDriver = $emp->is_operator; + $expDate = $emp->simper_expired_at ? $emp->simper_expired_at->format('d/m/Y') : '-'; + + if (! $isDriver) { + $statusText = 'Bukan Driver'; + } elseif (! $emp->simper_expired_at) { + $statusText = 'Belum Ada SIMPER'; + } elseif ($emp->simper_expired_at->isPast() && ! $emp->simper_expired_at->isToday()) { + $statusText = 'Kedaluwarsa'; + } elseif ($emp->simper_expired_at->lte($soon)) { + $statusText = 'Segera Habis'; + } else { + $statusText = 'Masih Berlaku'; + } + + $pdf->SetFillColor(248, 250, 252); + $pdf->SetDrawColor(241, 245, 249); + $pdf->SetTextColor(15, 23, 42); + + // Kolom 1: No + $pdf->SetFont('Arial', '', 7.5); + $pdf->Cell(10, 6.5, (string) ($idx + 1), 'B', 0, 'C', $fill); + + // Kolom 2: NIK (Bold) + $pdf->SetFont('Arial', 'B', 7.5); + $pdf->Cell(30, 6.5, $emp->nik, 'B', 0, 'C', $fill); + + // Kolom 3: Nama Lengkap (Bold, Truncate jika > 36 karakter) + $nama = mb_strimwidth($emp->name, 0, 36, '...'); + $pdf->Cell(62, 6.5, ' ' . $nama, 'B', 0, 'L', $fill); + + // Kolom 4: Jabatan + $pdf->SetFont('Arial', '', 7.5); + $jabatan = mb_strimwidth($emp->position ?: '-', 0, 26, '...'); + $pdf->Cell(45, 6.5, ' ' . $jabatan, 'B', 0, 'L', $fill); + + // Kolom 5: Unit / Divisi + $unit = mb_strimwidth($emp->unit_kerja ?: ($emp->division ?: '-'), 0, 24, '...'); + $pdf->Cell(40, 6.5, ' ' . $unit, 'B', 0, 'L', $fill); + + // Kolom 6: Status Driver + $pdf->Cell(26, 6.5, $isDriver ? 'Driver' : 'Non-Driver', 'B', 0, 'C', $fill); + + // Kolom 7: Masa Berlaku + $pdf->Cell(26, 6.5, $expDate, 'B', 0, 'C', $fill); + + // Kolom 8: Status SIMPER (Berwarna) + if ($statusText === 'Masih Berlaku') { + $pdf->SetTextColor(4, 120, 87); // #047857 Green + } elseif ($statusText === 'Segera Habis') { + $pdf->SetTextColor(180, 83, 9); // #b45309 Amber + } elseif ($statusText === 'Kedaluwarsa' || $statusText === 'Belum Ada SIMPER') { + $pdf->SetTextColor(190, 18, 60); // #be123c Rose + } else { + $pdf->SetTextColor(100, 116, 139); // #64748b Slate + } + $pdf->SetFont('Arial', 'B', 7.5); + $pdf->Cell(28, 6.5, $statusText, 'B', 0, 'C', $fill); + + $pdf->Ln(); + $fill = ! $fill; + } + + return $pdf->Output('S'); + } +} diff --git a/app/Services/SimpleXlsxExporter.php b/app/Services/SimpleXlsxExporter.php new file mode 100644 index 0000000..7d846b3 --- /dev/null +++ b/app/Services/SimpleXlsxExporter.php @@ -0,0 +1,203 @@ + 6, 'NIK' => 16, 'Nama Lengkap' => 28, ...] + * @param array $rows Array of associative or index arrays + * @param array $alignments Optional per-column alignment: 'center' or 'left' + * @return string Raw zip content + */ + public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = []): string + { + $numCols = count($headers); + $lastColLetter = self::colLetter($numCols); + + // Build sheetData XML + $sheetXml = ''; + $sheetXml .= ''; + + $totalRows = 4 + count($metaLines) + count($rows); + $sheetXml .= ''; + $sheetXml .= ''; + $sheetXml .= ''; + + // Column widths + $sheetXml .= ''; + $colIdx = 1; + foreach ($headers as $name => $width) { + $sheetXml .= ''; + $colIdx++; + } + $sheetXml .= ''; + + $sheetXml .= ''; + + // Row 1: Title + $rowNum = 1; + $sheetXml .= ''; + $sheetXml .= '' . htmlspecialchars($title, ENT_XML1) . ''; + $sheetXml .= ''; + + // Meta lines (Sub-titles) + foreach ($metaLines as $meta) { + $rowNum++; + $sheetXml .= ''; + $sheetXml .= '' . htmlspecialchars($meta, ENT_XML1) . ''; + $sheetXml .= ''; + } + + // Blank spacer row + $rowNum++; + $sheetXml .= ''; + + // Table Header Row + $rowNum++; + $headerRowNum = $rowNum; + $sheetXml .= ''; + $cIdx = 1; + foreach ($headers as $name => $width) { + $cellRef = self::colLetter($cIdx) . $headerRowNum; + $sheetXml .= '' . htmlspecialchars($name, ENT_XML1) . ''; + $cIdx++; + } + $sheetXml .= ''; + + // Table Data Rows + $alignKeys = array_values($alignments); + foreach ($rows as $rData) { + $rowNum++; + $sheetXml .= ''; + $cIdx = 1; + $vals = is_array($rData) ? array_values($rData) : []; + for ($i = 0; $i < $numCols; $i++) { + $val = $vals[$i] ?? ''; + $cellRef = self::colLetter($cIdx) . $rowNum; + $align = $alignKeys[$i] ?? ($cIdx === 1 ? 'center' : 'left'); + $styleId = ($align === 'center') ? 4 : 5; + + if (is_numeric($val) && strlen($val) > 0 && !str_starts_with((string)$val, '0')) { + $sheetXml .= '' . $val . ''; + } else { + $sheetXml .= '' . htmlspecialchars((string)$val, ENT_XML1) . ''; + } + $cIdx++; + } + $sheetXml .= ''; + } + + $sheetXml .= ''; + + // Merge cells for title and meta lines + $sheetXml .= ''; + $sheetXml .= ''; + for ($m = 2; $m <= 1 + count($metaLines); $m++) { + $sheetXml .= ''; + } + $sheetXml .= ''; + + $sheetXml .= ''; + $sheetXml .= ''; + + // Stylesheet with KMH Brand Colors (Navy / Forest Green) + $stylesXml = ' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +'; + + $workbookXml = ' + + + + +'; + + $workbookRelsXml = ' + + + +'; + + $relsXml = ' + + +'; + + $contentTypesXml = ' + + + + + + +'; + + // Build ZIP + $tmpFile = tempnam(sys_get_temp_dir(), 'xlsx_'); + $zip = new ZipArchive(); + $zip->open($tmpFile, ZipArchive::OVERWRITE); + + $zip->addFromString('[Content_Types].xml', $contentTypesXml); + $zip->addFromString('_rels/.rels', $relsXml); + $zip->addFromString('xl/workbook.xml', $workbookXml); + $zip->addFromString('xl/_rels/workbook.xml.rels', $workbookRelsXml); + $zip->addFromString('xl/styles.xml', $stylesXml); + $zip->addFromString('xl/worksheets/sheet1.xml', $sheetXml); + + $zip->close(); + + $content = file_get_contents($tmpFile); + unlink($tmpFile); + + return $content; + } + + private static function colLetter(int $colIndex): string + { + $letter = ''; + while ($colIndex > 0) { + $p = ($colIndex - 1) % 26; + $letter = chr(65 + $p) . $letter; + $colIndex = intval(($colIndex - $p) / 26); + } + return $letter ?: 'A'; + } +} diff --git a/app/Services/VehiclePdfExporter.php b/app/Services/VehiclePdfExporter.php new file mode 100644 index 0000000..03be31c --- /dev/null +++ b/app/Services/VehiclePdfExporter.php @@ -0,0 +1,199 @@ + 'NO', 'width' => 10, 'align' => 'C'], ...] + public int $totalRows = 0; + public string $logoPath = ''; + + public function Header(): void + { + // 1. Logo Perusahaan di Kiri Atas + if (!empty($this->logoPath) && file_exists($this->logoPath)) { + $this->Image($this->logoPath, 15, 10, 44); + } else { + $this->SetXY(15, 10); + $this->SetFont('Arial', 'B', 14); + $this->SetTextColor(27, 94, 32); + $this->Cell(60, 8, 'KERINCI HYDROPOWER', 0, 0, 'L'); + } + + // 2. Branding Sistem di Kanan Atas + $this->SetXY(170, 10); + $this->SetFont('Arial', 'B', 18); + $this->SetTextColor(27, 94, 32); // #1b5e20 Green + $this->Cell(112, 6, 'RKM-KMH', 0, 1, 'R'); + + $this->SetXY(170, 16); + $this->SetFont('Arial', 'B', 7.5); + $this->SetTextColor(71, 85, 105); // #475569 Slate + $this->Cell(112, 4, 'KERINCI HYDROPOWER 350 MW', 0, 1, 'R'); + + // 3. Banner Biru Gelap Navy (Sesuai Format it.allrole.web.id) + $this->SetY(24); + $this->SetFillColor(6, 33, 63); // #06213f Dark Navy + $this->Rect(15, 24, 267, 16, 'F'); + + // Teks Judul di Kiri Banner + $this->SetXY(18, 26); + $this->SetFont('Arial', 'B', 13); + $this->SetTextColor(255, 255, 255); + $this->Cell(140, 6, $this->reportTitle, 0, 1, 'L'); + + $this->SetXY(18, 32); + $this->SetFont('Arial', '', 8); + $this->SetTextColor(203, 213, 225); // #cbd5e1 Slate + $this->Cell(140, 5, $this->subtitle, 0, 1, 'L'); + + // Teks Sub-sistem di Kanan Banner + $this->SetXY(160, 26); + $this->SetFont('Arial', 'B', 9); + $this->SetTextColor(255, 255, 255); + $this->Cell(119, 6, 'SISTEM KENDARAAN RKM-KMH', 0, 1, 'R'); + + $this->SetXY(160, 32); + $this->SetFont('Arial', 'I', 7.5); + $this->SetTextColor(203, 213, 225); + $this->Cell(119, 5, 'Dicetak otomatis dari sistem', 0, 1, 'R'); + + // 4. Bagian Ringkasan Metadata (2 Kolom) + $metaY = 44; + $this->SetTextColor(51, 65, 85); + + // Kolom Kiri + foreach ($this->metaLeft as $k => $v) { + $this->SetXY(15, $metaY); + $this->SetFont('Arial', '', 8); + $this->Cell(28, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(85, 4.5, (string) $v, 0, 1); + $metaY += 5; + } + + // Kolom Kanan + $metaY2 = 44; + foreach ($this->metaRight as $k => $v) { + $this->SetXY(175, $metaY2); + $this->SetFont('Arial', '', 8); + $this->Cell(28, 4.5, $k, 0, 0); + $this->Cell(5, 4.5, ':', 0, 0); + $this->SetFont('Arial', 'B', 8); + $this->Cell(74, 4.5, (string) $v, 0, 1); + $metaY2 += 5; + } + + // Garis Pembatas Tipis + $divY = max($metaY, $metaY2) + 2; + $this->SetDrawColor(226, 232, 240); + $this->Line(15, $divY, 282, $divY); + + // 5. Header Tabel Solid Navy + $tableY = $divY + 3; + $this->SetXY(15, $tableY); + $this->SetFillColor(6, 33, 63); + $this->SetTextColor(255, 255, 255); + $this->SetFont('Arial', 'B', 7.5); + + foreach ($this->columns as $col) { + $this->Cell($col['width'], 7.5, $col['title'], 0, 0, $col['align'] ?? 'L', true); + } + $this->Ln(); + } + + public function Footer(): void + { + $this->SetY(-12); + $this->SetFont('Arial', '', 7.5); + $this->SetTextColor(148, 163, 184); + $this->Cell( + 180, + 5, + 'Menampilkan ' . $this->totalRows . ' data - Dokumen ini digenerate secara otomatis oleh Sistem RKM-KMH pada ' . now()->translatedFormat('d F Y') . '.', + 0, + 0, + 'L' + ); + $this->Cell(87, 5, 'Halaman ' . $this->PageNo() . ' dari {nb}', 0, 0, 'R'); + } + + /** + * Helper pembuatan file PDF seragam untuk modul armada kendaraan. + */ + public static function generate( + string $title, + string $subtitle, + array $metaLeft, + array $metaRight, + array $columns, + array $rows + ): string { + $pdf = new self('L', 'mm', 'A4'); + $pdf->AliasNbPages(); + $pdf->reportTitle = $title; + $pdf->subtitle = $subtitle; + $pdf->metaLeft = $metaLeft; + $pdf->metaRight = $metaRight; + $pdf->columns = $columns; + $pdf->totalRows = count($rows); + $pdf->logoPath = public_path('images/logo-kerinci.png'); + + $pdf->SetMargins(15, 10, 15); + $pdf->AddPage(); + $pdf->SetAutoPageBreak(true, 15); + + $fill = false; + foreach ($rows as $r) { + $pdf->SetFillColor(248, 250, 252); + $pdf->SetDrawColor(241, 245, 249); + $pdf->SetTextColor(15, 23, 42); + + foreach ($columns as $idx => $col) { + $val = (string) ($r[$idx] ?? '-'); + $align = $col['align'] ?? 'L'; + $width = $col['width']; + $isBold = !empty($col['bold']); + $isStatus = !empty($col['is_status']); + + if ($isStatus) { + if ($val === 'Operation') { + $pdf->SetTextColor(4, 120, 87); // Green + } elseif ($val === 'Standby') { + $pdf->SetTextColor(180, 83, 9); // Amber + } elseif ($val === 'Breakdown') { + $pdf->SetTextColor(190, 18, 60); // Red + } elseif ($val === 'Maintenance') { + $pdf->SetTextColor(2, 132, 199); // Sky blue + } else { + $pdf->SetTextColor(100, 116, 139); + } + $pdf->SetFont('Arial', 'B', 7.5); + } else { + $pdf->SetTextColor(15, 23, 42); + $pdf->SetFont('Arial', $isBold ? 'B' : '', 7.5); + } + + $maxChar = !empty($col['max_char']) ? $col['max_char'] : 0; + if ($maxChar > 0 && mb_strlen($val) > $maxChar) { + $val = mb_strimwidth($val, 0, $maxChar, '...'); + } + + $displayVal = ($align === 'L' && !empty($val) && $val !== '-') ? ' ' . $val : $val; + $pdf->Cell($width, 6.5, $displayVal, 'B', 0, $align, $fill); + } + + $pdf->Ln(); + $fill = !$fill; + } + + return $pdf->Output('S'); + } +} diff --git a/composer.json b/composer.json index 279a4eb..f4c66b8 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,7 @@ "php": "^8.2", "laravel/framework": "^12.0", "laravel/tinker": "^2.10.1", + "setasign/fpdf": "^1.9", "simplesoftwareio/simple-qrcode": "*", "spatie/laravel-permission": "^8.3" }, diff --git a/composer.lock b/composer.lock index 4d72ed8..68fb1c1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "170b1c005f6855019bb44940201e3dd9", + "content-hash": "3ab671de9e6dccda5b1787b8cef23b3a", "packages": [ { "name": "bacon/bacon-qr-code", @@ -3407,6 +3407,52 @@ }, "time": "2026-09-16T11:39:30+00:00" }, + { + "name": "setasign/fpdf", + "version": "1.9.0", + "source": { + "type": "git", + "url": "https://github.com/Setasign/FPDF.git", + "reference": "051b70e4c57dedc88df41b1eff1c62894e5f9ed0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Setasign/FPDF/zipball/051b70e4c57dedc88df41b1eff1c62894e5f9ed0", + "reference": "051b70e4c57dedc88df41b1eff1c62894e5f9ed0", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "ext-zlib": "*" + }, + "type": "library", + "autoload": { + "classmap": [ + "fpdf.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Olivier Plathey", + "email": "oliver@fpdf.org", + "homepage": "http://fpdf.org/" + } + ], + "description": "FPDF is a PHP class which allows to generate PDF files with pure PHP. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.", + "homepage": "http://www.fpdf.org", + "keywords": [ + "fpdf", + "pdf" + ], + "support": { + "source": "https://github.com/Setasign/FPDF/tree/1.9.0" + }, + "time": "2026-05-31T14:25:29+00:00" + }, { "name": "simplesoftwareio/simple-qrcode", "version": "4.2.0", diff --git a/config/rbac_permissions.php b/config/rbac_permissions.php index 17df9b7..559be7d 100644 --- a/config/rbac_permissions.php +++ b/config/rbac_permissions.php @@ -100,6 +100,18 @@ return [ 'label' => 'Melihat Ringkasan Aktivitas & Statistik', 'description' => 'Melihat summary dan grafik agregat penggunaan kendaraan.', ], + 'qma.p2h.view' => [ + 'label' => 'Melihat Log & Rekap P2H Unit Support', + 'description' => 'Melihat riwayat checksheet pemeriksaan pra-harian dan ringkasan kondisi operasional unit support.', + ], + 'qma.p2h.approve' => [ + 'label' => 'Menyetujui & Menolak P2H (Approval)', + 'description' => 'Memvalidasi kelayakan operasi unit support dan memberikan status approve/reject checksheet.', + ], + 'qma.p2h.templates' => [ + 'label' => 'Mengelola Master Template P2H', + 'description' => 'Mengatur 28 master template checksheet P2H, menambah, mengedit, dan menyusun urutan pertanyaan.', + ], ], ], 'pg' => [ @@ -150,5 +162,23 @@ return [ ], ], ], + 'employee' => [ + 'name' => 'Modul Karyawan (Operator & Pengemudi Lapangan)', + 'icon' => 'fa-solid fa-id-badge', + 'permissions' => [ + 'employee.dashboard' => [ + 'label' => 'Melihat Dashboard Karyawan', + 'description' => 'Mengakses dashboard personal karyawan, ringkasan masa berlaku SIMPER, dan shortcut pra-operasi.', + ], + 'employee.p2h' => [ + 'label' => 'Mengisi Form P2H Unit Support', + 'description' => 'Mengakses katalog unit support dan menginput checklist pra-harian P2H sebelum beroperasi.', + ], + 'employee.timesheet' => [ + 'label' => 'Mengisi Timesheet / Mobilisasi', + 'description' => 'Mencatat riwayat mobilisasi dan aktivitas operasional harian kendaraan.', + ], + ], + ], ], ]; diff --git a/database/seeders/P2hTemplateSeeder.php b/database/seeders/P2hTemplateSeeder.php index 60044e7..4e91ed9 100644 --- a/database/seeders/P2hTemplateSeeder.php +++ b/database/seeders/P2hTemplateSeeder.php @@ -21,97 +21,173 @@ class P2hTemplateSeeder extends Seeder $dir = 'C:/laragon/www/htdocs/Data_List_Questions_P2H'; } - if (!is_dir($dir)) { - $this->command->error("Direktori {$dir} tidak ditemukan."); - return; - } + $files = is_dir($dir) ? glob("{$dir}/*.md") : []; - $files = glob("{$dir}/*.md"); - $this->command->info("Ditemukan " . count($files) . " file template P2H."); + // 28 Kategori Template Master P2H Unit Support + $fallbackTemplates = [ + 'VGRM7Z' => ['name' => 'Boomlift', 'file_name' => 'P2H_Boomlift_VGRM7Z.md'], + 'VGRM7X' => ['name' => 'Bore Pile Rig', 'file_name' => 'P2H_Bore_Pile_Rig_VGRM7X.md'], + 'CDRM7C' => ['name' => 'Carry Deck Crane', 'file_name' => 'P2H_Carry_Deck_Crane_CDRM7C.md'], + 'YMWL9T' => ['name' => 'Electric Compressor', 'file_name' => 'P2H_Compressor_Electric_YMWL9T.md'], + 'YKWL9C' => ['name' => 'Engine Compressor', 'file_name' => 'P2H_Compressor_Engine_YKWL9C.md'], + 'CPWL9P' => ['name' => 'Trailer Concrete Pump Electric', 'file_name' => 'P2H_Concrete_Pump_Electric_CPWL9P.md'], + 'CPWL9E' => ['name' => 'Portable Concrete Pump Engine', 'file_name' => 'P2H_Concrete_Pump_Engine_CPWL9E.md'], + '29NVFP' => ['name' => 'Concrete Pump Truck', 'file_name' => 'P2H_Concrete_Pump_Truck_29NVFP.md'], + 'CT723D' => ['name' => 'Crane Truck', 'file_name' => 'P2H_Crane_Truck_CT723D.md'], + 'EH713B' => ['name' => 'Crawler Crane', 'file_name' => 'P2H_Crawler_Crane_EH713B.md'], + 'CR77BD' => ['name' => 'Crawler Rig Drill', 'file_name' => 'P2H_Crawler_Rig_Drill_CR77BD.md'], + 'DZ76BR' => ['name' => 'Dozer', 'file_name' => 'P2H_Dozer_DZ76BR.md'], + 'R8D3SY' => ['name' => 'Dump Truck', 'file_name' => 'P2H_Dump_Truck_R8D3SY.md'], + 'EXD4RP' => ['name' => 'Excavator', 'file_name' => 'P2H_Excavator_EXD4RP.md'], + 'FKD4LY' => ['name' => 'Forklift', 'file_name' => 'P2H_Forklift_FKD4LY.md'], + 'R5D3FT' => ['name' => 'Fuel Truck', 'file_name' => 'P2H_Fuel_Truck_R5D3FT.md'], + 'JD7553D' => ['name' => 'Jumbo Drill', 'file_name' => 'P2H_Jumbo_Drill_JD7553D.md'], + 'RF89BB' => ['name' => 'Manlift', 'file_name' => 'P2H_Manlift_RF89BB.md'], + 'MG79KB' => ['name' => 'Motor Grader', 'file_name' => 'P2H_Motor_Grader_MG79KB.md'], + 'ML71KB' => ['name' => 'Mucking Loader', 'file_name' => 'P2H_Mucking_Loader_ML71KB.md'], + 'EH713C' => ['name' => 'Rough Terrain Crane', 'file_name' => 'P2H_Rough_Terrain_Crane_EH713C.md'], + 'SSLS5W' => ['name' => 'Scissorlift', 'file_name' => 'P2H_Scissorlift_SSLS5W.md'], + 'MS31AC' => ['name' => 'Shotcrete', 'file_name' => 'P2H_Shotcrete_MS31AC.md'], + 'R8D3SW' => ['name' => 'Truk Mixer', 'file_name' => 'P2H_Truk_Mixer_R8D3SW.md'], + 'MV54AH' => ['name' => 'Vibro', 'file_name' => 'P2H_Vibro_MV54AH.md'], + 'CWPK3N' => ['name' => 'Water Pump', 'file_name' => 'P2H_Water_Pump_CWPK3N.md'], + 'WT51DB' => ['name' => 'Water Truck', 'file_name' => 'P2H_Water_Truck_WT51DB.md'], + 'R8D3ST' => ['name' => 'Wheel Loader', 'file_name' => 'P2H_Wheel_Loader_R8D3ST.md'], + ]; - DB::transaction(function () use ($files) { - foreach ($files as $file) { - $content = file_get_contents($file); - $fileName = basename($file); + DB::transaction(function () use ($files, $fallbackTemplates) { + if (!empty($files)) { + $this->command->info("Ditemukan " . count($files) . " file template P2H."); + foreach ($files as $file) { + $content = file_get_contents($file); + $fileName = basename($file); - // 1. Ekstrak Judul Kategori - // Pola: # [P2H Excavator](url) atau # P2H Excavator - $categoryName = ''; - if (preg_match('/#\s*\[?P2H\s+([^\]\(\r\n]+)/i', $content, $mTitle)) { - $categoryName = trim($mTitle[1]); - } + // 1. Ekstrak Judul Kategori + // Pola: # [P2H Excavator](url) atau # P2H Excavator + $categoryName = ''; + if (preg_match('/#\s*\[?P2H\s+([^\]\(\r\n]+)/i', $content, $mTitle)) { + $categoryName = trim($mTitle[1]); + } - // 2. Ekstrak Checksheet Code - // Pola: * **Checksheet Code:** `EXD4RP` - $checksheetCode = ''; - if (preg_match('/Checksheet Code:\**\s*`?([A-Za-z0-9]+)`?/i', $content, $mCode)) { - $checksheetCode = trim($mCode[1]); - } + // 2. Ekstrak Checksheet Code + // Pola: * **Checksheet Code:** `EXD4RP` + $checksheetCode = ''; + if (preg_match('/Checksheet Code:\**\s*`?([A-Za-z0-9]+)`?/i', $content, $mCode)) { + $checksheetCode = trim($mCode[1]); + } - if (!$checksheetCode) { - // Fallback kode dari nama file jika tidak ditemukan regex - $checksheetCode = strtoupper(Str::slug($categoryName, '_')); - } + if (!$checksheetCode) { + // Fallback kode dari nama file jika tidak ditemukan regex + $checksheetCode = strtoupper(Str::slug($categoryName, '_')); + } - $template = P2hTemplate::updateOrCreate( - ['code' => $checksheetCode], - [ - 'name' => $categoryName ?: pathinfo($fileName, PATHINFO_FILENAME), - 'file_name' => $fileName, - 'description' => "Template form inspeksi P2H resmi untuk kategori {$categoryName} (Kode: {$checksheetCode}).", - 'is_active' => true, - ] - ); + $template = P2hTemplate::updateOrCreate( + ['code' => $checksheetCode], + [ + 'name' => $categoryName ?: pathinfo($fileName, PATHINFO_FILENAME), + 'file_name' => $fileName, + 'description' => "Template form inspeksi P2H resmi untuk kategori {$categoryName} (Kode: {$checksheetCode}).", + 'is_active' => true, + ] + ); - // Bersihkan item lama jika seeder dijalankan ulang - $template->items()->delete(); + // Bersihkan item lama jika seeder dijalankan ulang + $template->items()->delete(); - // 3. Parse Baris Tabel Markdown - $lines = explode("\n", $content); - $currentSection = 'General'; - $sequence = 1; + // 3. Parse Baris Tabel Markdown + $lines = explode("\n", $content); + $currentSection = 'General'; + $sequence = 1; - foreach ($lines as $line) { - $line = trim($line); - if (str_starts_with($line, '|')) { - $cols = array_map('trim', explode('|', $line)); - // cols format: [0]=>'', [1]=>No, [2]=>Section, [3]=>Title, [4]=>Question Type, [5]=>Sequence, [6]=>'' - if (count($cols) >= 6 && is_numeric($cols[1])) { - $rawSection = trim(str_replace('**', '', $cols[2])); - $title = trim($cols[3]); - $rawType = trim($cols[4]); + foreach ($lines as $line) { + $line = trim($line); + if (str_starts_with($line, '|')) { + $cols = array_map('trim', explode('|', $line)); + // cols format: [0]=>'', [1]=>No, [2]=>Section, [3]=>Title, [4]=>Question Type, [5]=>Sequence, [6]=>'' + if (count($cols) >= 6 && is_numeric($cols[1])) { + $rawSection = trim(str_replace('**', '', $cols[2])); + $title = trim($cols[3]); + $rawType = trim($cols[4]); - // Jika baris adalah penanda Header Section - if (stripos($title, 'Header Section') !== false || $rawType === '-') { - if (!empty($rawSection)) { + // Jika baris adalah penanda Header Section + if (stripos($title, 'Header Section') !== false || $rawType === '-') { + if (!empty($rawSection)) { + $currentSection = $rawSection; + } + continue; + } + + // Abaikan baris penutup jika berupa baris survey kosong + if (stripos($title, 'Penutup') !== false || stripos($rawSection, 'Penutup') !== false) { + continue; + } + + if (!empty($rawSection) && $rawSection !== $currentSection) { $currentSection = $rawSection; } - continue; + + // Map question type + $qType = match(true) { + stripos($rawType, 'Datetime') !== false => 'datetime', + stripos($rawType, 'Numerical') !== false => 'number', + stripos($rawType, 'Multiple Lines') !== false => 'text', + stripos($rawType, 'Single Line') !== false => 'text', + default => 'choice', + }; + + P2hTemplateItem::create([ + 'template_id' => $template->id, + 'section' => $currentSection, + 'title' => $title, + 'question_type' => $qType, + 'sequence' => $sequence++, + ]); } + } + } + } + } else { + // Fallback: Gunakan daftar 28 master template bawaan jika folder markdown tidak ada + $this->command->info("Menggunakan 28 template master P2H bawaan."); + $defaultQuestions = [ + 'Pemeriksaan Keliling (Walk Around)' => [ + 'Kondisi fisik bodi, struktur, dan kebersihan unit', + 'Pemeriksaan kebocoran oli, air pendingin radiator, dan bahan bakar', + 'Kondisi ban / track shoe, baut roda, dan tegangan track', + ], + 'Ruang Mesin & Kompartemen' => [ + 'Level oli mesin, oli hidrolik, dan minyak rem', + 'Level air radiator dan kondisi v-belt / fan belt', + 'Kondisi baterai / aki dan kebersihan terminal kabel', + ], + 'Kabin & Fungsi Operasional' => [ + 'Fungsi sistem rem (Service Brake & Parking Brake)', + 'Fungsi sistem kemudi, tuas hidrolik, dan instrumen indikator', + 'Fungsi lampu kerja, lampu rotary, klakson, dan alarm mundur', + 'Ketersediaan APD standar dan APAR yang valid di dalam kabin', + ], + ]; - // Abaikan baris penutup jika berupa baris survey kosong - if (stripos($title, 'Penutup') !== false || stripos($rawSection, 'Penutup') !== false) { - continue; - } - - if (!empty($rawSection) && $rawSection !== $currentSection) { - $currentSection = $rawSection; - } - - // Map question type - $qType = match(true) { - stripos($rawType, 'Datetime') !== false => 'datetime', - stripos($rawType, 'Numerical') !== false => 'number', - stripos($rawType, 'Multiple Lines') !== false => 'text', - stripos($rawType, 'Single Line') !== false => 'text', - default => 'choice', - }; + foreach ($fallbackTemplates as $code => $tmplData) { + $template = P2hTemplate::updateOrCreate( + ['code' => $code], + [ + 'name' => $tmplData['name'], + 'file_name' => $tmplData['file_name'], + 'description' => "Template form inspeksi P2H resmi untuk kategori {$tmplData['name']} (Kode: {$code}).", + 'is_active' => true, + ] + ); + $template->items()->delete(); + $sequence = 1; + foreach ($defaultQuestions as $section => $questions) { + foreach ($questions as $qTitle) { P2hTemplateItem::create([ 'template_id' => $template->id, - 'section' => $currentSection, - 'title' => $title, - 'question_type' => $qType, + 'section' => $section, + 'title' => $qTitle, + 'question_type' => 'choice', 'sequence' => $sequence++, ]); } diff --git a/database/seeders/RolePermissionSeeder.php b/database/seeders/RolePermissionSeeder.php index 4b3fd7a..b88b580 100644 --- a/database/seeders/RolePermissionSeeder.php +++ b/database/seeders/RolePermissionSeeder.php @@ -48,6 +48,9 @@ class RolePermissionSeeder extends Seeder 'qma.vehicles.delete', 'qma.logs.view', 'qma.summary.view', + 'qma.p2h.view', + 'qma.p2h.approve', + 'qma.p2h.templates', ], 'pg_admin' => [ 'pg.guards.view', @@ -62,6 +65,11 @@ class RolePermissionSeeder extends Seeder 'gate.approve', 'gate.reject', ], + 'employee' => [ + 'employee.dashboard', + 'employee.p2h', + 'employee.timesheet', + ], ]; foreach ($rolesWithPermissions as $roleName => $perms) { diff --git a/resources/views/hse/employees_index.blade.php b/resources/views/hse/employees_index.blade.php index 5fb89f4..f3c4fd7 100644 --- a/resources/views/hse/employees_index.blade.php +++ b/resources/views/hse/employees_index.blade.php @@ -26,22 +26,37 @@ -
- - +
+ + + @can('hse.employees.create') - @endcan
@@ -601,10 +616,32 @@ } }); + // Toggle Menu Dropdown Ekspor Simper (Format it.allrole.web.id) + function toggleSimperExportMenu(event) { + event.stopPropagation(); + const menu = document.getElementById('exportMenuSimper'); + if (menu) { + menu.style.display = menu.style.display === 'block' ? 'none' : 'block'; + } + } + + // Klik di luar dropdown untuk menutup menu + document.addEventListener('click', function(event) { + const container = document.getElementById('exportSimperDropdownContainer'); + const menu = document.getElementById('exportMenuSimper'); + if (container && !container.contains(event.target)) { + if (menu) { + menu.style.display = 'none'; + } + } + }); + // Keyboard ESC untuk menutup modal panduan document.addEventListener('keydown', function(e) { if (e.key === 'Escape') { closeGuideModal(); + const exportMenu = document.getElementById('exportMenuSimper'); + if (exportMenu) exportMenu.style.display = 'none'; } }); diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index a5d9dcc..0510220 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -285,7 +285,7 @@ @endcan - @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view'])) + @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view', 'qma.p2h.view', 'qma.p2h.templates']))

MANAJEMEN QMA @@ -322,7 +322,7 @@

@endcan - @can('qma.logs.view') + @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @php $isActivityRoute = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @endphp @@ -340,18 +340,24 @@
+ @can('qma.logs.view') Timesheet LV + @endcan + @can('qma.p2h.view') P2H Unit Support + @endcan
+ @endif + @can('qma.p2h.templates') @@ -574,7 +580,7 @@ @endcan - @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view'])) + @if(auth()->user()->canAny(['qma.vehicles.view', 'qma.logs.view', 'qma.summary.view', 'qma.p2h.view', 'qma.p2h.templates']))

MANAJEMEN QMA @@ -609,7 +615,7 @@

@endcan - @can('qma.logs.view') + @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @php $isActivityRouteMob = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @endphp @@ -625,18 +631,24 @@
+ @can('qma.logs.view') Timesheet LV + @endcan + @can('qma.p2h.view') P2H Unit Support + @endcan
+ @endif + @can('qma.p2h.templates') Master Template P2H diff --git a/resources/views/pg/guards_index.blade.php b/resources/views/pg/guards_index.blade.php index 27d7c88..964ab9e 100644 --- a/resources/views/pg/guards_index.blade.php +++ b/resources/views/pg/guards_index.blade.php @@ -25,14 +25,37 @@ - -
+ +
+ + + @can('pg.guards.create') @endcan
@@ -538,6 +561,23 @@
diff --git a/resources/views/qma/activity_summary.blade.php b/resources/views/qma/activity_summary.blade.php index 7c90d53..a05378e 100644 --- a/resources/views/qma/activity_summary.blade.php +++ b/resources/views/qma/activity_summary.blade.php @@ -24,10 +24,33 @@ - @@ -647,9 +670,30 @@ document.addEventListener('DOMContentLoaded', function () { } } + // Dropdown Menu Ekspor Summary Aktivitas Kendaraan + function toggleActivitySummaryExportMenu(event) { + event.stopPropagation(); + const menu = document.getElementById('exportMenuActivitySummary'); + if (menu) { + menu.style.display = menu.style.display === 'block' ? 'none' : 'block'; + } + } + + document.addEventListener('click', function(event) { + const container = document.getElementById('exportActivitySummaryDropdownContainer'); + const menu = document.getElementById('exportMenuActivitySummary'); + if (container && !container.contains(event.target)) { + if (menu) { + menu.style.display = 'none'; + } + } + }); + document.addEventListener('keydown', function(e) { if (e.key === 'Escape') { closeGuideModal(); + const exportMenu = document.getElementById('exportMenuActivitySummary'); + if (exportMenu) exportMenu.style.display = 'none'; } }); diff --git a/resources/views/qma/p2h_index.blade.php b/resources/views/qma/p2h_index.blade.php index bc65e97..6b8151b 100644 --- a/resources/views/qma/p2h_index.blade.php +++ b/resources/views/qma/p2h_index.blade.php @@ -24,10 +24,33 @@ - @@ -323,11 +346,32 @@ function closeGuideModal() { } } -document.addEventListener('keydown', function(e) { - if (e.key === 'Escape') { - closeGuideModal(); + // Dropdown Menu Ekspor P2H Unit Support + function toggleP2hExportMenu(event) { + event.stopPropagation(); + const menu = document.getElementById('exportMenuP2h'); + if (menu) { + menu.style.display = menu.style.display === 'block' ? 'none' : 'block'; + } } -}); + + document.addEventListener('click', function(event) { + const container = document.getElementById('exportP2hDropdownContainer'); + const menu = document.getElementById('exportMenuP2h'); + if (container && !container.contains(event.target)) { + if (menu) { + menu.style.display = 'none'; + } + } + }); + + document.addEventListener('keydown', function(e) { + if (e.key === 'Escape') { + closeGuideModal(); + const exportMenu = document.getElementById('exportMenuP2h'); + if (exportMenu) exportMenu.style.display = 'none'; + } + }); diff --git a/resources/views/qma/p2h_summary.blade.php b/resources/views/qma/p2h_summary.blade.php index 123a042..d4c2fec 100644 --- a/resources/views/qma/p2h_summary.blade.php +++ b/resources/views/qma/p2h_summary.blade.php @@ -24,12 +24,35 @@ -
- +
+ + + + Detail P2H - + Master Template @@ -452,9 +475,30 @@ document.addEventListener('DOMContentLoaded', function () { } } + // Dropdown Menu Ekspor Summary P2H Unit Support + function toggleP2hSummaryExportMenu(event) { + event.stopPropagation(); + const menu = document.getElementById('exportMenuP2hSummary'); + if (menu) { + menu.style.display = menu.style.display === 'block' ? 'none' : 'block'; + } + } + + document.addEventListener('click', function(event) { + const container = document.getElementById('exportP2hSummaryDropdownContainer'); + const menu = document.getElementById('exportMenuP2hSummary'); + if (container && !container.contains(event.target)) { + if (menu) { + menu.style.display = 'none'; + } + } + }); + document.addEventListener('keydown', function(e) { if (e.key === 'Escape') { closeGuideModal(); + const exportMenu = document.getElementById('exportMenuP2hSummary'); + if (exportMenu) exportMenu.style.display = 'none'; } }); diff --git a/resources/views/qma/vehicles_lv.blade.php b/resources/views/qma/vehicles_lv.blade.php index 17b9a6d..544226e 100644 --- a/resources/views/qma/vehicles_lv.blade.php +++ b/resources/views/qma/vehicles_lv.blade.php @@ -27,13 +27,28 @@
- + + @can('qma.vehicles.create') + + @can('qma.vehicles.create')
-
+
+ class="flex-1 sm:flex-none flex items-center justify-center space-x-2 text-xs font-bold text-slate-700 hover:text-slate-900 bg-white border border-gray-200 rounded-xl px-3 sm:px-4 py-2.5 shadow-sm transition hover:bg-gray-50 cursor-pointer"> Kembali + + + + + @can('qma.vehicles.create') + @endcan
@@ -825,5 +851,31 @@ } } }); + + // Dropdown Menu Ekspor Unit Support Kategori Ini + function toggleSupportUnitsExportMenu(event) { + event.stopPropagation(); + const menu = document.getElementById('exportMenuSupportUnits'); + if (menu) { + menu.style.display = menu.style.display === 'block' ? 'none' : 'block'; + } + } + + document.addEventListener('click', function(event) { + const container = document.getElementById('exportSupportUnitsDropdownContainer'); + const menu = document.getElementById('exportMenuSupportUnits'); + if (container && !container.contains(event.target)) { + if (menu) { + menu.style.display = 'none'; + } + } + }); + + document.addEventListener('keydown', function(e) { + if (e.key === 'Escape') { + const exportMenu = document.getElementById('exportMenuSupportUnits'); + if (exportMenu) exportMenu.style.display = 'none'; + } + }); @endsection diff --git a/routes/web.php b/routes/web.php index 7d5af09..760e40f 100644 --- a/routes/web.php +++ b/routes/web.php @@ -52,6 +52,8 @@ Route::middleware('auth')->group(function () { Route::prefix('hse')->name('hse.')->group(function () { Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard')->middleware('permission:hse.employees.view'); Route::get('/employees', [EmployeeController::class, 'index'])->name('employees.index')->middleware('permission:hse.employees.view'); + Route::get('/employees/export-excel', [EmployeeController::class, 'exportExcel'])->name('employees.export_excel')->middleware('permission:hse.employees.view'); + Route::get('/employees/export-pdf', [EmployeeController::class, 'exportPdf'])->name('employees.export_pdf')->middleware('permission:hse.employees.view'); Route::post('/employees', [EmployeeController::class, 'store'])->name('employees.store')->middleware('permission:hse.employees.create'); Route::post('/employees/{id}', [EmployeeController::class, 'update'])->name('employees.update')->middleware('permission:hse.employees.edit'); }); @@ -63,30 +65,46 @@ Route::middleware('auth')->group(function () { // Halaman Data Kendaraan Terpisah: Light Vehicle (LV) dan Unit Support Route::get('/vehicles', [VehicleController::class, 'index'])->name('vehicles.index')->middleware('permission:qma.vehicles.view'); Route::get('/vehicles/light-vehicle', [VehicleController::class, 'indexLv'])->name('vehicles.lv')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/light-vehicle/export-excel', [VehicleController::class, 'exportLvExcel'])->name('vehicles.lv.export_excel')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/light-vehicle/export-pdf', [VehicleController::class, 'exportLvPdf'])->name('vehicles.lv.export_pdf')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support', [VehicleController::class, 'indexSupport'])->name('vehicles.support')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/export-excel', [VehicleController::class, 'exportSupportExcel'])->name('vehicles.support.export_excel')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/export-pdf', [VehicleController::class, 'exportSupportPdf'])->name('vehicles.support.export_pdf')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/{id}/units', [VehicleController::class, 'indexSupportUnits'])->name('vehicles.support.units')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/{id}/units/export-excel', [VehicleController::class, 'exportSupportUnitsExcel'])->name('vehicles.support.units.export_excel')->middleware('permission:qma.vehicles.view'); + Route::get('/vehicles/unit-support/{id}/units/export-pdf', [VehicleController::class, 'exportSupportUnitsPdf'])->name('vehicles.support.units.export_pdf')->middleware('permission:qma.vehicles.view'); Route::post('/vehicles/unit-support/{id}/units', [VehicleController::class, 'storeSupportUnit'])->name('vehicles.support.units.store')->middleware('permission:qma.vehicles.create'); Route::post('/vehicles', [VehicleController::class, 'store'])->name('vehicles.store')->middleware('permission:qma.vehicles.create'); Route::post('/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit'); Route::delete('/vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy')->middleware('permission:qma.vehicles.delete'); Route::get('/activity-log', [ActivityLogController::class, 'index'])->name('activity.log')->middleware('permission:qma.logs.view'); + Route::get('/activity-log/export-excel', [ActivityLogController::class, 'exportExcel'])->name('activity.export_excel')->middleware('permission:qma.logs.view'); + Route::get('/activity-log/export-pdf', [ActivityLogController::class, 'exportPdf'])->name('activity.export_pdf')->middleware('permission:qma.logs.view'); Route::get('/activity-summary', [ActivityLogController::class, 'summary'])->name('activity.summary')->middleware('permission:qma.summary.view'); + Route::get('/activity-summary/export-excel', [ActivityLogController::class, 'exportSummaryExcel'])->name('activity.summary.export_excel')->middleware('permission:qma.summary.view'); + Route::get('/activity-summary/export-pdf', [ActivityLogController::class, 'exportSummaryPdf'])->name('activity.summary.export_pdf')->middleware('permission:qma.summary.view'); // Log Pemeriksaan P2H Unit Support & Approval Admin QMA - Route::get('/p2h-records', [P2hInspectionController::class, 'index'])->name('p2h.index')->middleware('permission:qma.vehicles.view'); - Route::get('/p2h-summary', [P2hInspectionController::class, 'summary'])->name('p2h.summary')->middleware('permission:qma.vehicles.view'); - Route::get('/p2h-records/{id}', [P2hInspectionController::class, 'show'])->name('p2h.show')->middleware('permission:qma.vehicles.view'); - Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve')->middleware('permission:qma.vehicles.edit'); - Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.vehicles.edit'); + Route::get('/p2h-records', [P2hInspectionController::class, 'index'])->name('p2h.index')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-records/export-excel', [P2hInspectionController::class, 'exportExcel'])->name('p2h.export_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-records/export-pdf', [P2hInspectionController::class, 'exportPdf'])->name('p2h.export_pdf')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-summary', [P2hInspectionController::class, 'summary'])->name('p2h.summary')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-summary/export-excel', [P2hInspectionController::class, 'exportSummaryExcel'])->name('p2h.summary.export_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-summary/export-pdf', [P2hInspectionController::class, 'exportSummaryPdf'])->name('p2h.summary.export_pdf')->middleware('permission:qma.p2h.view|qma.vehicles.view'); + Route::get('/p2h-records/{id}', [P2hInspectionController::class, 'show'])->name('p2h.show')->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}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.p2h.approve|qma.vehicles.edit'); // Master 28 Template Checksheet P2H & Kelola Pertanyaan - Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.vehicles.view'); - Route::get('/p2h-templates/{id}', [P2hTemplateController::class, 'show'])->name('p2h.templates.show')->middleware('permission:qma.vehicles.view'); - Route::post('/p2h-templates/{templateId}/items', [P2hTemplateController::class, 'storeItem'])->name('p2h.templates.items.store')->middleware('permission:qma.vehicles.create'); - Route::match(['PUT', 'POST'], '/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'updateItem'])->name('p2h.templates.items.update')->middleware('permission:qma.vehicles.edit'); - Route::delete('/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'destroyItem'])->name('p2h.templates.items.destroy')->middleware('permission:qma.vehicles.delete'); - Route::post('/p2h-templates/{templateId}/sections/reorder', [P2hTemplateController::class, 'reorderSections'])->name('p2h.templates.sections.reorder')->middleware('permission:qma.vehicles.edit'); + Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.p2h.templates|qma.vehicles.view'); + Route::get('/p2h-templates/{id}', [P2hTemplateController::class, 'show'])->name('p2h.templates.show')->middleware('permission:qma.p2h.templates|qma.vehicles.view'); + Route::post('/p2h-templates/{templateId}/items', [P2hTemplateController::class, 'storeItem'])->name('p2h.templates.items.store')->middleware('permission:qma.p2h.templates|qma.vehicles.create'); + Route::match(['PUT', 'POST'], '/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'updateItem'])->name('p2h.templates.items.update')->middleware('permission:qma.p2h.templates|qma.vehicles.edit'); + Route::delete('/p2h-templates/{templateId}/items/{itemId}', [P2hTemplateController::class, 'destroyItem'])->name('p2h.templates.items.destroy')->middleware('permission:qma.p2h.templates|qma.vehicles.delete'); + Route::post('/p2h-templates/{templateId}/sections/reorder', [P2hTemplateController::class, 'reorderSections'])->name('p2h.templates.sections.reorder')->middleware('permission:qma.p2h.templates|qma.vehicles.edit'); }); // 4. Modul Private Guard (PG): Admin PG & Pos Gerbang Satpam @@ -94,11 +112,15 @@ Route::middleware('auth')->group(function () { // Modul Admin PG (Dashboard, Data Satpam & Log Verifikasi Gerbang) Route::get('/dashboard', [PgDashboardController::class, 'index'])->name('dashboard')->middleware('permission:pg.guards.view'); Route::get('/guards', [SecurityGuardController::class, 'index'])->name('guards.index')->middleware('permission:pg.guards.view'); + Route::get('/guards/export-excel', [SecurityGuardController::class, 'exportExcel'])->name('guards.export_excel')->middleware('permission:pg.guards.view'); + Route::get('/guards/export-pdf', [SecurityGuardController::class, 'exportPdf'])->name('guards.export_pdf')->middleware('permission:pg.guards.view'); Route::post('/guards', [SecurityGuardController::class, 'store'])->name('guards.store')->middleware('permission:pg.guards.create'); Route::post('/guards/{id}', [SecurityGuardController::class, 'update'])->name('guards.update')->middleware('permission:pg.guards.edit'); Route::post('/guards/{id}/toggle', [SecurityGuardController::class, 'toggleStatus'])->name('guards.toggle')->middleware('permission:pg.guards.toggle'); Route::delete('/guards/{id}', [SecurityGuardController::class, 'destroy'])->name('guards.destroy')->middleware('permission:pg.guards.delete'); Route::get('/verification-logs', [VerificationLogController::class, 'index'])->name('logs.index')->middleware('permission:pg.logs.view'); + Route::get('/verification-logs/export-excel', [VerificationLogController::class, 'exportExcel'])->name('logs.export_excel')->middleware('permission:pg.logs.view'); + Route::get('/verification-logs/export-pdf', [VerificationLogController::class, 'exportPdf'])->name('logs.export_pdf')->middleware('permission:pg.logs.view'); // Verifikasi Pos Gerbang (Khusus Petugas Satpam Pos Gerbang) Route::get('/gate-inspection', [GateInspectionController::class, 'index'])->name('gate.inspection')->middleware('permission:gate.inspect'); @@ -108,16 +130,16 @@ Route::middleware('auth')->group(function () { }); // 5. Modul Pengisian Form P2H Unit Support (Operator Wajib Login) - Route::prefix('p2h')->name('p2h.')->group(function () { + Route::prefix('p2h')->name('p2h.')->middleware('permission:employee.p2h|qma.vehicles.view')->group(function () { Route::get('/', [P2hFormController::class, 'index'])->name('index'); Route::get('/{code}', [P2hFormController::class, 'show'])->name('form'); Route::post('/{code}', [P2hFormController::class, 'store'])->name('store'); }); // 6. Modul Karyawan (Dashboard, P2H, Timesheet) - Route::get('/karyawan/dashboard', [\App\Http\Controllers\Employee\DashboardController::class, 'index'])->name('employee.dashboard'); - Route::get('/timesheet', [VehicleActivityFormController::class, 'index'])->name('timesheet.index'); - Route::get('/mobilisasi', [VehicleActivityFormController::class, 'index'])->name('mobilisasi.index'); + Route::get('/karyawan/dashboard', [\App\Http\Controllers\Employee\DashboardController::class, 'index'])->name('employee.dashboard')->middleware('permission:employee.dashboard|qma.vehicles.view'); + Route::get('/timesheet', [VehicleActivityFormController::class, 'index'])->name('timesheet.index')->middleware('permission:employee.timesheet|qma.vehicles.view'); + Route::get('/mobilisasi', [VehicleActivityFormController::class, 'index'])->name('mobilisasi.index')->middleware('permission:employee.timesheet|qma.vehicles.view'); // 7. Modul Profil Saya (Seluruh Pengguna Terautentikasi) Route::get('/profile', [ProfileController::class, 'index'])->name('profile.index'); diff --git a/tests/Feature/HseSimperExportTest.php b/tests/Feature/HseSimperExportTest.php new file mode 100644 index 0000000..a6a9a33 --- /dev/null +++ b/tests/Feature/HseSimperExportTest.php @@ -0,0 +1,112 @@ + 'hse_admin', 'guard_name' => 'web']); + $permissionView = Permission::firstOrCreate(['name' => 'hse.employees.view', 'guard_name' => 'web']); + $roleHse->givePermissionTo($permissionView); + + $this->hseAdmin = User::factory()->create(); + $this->hseAdmin->assignRole('hse_admin'); + + $this->unauthorizedUser = User::factory()->create(); + + // Seed sample employees + Employee::create([ + 'nik' => '10001', + 'name' => 'Budi Operator', + 'position' => 'Operator Excavator', + 'unit_kerja' => 'Operasional', + 'division' => 'Alat Berat', + 'is_operator' => true, + 'simper_expired_at' => now()->addMonths(6)->toDateString(), + ]); + + Employee::create([ + 'nik' => '10002', + 'name' => 'Siti Staff', + 'position' => 'Admin Keuangan', + 'unit_kerja' => 'Kantor Utama', + 'division' => 'Finance', + 'is_operator' => false, + 'simper_expired_at' => null, + ]); + } + + public function test_admin_hse_can_export_simper_excel(): void + { + $response = $this->actingAs($this->hseAdmin) + ->get(route('hse.employees.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Data_Simper_', $response->headers->get('Content-Disposition')); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_hse_can_export_simper_excel_with_filters(): void + { + $response = $this->actingAs($this->hseAdmin) + ->get(route('hse.employees.export_excel', [ + 'driver_status' => 'driver', + 'simper_status' => 'valid', + 'search' => 'Budi', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + } + + public function test_admin_hse_can_export_simper_pdf(): void + { + $response = $this->actingAs($this->hseAdmin) + ->get(route('hse.employees.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('Laporan_Daftar_Simper_', (string) $response->headers->get('Content-Disposition')); + $this->assertStringStartsWith('%PDF-', $response->getContent()); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_hse_can_export_simper_pdf_with_driver_filter(): void + { + $response = $this->actingAs($this->hseAdmin) + ->get(route('hse.employees.export_pdf', ['driver_status' => 'driver'])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringStartsWith('%PDF-', $response->getContent()); + $this->assertNotEmpty($response->getContent()); + $this->assertStringContainsString('Laporan_Daftar_Simper_', (string) $response->headers->get('Content-Disposition')); + } + + public function test_unauthorized_user_cannot_export_simper(): void + { + $responseExcel = $this->actingAs($this->unauthorizedUser) + ->get(route('hse.employees.export_excel')); + $responseExcel->assertStatus(403); + + $responsePdf = $this->actingAs($this->unauthorizedUser) + ->get(route('hse.employees.export_pdf')); + $responsePdf->assertStatus(403); + } +} diff --git a/tests/Feature/PgExportTest.php b/tests/Feature/PgExportTest.php new file mode 100644 index 0000000..76117e2 --- /dev/null +++ b/tests/Feature/PgExportTest.php @@ -0,0 +1,262 @@ +seed(RolePermissionSeeder::class); + + $this->pgAdmin = User::factory()->create([ + 'name' => 'Admin PG Test', + 'username' => 'pg_test', + 'role' => 'pg_admin', + ]); + $this->pgAdmin->assignRole('pg_admin'); + + $this->unauthorizedUser = User::factory()->create([ + 'name' => 'Unauthorized User', + 'username' => 'unauthorized_test', + 'role' => 'employee', + ]); + + $this->gate1 = Gate::create([ + 'name' => 'Pos Gerbang Utama', + 'code' => 'GATE-01', + 'location' => 'Main Entrance', + 'is_active' => true, + ]); + + $this->gate2 = Gate::create([ + 'name' => 'Pos Gerbang Bendungan', + 'code' => 'GATE-02', + 'location' => 'Dam Access', + 'is_active' => true, + ]); + + $userGuard1 = User::factory()->create([ + 'name' => 'Budi Santoso', + 'username' => 'SEC001', + 'role' => 'gate_officer', + 'gate_id' => $this->gate1->id, + ]); + + $this->guard1 = SecurityGuard::create([ + 'badge_id' => 'SEC001', + 'name' => 'Budi Santoso', + 'team' => 1, + 'gate_id' => $this->gate1->id, + 'user_id' => $userGuard1->id, + 'is_active' => true, + ]); + + $userGuard2 = User::factory()->create([ + 'name' => 'Agus Wijaya', + 'username' => 'SEC002', + 'role' => 'gate_officer', + 'gate_id' => $this->gate2->id, + ]); + + $this->guard2 = SecurityGuard::create([ + 'badge_id' => 'SEC002', + 'name' => 'Agus Wijaya', + 'team' => 2, + 'gate_id' => $this->gate2->id, + 'user_id' => $userGuard2->id, + 'is_active' => false, + ]); + + $this->vehicle = Vehicle::create([ + 'code' => 'LV-01', + 'category' => 'light_vehicle', + 'brand' => 'Toyota', + 'brand_type' => 'Toyota Hilux 4x4', + 'unit_type' => 'Double Cabin', + 'license_plate' => 'BH 1234 XY', + 'ownership' => 'PT KMH', + 'department' => 'Civil & Inviro', + 'status' => 'Operation', + 'current_km' => 15000, + ]); + + $this->driver = Employee::create([ + 'name' => 'Rahmat Hidayat', + 'nik' => 'KMH-1001', + 'department' => 'Civil & Inviro', + 'position' => 'Driver', + 'status' => 'active', + ]); + } + + public function test_admin_pg_can_export_guards_excel(): void + { + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.guards.export_excel')); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('data_satpam_', $response->headers->get('Content-Disposition')); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_pg_can_export_guards_excel_with_filters(): void + { + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.guards.export_excel', [ + 'team' => 1, + 'gate_id' => $this->gate1->id, + 'search' => 'Budi', + ])); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_pg_can_export_guards_pdf(): void + { + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.guards.export_pdf')); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline;', $response->headers->get('Content-Disposition')); + $this->assertStringContainsString('laporan_data_satpam_', $response->headers->get('Content-Disposition')); + $this->assertStringStartsWith('%PDF-', $response->getContent()); + } + + public function test_admin_pg_can_export_verification_logs_excel(): void + { + VehicleActivity::create([ + 'transaction_no' => 'TRX-20261016-0001', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate1->id, + 'security_guard_id' => $this->guard1->id, + 'direction' => 'out', + 'previous_km' => 14950, + 'current_km' => 15000, + 'distance' => 50, + 'purpose' => 'Mobilisasi material ke Dam Site', + 'validation_status' => 'approved', + 'recorded_at' => Carbon::now(), + 'validated_at' => Carbon::now(), + ]); + + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.logs.export_excel')); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('log_aktivitas_gerbang_', $response->headers->get('Content-Disposition')); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_pg_can_export_verification_logs_excel_with_filters(): void + { + VehicleActivity::create([ + 'transaction_no' => 'TRX-20261016-0002', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate1->id, + 'security_guard_id' => $this->guard1->id, + 'direction' => 'in', + 'previous_km' => 15000, + 'current_km' => 15050, + 'distance' => 50, + 'purpose' => 'Kembali ke workshop', + 'validation_status' => 'rejected', + 'rejection_note' => 'Odometer tidak sesuai', + 'recorded_at' => Carbon::now(), + 'validated_at' => Carbon::now(), + ]); + + $today = Carbon::today()->toDateString(); + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.logs.export_excel', [ + 'team' => 1, + 'gate_id' => $this->gate1->id, + 'direction' => 'in', + 'status' => 'rejected', + 'start_date' => $today, + 'end_date' => $today, + 'search' => 'TRX', + ])); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertNotEmpty($response->getContent()); + } + + public function test_admin_pg_can_export_verification_logs_pdf(): void + { + VehicleActivity::create([ + 'transaction_no' => 'TRX-20261016-0003', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate1->id, + 'security_guard_id' => $this->guard1->id, + 'direction' => 'out', + 'previous_km' => 15050, + 'current_km' => 15100, + 'distance' => 50, + 'purpose' => 'Inspeksi lapangan', + 'validation_status' => 'approved', + 'recorded_at' => Carbon::now(), + 'validated_at' => Carbon::now(), + ]); + + $response = $this->actingAs($this->pgAdmin) + ->get(route('pg.logs.export_pdf')); + + $response->assertOk(); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline;', $response->headers->get('Content-Disposition')); + $this->assertStringContainsString('log_verifikasi_gerbang_', $response->headers->get('Content-Disposition')); + $this->assertStringStartsWith('%PDF-', $response->getContent()); + } + + public function test_unauthorized_user_cannot_export_pg_guards_or_logs(): void + { + $this->actingAs($this->unauthorizedUser) + ->get(route('pg.guards.export_excel')) + ->assertForbidden(); + + $this->actingAs($this->unauthorizedUser) + ->get(route('pg.guards.export_pdf')) + ->assertForbidden(); + + $this->actingAs($this->unauthorizedUser) + ->get(route('pg.logs.export_excel')) + ->assertForbidden(); + + $this->actingAs($this->unauthorizedUser) + ->get(route('pg.logs.export_pdf')) + ->assertForbidden(); + } +} diff --git a/tests/Feature/QmaActivityAndP2hExportTest.php b/tests/Feature/QmaActivityAndP2hExportTest.php new file mode 100644 index 0000000..82ec164 --- /dev/null +++ b/tests/Feature/QmaActivityAndP2hExportTest.php @@ -0,0 +1,236 @@ +seed(RolePermissionSeeder::class); + + $this->qmaAdmin = User::factory()->create([ + 'name' => 'Admin QMA Test', + 'username' => 'qma_test', + 'role' => 'qma_admin', + ]); + $this->qmaAdmin->assignRole('qma_admin'); + + $this->unauthorizedUser = User::factory()->create([ + 'name' => 'Unauthorized User', + 'username' => 'unauthorized_test', + 'role' => 'employee', + ]); + + $this->lvVehicle = Vehicle::create([ + 'code' => 'LV-01', + 'category' => 'light_vehicle', + 'brand' => 'Toyota', + 'brand_type' => 'Toyota Hilux 4x4', + 'unit_type' => 'Double Cabin', + 'license_plate' => 'BH 1234 XY', + 'ownership' => 'PT KMH', + 'department' => 'Civil & Inviro', + 'status' => 'Operation', + 'current_km' => 12500, + ]); + + $this->supportVehicle = Vehicle::create([ + 'code' => 'EXC-01', + 'category' => 'unit_support', + 'unit_category' => 'Excavator', + 'brand' => 'Komatsu', + 'brand_type' => 'Komatsu PC200-8', + 'location' => 'Main Dam', + 'status' => 'Operation', + 'current_km' => 2400, + ]); + + $this->driver = Employee::create([ + 'nik' => '20001', + 'name' => 'Doni Driver', + 'position' => 'Driver LV', + 'unit_kerja' => 'Operasional', + 'is_operator' => true, + 'simper_expired_at' => now()->addYear()->toDateString(), + ]); + + $this->gate = Gate::create([ + 'name' => 'Main Gate KMH', + 'code' => 'MG-01', + 'location' => 'Pintu Masuk Utama', + 'is_active' => true, + ]); + + $this->guard = SecurityGuard::create([ + 'name' => 'Bambang Security', + 'badge_id' => 'SEC-001', + 'phone_number' => '08123456789', + 'status' => 'active', + 'assigned_gate_id' => $this->gate->id, + 'current_shift' => 'Shift 1', + ]); + + $this->template = P2hTemplate::create([ + 'name' => 'Checksheet Excavator', + 'code' => 'P2H-EXC', + 'is_active' => true, + ]); + + // Seed Sample Vehicle Activity + VehicleActivity::create([ + 'transaction_no' => 'TRX-ACT-001', + 'vehicle_id' => $this->lvVehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 12450, + 'current_km' => 12500, + 'distance' => 50, + 'purpose' => 'Antar Logistik ke Quarry 2', + 'recorded_at' => now(), + 'security_guard_id' => $this->guard->id, + 'validation_status' => 'approved', + 'validated_at' => now(), + ]); + + // Seed Sample P2H Record + P2hRecord::create([ + 'transaction_no' => 'P2H-20261016-0001', + 'vehicle_id' => $this->supportVehicle->id, + 'employee_id' => $this->driver->id, + 'template_id' => $this->template->id, + 'shift' => 'Shift 1', + 'start_hm' => 2400.5, + 'summary_condition' => 'normal', + 'defect_count' => 0, + 'general_notes' => 'Kondisi mesin dan hidrolik baik', + 'validation_status' => 'approved', + 'validated_by' => $this->qmaAdmin->id, + 'validated_at' => now(), + 'inspected_at' => now(), + ]); + } + + public function test_admin_qma_can_export_activity_log_excel(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Timesheet_LV_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_activity_log_excel_with_filters(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.export_excel', [ + 'direction' => 'out', + 'gate_id' => $this->gate->id, + 'status' => 'approved', + 'search' => 'Hilux', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $response->getContent()); + } + + public function test_admin_qma_can_export_activity_log_pdf(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline; filename="Laporan_Timesheet_LV_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith('%PDF-', $content); + $this->assertNotEmpty($content); + } + + public function test_admin_qma_can_export_p2h_records_excel(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_P2H_Unit_Support_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_p2h_records_excel_with_filters(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.export_excel', [ + 'validation_status' => 'approved', + 'summary_condition' => 'normal', + 'search' => 'EXC-01', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $response->getContent()); + } + + public function test_admin_qma_can_export_p2h_records_pdf(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline; filename="Laporan_P2H_Unit_Support_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith('%PDF-', $content); + $this->assertNotEmpty($content); + } + + public function test_unauthorized_user_cannot_export_activity_and_p2h(): void + { + $routes = [ + route('qma.activity.export_excel'), + route('qma.activity.export_pdf'), + route('qma.p2h.export_excel'), + route('qma.p2h.export_pdf'), + ]; + + foreach ($routes as $routeUrl) { + $response = $this->actingAs($this->unauthorizedUser)->get($routeUrl); + $response->assertStatus(403); + } + } +} diff --git a/tests/Feature/QmaSummaryExportTest.php b/tests/Feature/QmaSummaryExportTest.php new file mode 100644 index 0000000..52f1b81 --- /dev/null +++ b/tests/Feature/QmaSummaryExportTest.php @@ -0,0 +1,235 @@ +seed(RolePermissionSeeder::class); + + $this->qmaAdmin = User::factory()->create([ + 'name' => 'Admin QMA Test', + 'username' => 'qma_test', + 'role' => 'qma_admin', + ]); + $this->qmaAdmin->assignRole('qma_admin'); + + $this->unauthorizedUser = User::factory()->create([ + 'name' => 'Unauthorized User', + 'username' => 'unauthorized_test', + 'role' => 'employee', + ]); + + $this->lvVehicle = Vehicle::create([ + 'code' => 'LV-01', + 'category' => 'light_vehicle', + 'brand' => 'Toyota', + 'brand_type' => 'Toyota Hilux 4x4', + 'unit_type' => 'Double Cabin', + 'license_plate' => 'BH 1234 XY', + 'ownership' => 'PT KMH', + 'department' => 'Civil & Inviro', + 'status' => 'Operation', + 'current_km' => 12500, + ]); + + $this->supportVehicle = Vehicle::create([ + 'code' => 'EXC-01', + 'category' => 'unit_support', + 'unit_category' => 'Excavator', + 'brand' => 'Komatsu', + 'brand_type' => 'Komatsu PC200-8', + 'location' => 'Main Dam', + 'status' => 'Operation', + 'current_km' => 2400, + ]); + + $this->driver = Employee::create([ + 'nik' => '20001', + 'name' => 'Doni Driver', + 'position' => 'Driver LV', + 'unit_kerja' => 'Operasional', + 'is_operator' => true, + 'simper_expired_at' => now()->addYear()->toDateString(), + ]); + + $this->gate = Gate::create([ + 'name' => 'Main Gate KMH', + 'code' => 'MG-01', + 'location' => 'Pintu Masuk Utama', + 'is_active' => true, + ]); + + $this->guard = SecurityGuard::create([ + 'name' => 'Bambang Security', + 'badge_id' => 'SEC-001', + 'phone_number' => '08123456789', + 'status' => 'active', + 'assigned_gate_id' => $this->gate->id, + 'current_shift' => 'Shift 1', + ]); + + $this->template = P2hTemplate::create([ + 'name' => 'Checksheet Excavator', + 'code' => 'P2H-EXC', + 'is_active' => true, + ]); + + // Seed Sample Vehicle Activities + VehicleActivity::create([ + 'transaction_no' => 'TRX-ACT-001', + 'vehicle_id' => $this->lvVehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 12450, + 'current_km' => 12500, + 'distance' => 50, + 'purpose' => 'Antar Logistik ke Quarry 2', + 'recorded_at' => now(), + 'security_guard_id' => $this->guard->id, + 'validation_status' => 'approved', + 'validated_at' => now(), + ]); + + // Seed Sample P2H Record + P2hRecord::create([ + 'transaction_no' => 'P2H-20261016-0001', + 'vehicle_id' => $this->supportVehicle->id, + 'employee_id' => $this->driver->id, + 'template_id' => $this->template->id, + 'shift' => 'Shift 1', + 'start_hm' => 2400.5, + 'summary_condition' => 'normal', + 'defect_count' => 0, + 'general_notes' => 'Kondisi alat prima', + 'validation_status' => 'approved', + 'validated_by' => $this->qmaAdmin->id, + 'validated_at' => now(), + 'inspected_at' => now(), + ]); + } + + public function test_admin_qma_can_export_activity_summary_excel(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.summary.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Summary_Aktivitas_Kendaraan_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_activity_summary_excel_with_filters(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.summary.export_excel', [ + 'type' => 'lv', + 'gate_id' => $this->gate->id, + 'search' => 'Hilux', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $response->getContent()); + } + + public function test_admin_qma_can_export_activity_summary_pdf(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.activity.summary.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline; filename="Laporan_Summary_Aktivitas_Kendaraan_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith('%PDF-', $content); + $this->assertNotEmpty($content); + } + + public function test_admin_qma_can_export_p2h_summary_excel(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.summary.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Summary_P2H_Unit_Support_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_p2h_summary_excel_with_filters(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.summary.export_excel', [ + 'validation_status' => 'approved', + 'shift' => 'Shift 1', + 'search' => 'EXC-01', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $response->getContent()); + } + + public function test_admin_qma_can_export_p2h_summary_pdf(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.p2h.summary.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline; filename="Laporan_Summary_P2H_Unit_Support_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith('%PDF-', $content); + $this->assertNotEmpty($content); + } + + public function test_unauthorized_user_cannot_export_qma_summaries(): void + { + $routes = [ + route('qma.activity.summary.export_excel'), + route('qma.activity.summary.export_pdf'), + route('qma.p2h.summary.export_excel'), + route('qma.p2h.summary.export_pdf'), + ]; + + foreach ($routes as $routeUrl) { + $response = $this->actingAs($this->unauthorizedUser)->get($routeUrl); + $response->assertStatus(403); + } + } +} diff --git a/tests/Feature/QmaVehicleExportTest.php b/tests/Feature/QmaVehicleExportTest.php new file mode 100644 index 0000000..59dd248 --- /dev/null +++ b/tests/Feature/QmaVehicleExportTest.php @@ -0,0 +1,230 @@ +seed(RolePermissionSeeder::class); + + $this->qmaAdmin = User::factory()->create([ + 'name' => 'Admin QMA Test', + 'username' => 'qma_test', + 'role' => 'qma_admin', + ]); + $this->qmaAdmin->assignRole('qma_admin'); + + $this->unauthorizedUser = User::factory()->create([ + 'name' => 'Unauthorized User', + 'username' => 'unauthorized_test', + 'role' => 'employee', + ]); + + // Seed Sample Light Vehicle + $this->lvVehicle = Vehicle::create([ + 'code' => 'LV-01', + 'category' => 'light_vehicle', + 'brand' => 'Toyota', + 'brand_type' => 'Toyota Hilux Double Cabin 4x4', + 'unit_type' => 'Double Cabin', + 'license_plate' => 'BH 8888 KM', + 'ownership' => 'PT KMH', + 'department' => 'Civil & Inviro', + 'division' => 'Operasional', + 'status' => 'Operation', + 'current_km' => 15400, + ]); + + // Seed Sample Unit Support Category + $this->supportCategory = Vehicle::create([ + 'code' => 'CAT-EXC-01', + 'category' => 'unit_support', + 'unit_category' => 'Excavator', + 'brand' => 'Komatsu', + 'brand_type' => 'Komatsu PC200-8', + 'model_number' => 'PC200-8', + 'location' => 'Main Dam KMH', + 'ownership' => 'PT KMH Project', + 'status' => 'Operation', + 'parent_id' => null, + ]); + } + + public function test_admin_qma_can_export_lv_excel(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.lv.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Data_Light_Vehicle_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_lv_excel_with_filters(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.lv.export_excel', [ + 'status' => 'Operation', + 'search' => 'Hilux', + ])); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $response->getContent()); + } + + public function test_admin_qma_can_export_lv_pdf(): void + { + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.lv.export_pdf')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('inline; filename="Laporan_Light_Vehicle_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith('%PDF-', $content); + $this->assertNotEmpty($content); + } + + public function test_admin_qma_can_export_support_excel_with_category_fallback(): void + { + // Saat belum ada unit fisik, mengekspor daftar master kategori + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Kategori_Unit_Support_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_support_excel_with_physical_units(): void + { + // Buat unit fisik alat berat di bawah kategori + Vehicle::create([ + 'code' => 'EXC-01', + 'category' => 'unit_support', + 'parent_id' => $this->supportCategory->id, + 'brand_type' => 'Komatsu PC200-8', + 'serial_number' => 'KMH-SN-998811', + 'production_year' => 2023, + 'license_plate' => 'BH 1234 EX', + 'location' => 'Powerhouse Intake', + 'current_km' => 3200, + 'status' => 'Operation', + 'silo_document' => 'silo_docs/sample.pdf', + ]); + + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.export_excel')); + + $response->assertStatus(200); + $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringContainsString('Laporan_Unit_Support_Lengkap_', (string) $response->headers->get('Content-Disposition')); + + $content = $response->getContent(); + $this->assertStringStartsWith("PK\x03\x04", $content); + } + + public function test_admin_qma_can_export_support_pdf(): void + { + // 1. Fallback master kategori + $responseFallback = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.export_pdf')); + + $responseFallback->assertStatus(200); + $responseFallback->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringStartsWith('%PDF-', $responseFallback->getContent()); + + // 2. Dengan unit fisik + Vehicle::create([ + 'code' => 'EXC-02', + 'category' => 'unit_support', + 'parent_id' => $this->supportCategory->id, + 'brand_type' => 'Komatsu PC200-8', + 'serial_number' => 'KMH-SN-776655', + 'production_year' => 2022, + 'location' => 'Quarry 2', + 'current_km' => 1500, + 'status' => 'Standby', + ]); + + $responsePhysical = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.export_pdf')); + + $responsePhysical->assertStatus(200); + $responsePhysical->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('Laporan_Unit_Support_', (string) $responsePhysical->headers->get('Content-Disposition')); + $this->assertStringStartsWith('%PDF-', $responsePhysical->getContent()); + } + + public function test_admin_qma_can_export_category_specific_units_excel_and_pdf(): void + { + Vehicle::create([ + 'code' => 'EXC-03', + 'category' => 'unit_support', + 'parent_id' => $this->supportCategory->id, + 'brand_type' => 'Komatsu PC200-8', + 'serial_number' => 'KMH-SN-443322', + 'production_year' => 2024, + 'location' => 'Dam Site', + 'current_km' => 450, + 'status' => 'Operation', + ]); + + // Excel + $responseExcel = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.units.export_excel', $this->supportCategory->id)); + + $responseExcel->assertStatus(200); + $responseExcel->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + $this->assertStringStartsWith("PK\x03\x04", $responseExcel->getContent()); + + // PDF + $responsePdf = $this->actingAs($this->qmaAdmin) + ->get(route('qma.vehicles.support.units.export_pdf', $this->supportCategory->id)); + + $responsePdf->assertStatus(200); + $responsePdf->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringStartsWith('%PDF-', $responsePdf->getContent()); + } + + public function test_unauthorized_user_cannot_export_qma_vehicles(): void + { + $routes = [ + route('qma.vehicles.lv.export_excel'), + route('qma.vehicles.lv.export_pdf'), + route('qma.vehicles.support.export_excel'), + route('qma.vehicles.support.export_pdf'), + route('qma.vehicles.support.units.export_excel', $this->supportCategory->id), + route('qma.vehicles.support.units.export_pdf', $this->supportCategory->id), + ]; + + foreach ($routes as $routeUrl) { + $response = $this->actingAs($this->unauthorizedUser)->get($routeUrl); + $response->assertStatus(403); + } + } +} diff --git a/tests/Feature/SuperAdminRbacTest.php b/tests/Feature/SuperAdminRbacTest.php index 0c06b9c..48c0db4 100644 --- a/tests/Feature/SuperAdminRbacTest.php +++ b/tests/Feature/SuperAdminRbacTest.php @@ -166,17 +166,32 @@ class SuperAdminRbacTest extends TestCase { $superAdmin = User::where('username', 'superadmin')->first(); - // HSE Dashboard + // 1. HSE Module $response = $this->actingAs($superAdmin)->get(route('hse.dashboard')); $response->assertOk(); + $this->actingAs($superAdmin)->get(route('hse.employees.index'))->assertOk(); - // QMA Dashboard + // 2. QMA Module (LV, Support, Activity Logs, P2H Records, P2H Templates) $response = $this->actingAs($superAdmin)->get(route('qma.dashboard')); $response->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.vehicles.lv'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.vehicles.support'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.activity.log'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.activity.summary'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.p2h.index'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.p2h.summary'))->assertOk(); + $this->actingAs($superAdmin)->get(route('qma.p2h.templates'))->assertOk(); - // PG Dashboard + // 3. PG Module (Guards, Logs, Gate Inspection) $response = $this->actingAs($superAdmin)->get(route('pg.dashboard')); $response->assertOk(); + $this->actingAs($superAdmin)->get(route('pg.guards.index'))->assertOk(); + $this->actingAs($superAdmin)->get(route('pg.logs.index'))->assertOk(); + $this->actingAs($superAdmin)->get(route('pg.gate.inspection'))->assertOk(); + + // 4. Employee & P2H Public/Operator Module + $this->actingAs($superAdmin)->get(route('p2h.index'))->assertOk(); + $this->actingAs($superAdmin)->get(route('employee.dashboard'))->assertOk(); } public function test_permission_revocation_immediately_blocks_action_and_hides_button(): void