Compare commits

..
14 Commits
Author SHA1 Message Date
Ray1111-aa b8fa1771b9 feat: implement 3-level heavy equipment drilldown and transporter options in unit transfer 2026-11-02 12:00:21 +07:00
Ray1111-aa 8a94e98ed9 fix(p2h): limit pdf signatures to 2 parties (operator and admin qma) and fix overlapping text coordinates 2026-11-02 08:43:43 +07:00
Ray1111-aa 6e84e6106f docs(p2h): clarify general notes label as optional in p2h form 2026-11-02 08:35:02 +07:00
Ray1111-aa bc2215d98e feat(p2h): add comprehensive submit protection to verify all checklist items before form submission 2026-11-02 08:31:36 +07:00
Ray1111-aa a09071f5ed fix(hse): remove syntax error in javascript and restore tambah, ekspor, and impor button functionality 2026-11-02 08:22:31 +07:00
Ray1111-aa e2054dcb8a feat: resolve audit items (multi-simper hse dashboard & export, soft-delete conflict handling, p2h blank initial state, qma breakdown recovery, and exclude lv from transporter) 2026-11-01 23:18:17 +07:00
Ray1111-aa aec6c36344 feat: enhance HSE SIMPER renewal modal to read existing user simpers, provide clear dropdown selection, and support sukon 2026-11-01 22:37:06 +07:00
Ray1111-aa 96178971fd feat: timesheet auto hm, sync excel vehicle locations, heavy equipment grouped by type, 2-party bast signature, and compact role permission ui 2026-11-01 22:28:12 +07:00
Ray1111-aa b83a8fa843 feat: fix HSE simper 500 error, enhance PG rejection, P2H wizard, simper renewal, QMA table UI, and nginx upload timeouts 2026-11-01 21:26:22 +07:00
Ray1111-aa bc6213d864 feat(backup): add real-time upload progress bar and single-upload token optimization for converter and direct restore 2026-10-30 15:15:52 +07:00
Ray1111-aa 14298cfff3 build: update compiled production assets in public/build 2026-10-30 14:11:23 +07:00
Ray1111-aa a32e996780 feat(backup): add standalone in-portal .kmh converter to Excel, CSV, and SQL with zero storage retention 2026-10-30 10:29:04 +07:00
Ray1111-aa 721abb56c2 refactor(backup): remove internal reader to keep main application completely clean and decoupled 2026-10-30 10:01:54 +07:00
Ray1111-aa 93baeac001 refactor(backup): streamline kmh reader purely to upload model and remove server file inspect tab 2026-10-30 09:47:14 +07:00
47 changed files with 6731 additions and 2061 deletions
@@ -1,112 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\DatabaseBackupService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class InspectKmhBackupCommand extends Command
{
/**
* The name and signature of the console command.
*/
protected $signature = 'kmh:inspect
{file? : Nama file .kmh di folder backup atau path absolut ke file .kmh}';
/**
* The console command description.
*/
protected $description = 'Inspeksi dan baca isi metadata file backup .kmh terenkripsi tanpa mengubah database';
public function handle(DatabaseBackupService $service): int
{
$input = $this->argument('file');
$backupDir = $service->getBackupDirectory();
if (!$input) {
$files = collect(File::glob($backupDir . '/*.kmh'))
->map(fn($f) => basename($f))
->values()
->all();
if (empty($files)) {
$this->warn("Tidak ada file .kmh di direktori backup ({$backupDir}).");
$this->line("Gunakan: php artisan kmh:inspect /path/ke/file.kmh");
return Command::FAILURE;
}
$input = $this->choice('Pilih file .kmh yang ingin diinspeksi:', $files);
}
// Tentukan path lengkap
$targetPath = File::exists($input)
? $input
: $backupDir . DIRECTORY_SEPARATOR . basename($input);
if (!File::exists($targetPath)) {
$this->error("Berkas .kmh tidak ditemukan pada: {$targetPath}");
return Command::FAILURE;
}
$this->info("Sedang memeriksa & membaca arsip: " . basename($targetPath) . " ...");
try {
$data = $service->inspectKmhFile($targetPath);
$this->newLine();
$this->line("=====================================================================");
$this->info(" HASIL INSPEKSI ARSIP KMH (RKM BACKUP READER)");
$this->line("=====================================================================");
$this->table(
['Parameter', 'Keterangan'],
[
['Nama File', $data['filename']],
['Ukuran Berkas', $data['file_size_human'] . " ({$data['file_size']} bytes)"],
['Format Arsip', $data['format']],
['Sistem Asal', $data['system']],
['Waktu Pembuatan', $data['created_at_human'] . " ({$data['created_at_diff']})"],
['Tipe Backup', $data['type_label']],
['Database Asal', $data['database']],
['Enkripsi & Keamanan', $data['encryption_cipher'] . ' (' . $data['hmac_verification'] . ')'],
['Ukuran SQL Database', $data['sql_size_human']],
['File Media (storage/)', $data['has_media'] ? "{$data['media_file_count']} berkas media" : 'Tidak disertakan'],
['Versi Environment', "Laravel {$data['laravel_version']} / PHP {$data['php_version']}"],
]
);
if (!empty($data['tables'])) {
$this->newLine();
$this->comment(" Daftar Tabel & Jumlah Baris Data (" . count($data['tables']) . " tabel):");
$formattedTables = array_map(function ($t) use ($data) {
$rows = $data['table_details'][$t]['rows_count'] ?? 0;
return "{$t} ({$rows} baris)";
}, $data['tables']);
$chunks = array_chunk($formattedTables, 3);
$rows = array_map(function ($chunk) {
return array_pad($chunk, 3, '');
}, $chunks);
$this->table(['Tabel & Baris', 'Tabel & Baris', 'Tabel & Baris'], $rows);
}
if (!empty($data['media_samples'])) {
$this->newLine();
$this->comment(" Sampel Berkas Media:");
foreach ($data['media_samples'] as $sample) {
$this->line(" - {$sample}");
}
}
$this->newLine();
$this->info("✓ Berkas sah, terenkripsi valid, dan siap dipulihkan jika diperlukan.");
$this->line("=====================================================================");
return Command::SUCCESS;
} catch (\Throwable $e) {
$this->error("Gagal membaca arsip .kmh: " . $e->getMessage());
return Command::FAILURE;
}
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Models\UnitSupportTimesheet;
use App\Models\Vehicle;
use Illuminate\Console\Command;
class RecalculateTimesheetHoursCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'qma:recalculate-timesheet-hours';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Hitung otomatis dan perbarui finish HM serta durasi jam operasional (1 HM = 1 Jam) dari entri kronologis berikutnya';
/**
* Execute the console command.
*/
public function handle(): int
{
$this->info('Memulai rekalkulasi finish HM & jam operasi timesheet unit support...');
$vehicles = Vehicle::whereHas('supportTimesheets')->get();
$totalUpdated = 0;
foreach ($vehicles as $veh) {
$timesheets = UnitSupportTimesheet::where('vehicle_id', $veh->id)
->orderBy('date', 'asc')
->orderBy('start_time', 'asc')
->orderBy('id', 'asc')
->get();
$count = $timesheets->count();
for ($i = 0; $i < $count - 1; $i++) {
$current = $timesheets[$i];
$next = $timesheets[$i + 1];
// Jika current belum memiliki end_meter atau bernilai 0
if ($current->end_meter === null || (float) $current->end_meter == 0) {
if ($next->start_meter !== null && (float) $next->start_meter >= (float) $current->start_meter) {
$diff = (float) $next->start_meter - (float) $current->start_meter;
$current->update([
'end_meter' => $next->start_meter,
'operating_hours' => $diff,
]);
$totalUpdated++;
}
}
}
}
$this->info("Rekalkulasi selesai. Sebanyak {$totalUpdated} entri timesheet berhasil diperbarui.");
return self::SUCCESS;
}
}
@@ -0,0 +1,283 @@
<?php
namespace App\Console\Commands;
use App\Models\Vehicle;
use App\Models\VehicleLocationHistory;
use App\Services\SimpleXlsxImporter;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class SyncExcelVehicleDataCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'qma:sync-excel-locations {--file=Berkas/DATA LOKASI TERBARU RKM KMH.xlsx}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Perbarui lokasi, status site, tipe, dan spesifikasi unit alat berat (Heavy Equipment) dari berkas Excel DATA LOKASI TERBARU RKM KMH';
/**
* Execute the console command.
*/
public function handle(): int
{
$filePath = base_path($this->option('file'));
if (!file_exists($filePath)) {
$this->error("Berkas Excel tidak ditemukan di: {$filePath}");
return self::FAILURE;
}
$this->info("Membaca berkas: {$filePath} ...");
$rows = SimpleXlsxImporter::parse($filePath);
$totalRows = count($rows);
$this->info("Total baris terbaca: {$totalRows}");
if ($totalRows < 2) {
$this->warn('Berkas Excel kosong atau tidak memiliki baris data.');
return self::SUCCESS;
}
$updatedCount = 0;
$createdCount = 0;
DB::beginTransaction();
try {
for ($i = 1; $i < $totalRows; $i++) {
$r = $rows[$i];
$code1 = trim($r[4] ?? '');
if (!$code1) {
continue;
}
$cat = trim($r[2] ?? '') ?: 'SUPPORT';
$type = trim($r[3] ?? '') ?: 'HEAVY EQUIPMENT';
$statusRaw = strtoupper(trim($r[6] ?? ''));
$jenis = strtoupper(trim($r[7] ?? ''));
$lokasiSite = trim($r[8] ?? '');
$plate = trim($r[9] ?? '');
$assetNo = trim($r[10] ?? '');
$brand = trim($r[11] ?? '');
$model = trim($r[12] ?? '');
$serial = trim($r[13] ?? '');
$prodYear = trim($r[16] ?? '');
$lokasiCurrent = trim($r[18] ?? '');
$owner = trim($r[20] ?? '');
// 1. Status Operasional
$status = match ($statusRaw) {
'OPERASI', 'OPERATION' => 'Operation',
'BREAKDOWN' => 'Breakdown',
'STANDBY' => 'Standby',
'MAINTENANCE' => 'Maintenance',
default => 'Standby',
};
// 2. Lokasi & Status Area (Inside / Outside Site)
// Sesuai berkas Excel "DATA LOKASI TERBARU RKM KMH",
// Kolom 8 adalah "LOKASI" tempat unit berada (ADIT 3, POWER HOUSE, VERTICAL SHAFT, dll.)
$finalLocation = $lokasiSite ?: ($lokasiCurrent ?: 'Site Kerinci');
// Klasifikasi site_status berdasarkan lokasi:
// Lokasi eksternal / kontraktor luar / workshop luar -> outside_site
// Lokasi area proyek KMH Kerinci (Adit, Power House, Bendungan, dll.) -> inside_site
$outsideKeywords = [
'PT.', 'HO', 'LAMPUNG', 'JAKARTA', 'CIDAS', 'POSO',
'MEDCO', 'SULINDO', 'BMS', 'BHARA', 'BUKAKA', 'ACEH'
];
$upperLoc = strtoupper($finalLocation);
$isOutside = false;
foreach ($outsideKeywords as $kw) {
if (str_contains($upperLoc, $kw)) {
$isOutside = true;
break;
}
}
$siteStatus = $isOutside ? 'outside_site' : 'inside_site';
// 3. Timesheet Mobile Flag
$isMobile = (str_contains($jenis, 'MOBILE') || $type === 'DUMP TRUCK' || $type === 'LIGHT TRUCK');
// 4. Cari unit di database (cocokkan kode asli, kode tanpa spasi, atau nomor seri)
$cleanCode = preg_replace('/[^a-zA-Z0-9]/', '', $code1);
$vehicle = Vehicle::where('code', $code1)
->orWhereRaw("REPLACE(REPLACE(code, ' ', ''), '-', '') = ?", [$cleanCode])
->first();
if (!$vehicle && !empty($serial) && $serial !== '?') {
$vehicle = Vehicle::where('serial_number', $serial)->first();
}
$cleanBrand = ($brand !== '?' && !empty($brand)) ? $brand : null;
$cleanModel = ($model !== '?' && !empty($model)) ? $model : null;
$cleanSerial = ($serial !== '?' && !empty($serial)) ? $serial : null;
$yearInt = (is_numeric($prodYear) && (int) $prodYear > 1950 && (int) $prodYear < 2100) ? (int) $prodYear : null;
$brandTypeCombined = trim(($cleanBrand ?? '') . ' ' . ($cleanModel ?? ''));
if ($vehicle) {
// Update data unit yang sudah ada
$updatePayload = [
'category' => 'unit_support',
'operational_group' => $cat,
'unit_type' => $type,
'location' => $finalLocation,
'site_status' => $siteStatus,
'status' => $status,
'location_updated_at' => Carbon::now(),
'location_updated_by' => 'Import Berkas Excel Lokasi',
'location_note' => "Pembaruan dari berkas DATA LOKASI TERBARU RKM KMH ({$finalLocation})",
];
if (empty($vehicle->unit_category)) {
$updatePayload['unit_category'] = $vehicle->parent?->unit_category ?: ucwords(strtolower($type));
}
if ($cleanBrand) {
$updatePayload['brand'] = $cleanBrand;
}
if ($cleanModel) {
$updatePayload['model_number'] = $cleanModel;
}
if (empty($vehicle->brand_type) && !empty($brandTypeCombined)) {
$updatePayload['brand_type'] = $brandTypeCombined;
}
if ($cleanSerial && empty($vehicle->serial_number)) {
$updatePayload['serial_number'] = $cleanSerial;
}
if ($yearInt && empty($vehicle->production_year)) {
$updatePayload['production_year'] = $yearInt;
}
if (!empty($plate) && empty($vehicle->license_plate)) {
$updatePayload['license_plate'] = $plate;
}
if (!empty($owner)) {
$updatePayload['ownership'] = $owner;
}
if ($isMobile) {
$updatePayload['is_timesheet_mobile'] = true;
}
$vehicle->update($updatePayload);
$updatedCount++;
} else {
// Buat unit baru jika belum terdaftar
$vehicle = Vehicle::create([
'code' => $code1,
'category' => 'unit_support',
'operational_group' => $cat,
'unit_category' => $cat,
'unit_type' => $type,
'brand' => $cleanBrand,
'model_number' => $cleanModel,
'brand_type' => !empty($brandTypeCombined) ? $brandTypeCombined : $type,
'serial_number' => $cleanSerial,
'license_plate' => $plate ?: null,
'production_year' => $yearInt,
'location' => $finalLocation,
'site_status' => $siteStatus,
'status' => $status,
'ownership' => $owner ?: 'PT Kerinci Merangin Hidro',
'is_timesheet_mobile' => $isMobile,
'location_updated_at' => Carbon::now(),
'location_updated_by' => 'Import Berkas Excel Lokasi',
'location_note' => "Pendaftaran baru dari berkas DATA LOKASI TERBARU RKM KMH",
]);
$createdCount++;
}
// Catat riwayat lokasi unit
VehicleLocationHistory::create([
'vehicle_id' => $vehicle->id,
'site_status' => $siteStatus,
'location' => $finalLocation,
'note' => "Sinkronisasi Berkas Excel: Status {$status} di {$finalLocation}",
'source' => 'import',
'user_id' => null,
'user_name' => 'Import Berkas Excel Lokasi',
'recorded_at' => Carbon::now(),
]);
}
// Fallback untuk unit support yang belum memiliki operational_group
$typeFallback = [
'DUMP TRUCK' => 'HAULING',
'DUMP TRUCK FFT' => 'HAULING',
'MIXER TRUCK' => 'HAULING',
'CAPSULE CEMENT' => 'HAULING',
'EXCAVATOR' => 'LOADER',
'WHEEL LOADER' => 'LOADER',
'MUCKING LOADER' => 'LOADER',
'CRAWLER ROCK DRILL' => 'DRILLING',
'BORE PILE' => 'DRILLING',
'JUMBO DRILL' => 'DRILLING',
'WHEEL RIG DRILL' => 'DRILLING',
'BULLDOZER' => 'PIT SERVICE',
'MOTOR GRADER' => 'PIT SERVICE',
'VIBRO' => 'PIT SERVICE',
'WATER TRUCK' => 'PIT SERVICE',
'BOOMLIFT' => 'HANDLING',
'CARRYDECK CRANE' => 'HANDLING',
'CRAWLER CRANE' => 'HANDLING',
'CRANE TRUCK' => 'HANDLING',
'FLAT BED' => 'HANDLING',
'FORKLIFT' => 'HANDLING',
'LOW BED' => 'HANDLING',
'MOBILE CRANE' => 'HANDLING',
'ROUGHTER CRANE' => 'HANDLING',
'SCISSOR LIFT' => 'HANDLING',
'TOWER CRANE' => 'HANDLING',
'TRAILER' => 'HANDLING',
'ASPHALT PATCH MIXER' => 'SUPPORT',
'COMPRESSOR' => 'SUPPORT',
'CONCRETE PUMP' => 'SUPPORT',
'CONCRETE PUMP TRUCK' => 'SUPPORT',
'ENGINE GENSET' => 'SUPPORT',
'FUEL TRUCK' => 'SUPPORT',
'SILENT SHEET PILE' => 'SUPPORT',
'LIGHT TRUCK' => 'SUPPORT',
'SHOTCRETE' => 'SUPPORT',
'SKYLIFT TRUCK' => 'SUPPORT',
'WET SHOTCRETE TRUCK' => 'SUPPORT',
];
foreach ($typeFallback as $fbType => $fbGroup) {
Vehicle::where('category', 'unit_support')
->where(function ($q) {
$q->whereNull('operational_group')->orWhere('operational_group', '');
})
->where(function ($q) use ($fbType) {
$q->where('unit_type', $fbType)
->orWhere('unit_category', $fbType);
})
->update(['operational_group' => $fbGroup]);
}
// Default terakhir jika masih kosong
Vehicle::where('category', 'unit_support')
->where(function ($q) {
$q->whereNull('operational_group')->orWhere('operational_group', '');
})
->update(['operational_group' => 'SUPPORT']);
DB::commit();
} catch (\Throwable $e) {
DB::rollBack();
$this->error("Gagal melakukan sinkronisasi: " . $e->getMessage());
return self::FAILURE;
}
$this->info("Sinkronisasi Selesai!");
$this->info("- Unit diperbarui: {$updatedCount}");
$this->info("- Unit baru dibuat: {$createdCount}");
return self::SUCCESS;
}
}
+126 -70
View File
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog; use App\Models\AdminActivityLog;
use App\Models\BackupLog; use App\Models\BackupLog;
use App\Services\DatabaseBackupService; use App\Services\DatabaseBackupService;
use App\Services\KmhConverterService;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -19,7 +20,8 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
class BackupController extends Controller class BackupController extends Controller
{ {
public function __construct( public function __construct(
protected DatabaseBackupService $backupService protected DatabaseBackupService $backupService,
protected KmhConverterService $converterService
) {} ) {}
/** /**
@@ -377,78 +379,23 @@ class BackupController extends Controller
targetName: $originalName targetName: $originalName
); );
if ($request->ajax() || $request->wantsJson()) {
return response()->json([
'success' => true,
'message' => "Sistem berhasil dipulihkan secara langsung dari file '{$originalName}'. Seluruh data tabel dan media telah disinkronkan kembali.",
]);
}
return back()->with('success', "Sistem berhasil dipulihkan secara langsung dari file '{$originalName}'. Seluruh data tabel dan media telah disinkronkan kembali."); return back()->with('success', "Sistem berhasil dipulihkan secara langsung dari file '{$originalName}'. Seluruh data tabel dan media telah disinkronkan kembali.");
} catch (\Throwable $e) { } catch (\Throwable $e) {
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage()); if ($request->ajax() || $request->wantsJson()) {
} return response()->json([
} 'success' => false,
'message' => 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage(),
/** ], 422);
* Inspeksi dan baca metadata isi file .kmh yang sudah ada di penyimpanan server.
*/
public function inspect(string $filename): JsonResponse
{
$filename = basename($filename);
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
if (!File::exists($fullPath)) {
return response()->json([
'success' => false,
'message' => "Berkas backup '{$filename}' tidak ditemukan di penyimpanan server VPS.",
], 404);
}
try {
$data = $this->backupService->inspectKmhFile($fullPath);
return response()->json([
'success' => true,
'data' => $data,
]);
} catch (\Throwable $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 422);
}
}
/**
* Inspeksi dan baca metadata isi file .kmh yang diunggah dari komputer lokal.
* File sementara langsung dihapus otomatis setelah dibaca (Zero Storage Retention).
*/
public function inspectUpload(Request $request): JsonResponse
{
$request->validate([
'backup_file' => ['required', 'file', 'max:512000'],
], [
'backup_file.required' => 'Pilih atau letakkan berkas file .kmh yang ingin dibaca.',
'backup_file.file' => 'Berkas yang diunggah tidak valid.',
'backup_file.max' => 'Ukuran file melebihi batas maksimal upload 500 MB.',
]);
$uploaded = $request->file('backup_file');
$tempPath = tempnam(sys_get_temp_dir(), 'kmh_upload_inspect_');
try {
$uploaded->move(dirname($tempPath), basename($tempPath));
$data = $this->backupService->inspectKmhFile($tempPath);
// Ganti nama file dengan nama asli dari komputer pengguna
$data['filename'] = $uploaded->getClientOriginalName();
return response()->json([
'success' => true,
'data' => $data,
]);
} catch (\Throwable $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 422);
} finally {
if (is_file($tempPath)) {
@unlink($tempPath);
} }
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage());
} }
} }
@@ -479,4 +426,113 @@ class BackupController extends Controller
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server atau sudah pernah dihapus."); return back()->with('error', "File backup '{$filename}' tidak ditemukan di server atau sudah pernah dihapus.");
} }
/**
* Periksa metadata & daftar tabel dari berkas .kmh yang diunggah dari komputer.
* Mengembalikan informasi file dan tabel dalam format JSON tanpa menyimpan data di server (0 Byte retained).
*/
public function converterInspect(Request $request): JsonResponse
{
$request->validate([
'backup_file' => 'required|file',
]);
$file = $request->file('backup_file');
$originalName = $file->getClientOriginalName();
if (!str_ends_with(strtolower($originalName), '.kmh')) {
return response()->json([
'success' => false,
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
], 422);
}
try {
$metadata = $this->converterService->inspectUploadedFile($file);
return response()->json([
'success' => true,
'data' => $metadata,
]);
} catch (\Throwable $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage(),
], 422);
}
}
/**
* Konversi berkas .kmh yang diunggah ke format pilihan (xlsx, csv, sql, media).
* Mendukung eksekusi via token sesi (tanpa perlu upload ulang 2x) atau direct upload.
* Mengalirkan file hasil langsung ke browser dan segera menghapus semua file sementara (Zero Disk Retention).
*/
public function converterExecute(Request $request): BinaryFileResponse|JsonResponse
{
$request->validate([
'backup_file' => 'nullable|file',
'token' => 'nullable|string',
'tables' => 'nullable|array',
'tables.*' => 'string',
'format' => 'required|in:xlsx,csv,sql,media',
]);
$selectedTables = $request->input('tables', []);
$format = $request->input('format');
$token = $request->input('token');
if ($format !== 'media' && empty($selectedTables)) {
return response()->json([
'success' => false,
'message' => 'Silakan pilih minimal 1 tabel untuk dikonversi.',
], 422);
}
try {
if ($token) {
$result = $this->converterService->convertByToken($token, $selectedTables, $format);
$originalName = 'arsip_kmh';
} elseif ($request->hasFile('backup_file')) {
$file = $request->file('backup_file');
$originalName = $file->getClientOriginalName();
if (!str_ends_with(strtolower($originalName), '.kmh')) {
return response()->json([
'success' => false,
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
], 422);
}
$result = $this->converterService->convertUploadedFile($file, $selectedTables, $format);
} else {
return response()->json([
'success' => false,
'message' => 'Berkas atau sesi konversi tidak ditemukan. Silakan pilih kembali berkas .kmh.',
], 422);
}
AdminActivityLog::record(
actionType: 'export',
module: 'Backup & Restore',
description: "Mengonversi arsip .kmh '{$originalName}' ke format " . strtoupper($format) . ($format === 'media' ? ' (Media Foto)' : ' untuk ' . count($selectedTables) . ' tabel.'),
targetType: 'BackupFile',
targetName: $originalName
);
$workDir = $result['work_dir'];
register_shutdown_function(function () use ($workDir) {
if (is_dir($workDir)) {
File::deleteDirectory($workDir);
}
});
return response()->download($result['path'], $result['filename'], [
'Content-Type' => $result['mime'],
'Access-Control-Expose-Headers' => 'Content-Disposition',
])->deleteFileAfterSend(true);
} catch (\Throwable $e) {
return response()->json([
'success' => false,
'message' => 'Gagal melakukan konversi arsip: ' . $e->getMessage(),
], 422);
}
}
} }
+38 -12
View File
@@ -74,8 +74,8 @@ class UserController extends Controller
{ {
$validated = $request->validate([ $validated = $request->validate([
'name' => ['required', 'string', 'max:255'], 'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:50', 'unique:users,username'], 'username' => ['required', 'string', 'max:50', Rule::unique('users', 'username')->whereNull('deleted_at')],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'], 'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->whereNull('deleted_at')],
'password' => ['required', 'string', 'min:6'], 'password' => ['required', 'string', 'min:6'],
'role' => ['required', 'string', 'exists:roles,name'], 'role' => ['required', 'string', 'exists:roles,name'],
'gate_id' => ['nullable', 'exists:gates,id'], 'gate_id' => ['nullable', 'exists:gates,id'],
@@ -102,15 +102,38 @@ class UserController extends Controller
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80); $photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
} }
$user = User::create([ $user = User::withTrashed()
'name' => $validated['name'], ->where('username', $validated['username'])
'username' => $validated['username'], ->orWhere('email', $validated['email'])
'email' => $validated['email'], ->first();
'password' => Hash::make($validated['password']),
'role' => $validated['role'], // Simpan ke kolom legacy untuk backwards-compat if ($user) {
'gate_id' => $validated['gate_id'] ?? null, if ($user->trashed()) {
'photo_path' => $photoPath, $user->restore();
]); }
$userData = [
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
'role' => $validated['role'],
'gate_id' => $validated['gate_id'] ?? null,
];
if ($photoPath) {
$userData['photo_path'] = $photoPath;
}
$user->update($userData);
} else {
$user = User::create([
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
'role' => $validated['role'], // Simpan ke kolom legacy untuk backwards-compat
'gate_id' => $validated['gate_id'] ?? null,
'photo_path' => $photoPath,
]);
}
// Assign Spatie Role // Assign Spatie Role
$user->assignRole($validated['role']); $user->assignRole($validated['role']);
@@ -141,7 +164,7 @@ class UserController extends Controller
$defaultDivision = ($isGateOfficer || $isPgAdmin) ? 'Private Guard' : '-'; $defaultDivision = ($isGateOfficer || $isPgAdmin) ? 'Private Guard' : '-';
$defaultPosition = $isGateOfficer ? 'Anggota' : ($isPgAdmin ? 'Admin PG' : ($isEmployeeRole ? 'Driver Operasional' : '-')); $defaultPosition = $isGateOfficer ? 'Anggota' : ($isPgAdmin ? 'Admin PG' : ($isEmployeeRole ? 'Driver Operasional' : '-'));
$emp = Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first(); $emp = Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
$empData = [ $empData = [
'user_id' => $user->id, 'user_id' => $user->id,
'nik' => $user->username, 'nik' => $user->username,
@@ -154,6 +177,9 @@ class UserController extends Controller
'photo_path' => $photoPath ?: $emp?->photo_path, 'photo_path' => $photoPath ?: $emp?->photo_path,
]; ];
if ($emp) { if ($emp) {
if ($emp->trashed()) {
$emp->restore();
}
$emp->update($empData); $emp->update($empData);
} else { } else {
Employee::create($empData); Employee::create($empData);
+145 -29
View File
@@ -17,6 +17,7 @@ use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View; use Illuminate\View\View;
class EmployeeController extends Controller class EmployeeController extends Controller
@@ -42,9 +43,10 @@ class EmployeeController extends Controller
->take(5) ->take(5)
->get(); ->get();
// 2. Monitoring Status & Masa Berlaku SIMPER (Prioritas Kedaluwarsa & Segera Habis) // 2. Monitoring Status & Masa Berlaku SIMPER (Prioritas Kedaluwarsa & Segera Habis dengan Dukungan Multi-SIMPER)
$today = now()->toDateString(); $today = now()->toDateString();
$simperLogs = Employee::where('is_operator', true) $simperLogs = Employee::where('is_operator', true)
->with(['simpers.simperType'])
->orderByRaw("CASE ->orderByRaw("CASE
WHEN simper_expired_at IS NULL THEN 1 WHEN simper_expired_at IS NULL THEN 1
WHEN simper_expired_at < ? THEN 0 WHEN simper_expired_at < ? THEN 0
@@ -209,6 +211,7 @@ class EmployeeController extends Controller
'Unit Kerja' => 20, 'Unit Kerja' => 20,
'Divisi' => 20, 'Divisi' => 20,
'Status Driver' => 16, 'Status Driver' => 16,
'Jenis Izin SIMPER' => 24,
'Masa Berlaku SIMPER' => 22, 'Masa Berlaku SIMPER' => 22,
'Status SIMPER' => 24, 'Status SIMPER' => 24,
]; ];
@@ -221,6 +224,13 @@ class EmployeeController extends Controller
$isDriver = $emp->is_operator; $isDriver = $emp->is_operator;
$expDate = $emp->simper_expired_at ? $emp->simper_expired_at->format('d/m/Y') : '-'; $expDate = $emp->simper_expired_at ? $emp->simper_expired_at->format('d/m/Y') : '-';
// Ambil rincian seluruh kode SIMPER yang dipegang
$simperList = $emp->simpers->map(function ($s) {
$code = $s->simperType?->code ?: 'SIMPER';
return str_replace('SIMPER-', '', $code);
})->filter()->unique()->values();
$simperTypesText = $simperList->isNotEmpty() ? $simperList->join(', ') : ($isDriver ? 'LV (Default)' : '-');
if (! $isDriver) { if (! $isDriver) {
$statusText = 'Bukan Driver'; $statusText = 'Bukan Driver';
} elseif (! $emp->simper_expired_at) { } elseif (! $emp->simper_expired_at) {
@@ -242,6 +252,7 @@ class EmployeeController extends Controller
$emp->unit_kerja ?: '-', $emp->unit_kerja ?: '-',
$emp->division ?: '-', $emp->division ?: '-',
$isDriver ? 'Driver' : 'Bukan Driver', $isDriver ? 'Driver' : 'Bukan Driver',
$simperTypesText,
$expDate, $expDate,
$statusText, $statusText,
]; ];
@@ -256,6 +267,7 @@ class EmployeeController extends Controller
'left', // Unit Kerja 'left', // Unit Kerja
'left', // Divisi 'left', // Divisi
'center', // Status Driver 'center', // Status Driver
'center', // Jenis Izin SIMPER
'center', // Masa Berlaku 'center', // Masa Berlaku
'center', // Status SIMPER 'center', // Status SIMPER
]; ];
@@ -580,7 +592,7 @@ class EmployeeController extends Controller
public function store(Request $request): RedirectResponse public function store(Request $request): RedirectResponse
{ {
$validated = $request->validate([ $validated = $request->validate([
'nik' => ['required', 'string', 'max:50', 'unique:employees,nik'], 'nik' => ['required', 'string', 'max:50', Rule::unique('employees', 'nik')->whereNull('deleted_at')],
'name' => ['required', 'string', 'max:100'], 'name' => ['required', 'string', 'max:100'],
'unit_kerja' => ['required', 'string'], 'unit_kerja' => ['required', 'string'],
'division' => ['required', 'string'], 'division' => ['required', 'string'],
@@ -588,6 +600,10 @@ class EmployeeController extends Controller
'is_operator' => ['required', 'in:1,0'], 'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'], 'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'], 'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
'simper_assignments' => ['nullable', 'array'],
'simper_assignments.*.expired_at' => ['nullable', 'date'],
'simper_assignments.*.simper_number' => ['nullable', 'string', 'max:100'],
'renew_simper_type_id' => ['nullable', 'string'],
], [ ], [
'nik.required' => 'NIK wajib diisi.', 'nik.required' => 'NIK wajib diisi.',
'nik.unique' => 'NIK sudah terdaftar dalam sistem.', 'nik.unique' => 'NIK sudah terdaftar dalam sistem.',
@@ -609,15 +625,24 @@ class EmployeeController extends Controller
$employeeType = 'Karyawan'; $employeeType = 'Karyawan';
} }
$user = User::firstOrCreate( $user = User::withTrashed()->where('username', $validated['nik'])->first();
['username' => $validated['nik']], if ($user) {
[ if ($user->trashed()) {
$user->restore();
}
$user->update([
'name' => $validated['name'],
'role' => $user->role ?: 'employee',
]);
} else {
$user = User::create([
'username' => $validated['nik'],
'name' => $validated['name'], 'name' => $validated['name'],
'email' => strtolower(str_replace(['-', ' '], '', $validated['nik'])) . '@kmh.co.id', 'email' => strtolower(str_replace(['-', ' '], '', $validated['nik'])) . '@kmh.co.id',
'password' => Hash::make(config('auth.default_employee_password', '123456')), 'password' => Hash::make(config('auth.default_employee_password', '123456')),
'role' => 'employee', 'role' => 'employee',
] ]);
); }
if (!$user->hasRole('employee')) { if (!$user->hasRole('employee')) {
$user->assignRole('employee'); $user->assignRole('employee');
@@ -629,18 +654,36 @@ class EmployeeController extends Controller
$user->update(['photo_path' => $photoPath]); $user->update(['photo_path' => $photoPath]);
} }
$employee = Employee::create([ $employee = Employee::withTrashed()->where('nik', $validated['nik'])->first();
'nik' => $validated['nik'], if ($employee) {
'name' => $validated['name'], if ($employee->trashed()) {
'employee_type' => $employeeType, $employee->restore();
'unit_kerja' => $validated['unit_kerja'], }
'division' => $validated['division'], $employee->update([
'position' => $validated['position'], 'name' => $validated['name'],
'is_operator' => $isOperator, 'employee_type' => $employeeType,
'simper_expired_at' => $simperExpiredAt, 'unit_kerja' => $validated['unit_kerja'],
'photo_path' => $photoPath, 'division' => $validated['division'],
'user_id' => $user->id, 'position' => $validated['position'],
]); 'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath ?? $employee->photo_path,
'user_id' => $user->id,
]);
} else {
$employee = Employee::create([
'nik' => $validated['nik'],
'name' => $validated['name'],
'employee_type' => $employeeType,
'unit_kerja' => $validated['unit_kerja'],
'division' => $validated['division'],
'position' => $validated['position'],
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath,
'user_id' => $user->id,
]);
}
// Sinkronisasi Multi-SIMPER Personil // Sinkronisasi Multi-SIMPER Personil
$this->syncEmployeeSimpers($employee, $request, $isOperator, $simperExpiredAt); $this->syncEmployeeSimpers($employee, $request, $isOperator, $simperExpiredAt);
@@ -696,6 +739,10 @@ class EmployeeController extends Controller
'is_operator' => ['required', 'in:1,0'], 'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'], 'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'], 'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
'simper_assignments' => ['nullable', 'array'],
'simper_assignments.*.expired_at' => ['nullable', 'date'],
'simper_assignments.*.simper_number' => ['nullable', 'string', 'max:100'],
'renew_simper_type_id' => ['nullable', 'string'],
], [ ], [
'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.', 'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.',
'name.required' => 'Nama lengkap wajib diisi.', 'name.required' => 'Nama lengkap wajib diisi.',
@@ -810,7 +857,8 @@ class EmployeeController extends Controller
private function syncEmployeeSimpers(Employee $employee, Request $request, bool $isOperator, ?string $fallbackDate): void private function syncEmployeeSimpers(Employee $employee, Request $request, bool $isOperator, ?string $fallbackDate): void
{ {
if (! $isOperator) { if (! $isOperator) {
$employee->simpers()->delete(); $employee->simpers()->forceDelete();
$employee->update(['simper_expired_at' => null]);
return; return;
} }
@@ -821,20 +869,30 @@ class EmployeeController extends Controller
$maxExpiredAt = null; $maxExpiredAt = null;
foreach ($simperAssignments as $typeId => $data) { foreach ($simperAssignments as $typeId => $data) {
$isEnabled = ! empty($data['enabled']) || (! isset($data['enabled']) && ! empty($data['expired_at'])); // Hanya aktif jika dicentang eksplisit, ATAU fallback jika form tidak menyertakan checkbox enabled namun memiliki tanggal
$isEnabled = ! empty($data['enabled']);
if (! $isEnabled && ! isset($data['enabled']) && ! empty($data['expired_at'])) {
$isEnabled = true;
}
if ($isEnabled && ! empty($data['expired_at'])) { if ($isEnabled && ! empty($data['expired_at'])) {
$expDate = $data['expired_at']; $expDate = $data['expired_at'];
$simperNum = ! empty($data['simper_number']) ? trim($data['simper_number']) : ('SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT)); $simperNum = ! empty($data['simper_number']) ? trim($data['simper_number']) : ('SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT));
EmployeeSimper::updateOrCreate( $simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $typeId], ['employee_id' => $employee->id, 'simper_type_id' => (int) $typeId],
[ [
'simper_number' => $simperNum, 'simper_number' => $simperNum,
'expired_at' => $expDate, 'expired_at' => $expDate,
'status' => 'active', 'status' => 'active',
'deleted_at' => null,
] ]
); );
if ($simper->trashed()) {
$simper->restore();
}
$activeTypeIds[] = (int) $typeId; $activeTypeIds[] = (int) $typeId;
if (! $maxExpiredAt || $expDate > $maxExpiredAt) { if (! $maxExpiredAt || $expDate > $maxExpiredAt) {
@@ -843,26 +901,84 @@ class EmployeeController extends Controller
} }
} }
// Hapus jenis SIMPER yang sudah tidak dicentang // Hapus jenis SIMPER yang sudah tidak dicentang (Gunakan forceDelete agar tidak memicu benturan Unique Index)
EmployeeSimper::where('employee_id', $employee->id) EmployeeSimper::where('employee_id', $employee->id)
->whereNotIn('simper_type_id', $activeTypeIds) ->whereNotIn('simper_type_id', $activeTypeIds)
->delete(); ->forceDelete();
if ($maxExpiredAt && $employee->simper_expired_at != $maxExpiredAt) { $employee->update(['simper_expired_at' => $maxExpiredAt]);
$employee->update(['simper_expired_at' => $maxExpiredAt]); } elseif ($request->filled('renew_simper_type_id')) {
// Khusus alur Perpanjang SIMPER via Modal (#renewModal)
$renewTypeId = $request->input('renew_simper_type_id');
$newExpiry = $request->input('simper_expired_at');
if ($newExpiry) {
if ($renewTypeId === 'all') {
// Perpanjang semua SIMPER yang aktif dimiliki oleh karyawan
$existingSimpers = $employee->simpers;
if ($existingSimpers->isNotEmpty()) {
foreach ($existingSimpers as $s) {
$s->update([
'expired_at' => $newExpiry,
'status' => 'active',
]);
}
} else {
// Jika belum ada SIMPER sama sekali, buatkan SIMPER-LV default
$lvTypeId = SimperType::where('code', 'SIMPER-LV')->value('id');
if ($lvTypeId) {
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $lvTypeId],
[
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $newExpiry,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
}
}
} else {
// Perpanjang jenis SIMPER spesifik yang dipilih pada dropdown
$targetTypeId = (int) $renewTypeId;
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $targetTypeId],
[
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $newExpiry,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
}
// Sinkronkan simper_expired_at master karyawan dengan tanggal terlama di antara simper aktif
$latestMax = $employee->simpers()->max('expired_at');
$employee->update(['simper_expired_at' => $latestMax]);
} }
} elseif ($fallbackDate) { } elseif ($fallbackDate) {
// Fallback untuk form sederhana / pengujian yang mengirimkan 1 tanggal simper_expired_at // Fallback untuk pengujian sederhana yang mengirimkan 1 tanggal simper_expired_at
$lvTypeId = SimperType::where('code', 'SIMPER-LV')->value('id'); $lvTypeId = SimperType::where('code', 'SIMPER-LV')->value('id');
if ($lvTypeId) { if ($lvTypeId) {
EmployeeSimper::updateOrCreate( $simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $lvTypeId], ['employee_id' => $employee->id, 'simper_type_id' => $lvTypeId],
[ [
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT), 'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $fallbackDate, 'expired_at' => $fallbackDate,
'status' => 'active', 'status' => 'active',
'deleted_at' => null,
] ]
); );
if ($simper->trashed()) {
$simper->restore();
}
$employee->update(['simper_expired_at' => $fallbackDate]);
} }
} }
} }
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Pg; namespace App\Http\Controllers\Pg;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Models\Gate; use App\Models\Gate;
use App\Models\SecurityGuard; use App\Models\SecurityGuard;
use App\Models\VehicleActivity; use App\Models\VehicleActivity;
@@ -268,6 +269,15 @@ class GateInspectionController extends Controller
'validated_at' => Carbon::now(), 'validated_at' => Carbon::now(),
]); ]);
return back()->with('success', "Aktivitas kendaraan {$activity->vehicle->code} telah ditolak."); AdminActivityLog::record(
'reject',
'pos_gerbang',
"Penolakan perlintasan gerbang untuk kendaraan {$activity->vehicle?->code} (Driver: {$activity->driver?->name}). Alasan: {$activity->rejection_note}",
'vehicle_activity',
$activity->id,
$activity->transaction_no
);
return back()->with('success', "Aktivitas perlintasan kendaraan {$activity->vehicle->code} telah ditolak.");
} }
} }
@@ -735,8 +735,11 @@ class P2hInspectionController extends Controller
]); ]);
// Jika unit dinyatakan aman dan sebelumnya breakdown karena review, status unit disetujui operasi // Jika unit dinyatakan aman dan sebelumnya breakdown karena review, status unit disetujui operasi
if (!$record->hasDefects() && $record->vehicle->status === 'Breakdown') { if (!$record->hasDefects() && $record->vehicle && $record->vehicle->status === 'Breakdown') {
$record->vehicle->update(['status' => 'Operation']); $record->vehicle->update([
'status' => 'Operation',
'location_note' => "Status dipulihkan ke Operation pasca persetujuan P2H {$record->transaction_no}",
]);
} }
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} berhasil DISETUJUI."); return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} berhasil DISETUJUI.");
@@ -134,15 +134,24 @@ class SupportTimesheetController extends Controller
$timesheets = $query->paginate($perPage)->withQueryString(); $timesheets = $query->paginate($perPage)->withQueryString();
// KPI Ringkasan Data Terfilter // KPI Ringkasan Data Terfilter
$statsQuery = clone $this->getFilteredQuery($request); $statsItems = (clone $this->getFilteredQuery($request))->get();
$totalEntries = (clone $statsQuery)->count(); $totalEntries = $statsItems->count();
$totalOperatingHours = (clone $statsQuery)->sum('operating_hours'); $totalOperatingHours = 0.0;
$totalFuelLiters = (clone $statsQuery)->sum('fuel_liters'); foreach ($statsItems as $item) {
$activeUnitsCount = (clone $statsQuery)->distinct('vehicle_id')->count('vehicle_id'); $totalOperatingHours += (float) ($item->effective_operating_hours ?? 0);
$breakdownCount = (clone $statsQuery)->where('status', 'Breakdown')->count(); }
$totalFuelLiters = $statsItems->sum('fuel_liters');
$activeUnitsCount = $statsItems->pluck('vehicle_id')->unique()->count();
$breakdownCount = $statsItems->where('status', 'Breakdown')->count();
// Data Master untuk Form & Filter // Data Master untuk Form & Filter (Alat Berat / Heavy Equipment - Bebas dari Unit LV)
$unitSupports = Vehicle::unitSupports() $unitSupports = Vehicle::unitSupports()
->where('category', '!=', 'light_vehicle')
->where(function (Builder $q) {
$q->where('code', 'not like', 'LV %')
->where('code', 'not like', 'LV-%')
->where('code', 'not like', 'LV_%');
})
->where(function (Builder $q) { ->where(function (Builder $q) {
$q->whereNotNull('parent_id') $q->whereNotNull('parent_id')
->orWhereDoesntHave('units'); ->orWhereDoesntHave('units');
@@ -168,8 +177,37 @@ class SupportTimesheetController extends Controller
} }
$shifts = self::SHIFTS; $shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions(); // Ambil preset + aktivitas yang pernah diisi secara dinamis di database
$dbActivities = UnitSupportTimesheet::whereNotNull('activity_type')
->where('activity_type', '!=', '')
->distinct()
->pluck('activity_type')
->all();
$activityTypes = collect(self::PRESET_ACTIVITIES)
->merge($dbActivities)
->map(fn($a) => trim($a))
->filter()
->unique()
->values()
->all();
// Ambil seluruh saran lokasi dari gerbang, kendaraan, riwayat, dan timesheet
$dbTimesheetLocs = UnitSupportTimesheet::whereNotNull('location')
->where('location', '!=', '')
->distinct()
->pluck('location')
->all();
$locationSuggestions = collect(UnitManagementController::getAllLocationSuggestions())
->merge($dbTimesheetLocs)
->map(fn($l) => trim($l))
->filter()
->unique()
->sort()
->values()
->all();
$unitLocations = $unitSupports->groupBy(function ($u) { $unitLocations = $unitSupports->groupBy(function ($u) {
return trim($u->location) ?: 'Site Kerinci'; return trim($u->location) ?: 'Site Kerinci';
@@ -282,7 +320,26 @@ class SupportTimesheetController extends Controller
$endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null $endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null
? (float) $validated['end_meter'] ? (float) $validated['end_meter']
: null; : null;
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
if ($endMeter === null) {
$nextEntry = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where(function ($q) use ($validated, $startMeter) {
$q->where('date', '>', $validated['date'])
->orWhere(function ($sq) use ($validated, $startMeter) {
$sq->where('date', $validated['date'])
->where('start_meter', '>=', $startMeter);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($nextEntry && (float) $nextEntry->start_meter >= $startMeter) {
$endMeter = (float) $nextEntry->start_meter;
}
}
$operatingHours = $endMeter !== null ? max(0.0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang'; $shift = $validated['shift'] ?: 'Shift Siang';
$updaterName = auth()->user()?->name ?? 'Admin QMA'; $updaterName = auth()->user()?->name ?? 'Admin QMA';
$timesheetNo = null; $timesheetNo = null;
@@ -325,6 +382,25 @@ class SupportTimesheetController extends Controller
'created_by_user_id' => auth()->id(), 'created_by_user_id' => auth()->id(),
]); ]);
// 1b. Perbarui entri sebelumnya yang belum memiliki end_meter untuk unit yang sama (1 HM = 1 Jam)
$prevTimesheet = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where('id', '<', $timesheet->id)
->whereDate('date', '<=', $validated['date'])
->where(function ($q) {
$q->whereNull('end_meter')
->orWhere('end_meter', '<=', 0);
})
->orderByDesc('id')
->first();
if ($prevTimesheet && (float) $startMeter >= (float) $prevTimesheet->start_meter) {
$prevDiff = (float) $startMeter - (float) $prevTimesheet->start_meter;
$prevTimesheet->update([
'end_meter' => $startMeter,
'operating_hours' => $prevDiff,
]);
}
// 2. Sinkronisasi Master Kendaraan (Odometer & Posisi di Manajemen Unit) // 2. Sinkronisasi Master Kendaraan (Odometer & Posisi di Manajemen Unit)
$updateData = [ $updateData = [
'status' => $validated['status'], 'status' => $validated['status'],
@@ -355,7 +431,12 @@ class SupportTimesheetController extends Controller
]); ]);
}); });
return back()->with('success', "Timesheet {$timesheetNo} untuk unit {$vehicle->code} berhasil disimpan."); $successMsg = "Timesheet {$timesheetNo} untuk unit {$vehicle->code} berhasil disimpan.";
if ($operatingHours !== null && $operatingHours > 24) {
$successMsg .= " (Catatan: Total waktu operasi tercatat {$operatingHours} HM/Jam [> 24 jam]. Harap periksa apakah angka Start HM atau End HM sudah sesuai).";
}
return back()->with('success', $successMsg);
} }
/** /**
@@ -457,7 +538,12 @@ class SupportTimesheetController extends Controller
'notes' => $validated['notes'] ?? null, 'notes' => $validated['notes'] ?? null,
]); ]);
return back()->with('success', "Timesheet {$timesheet->timesheet_no} berhasil diperbarui."); $successMsg = "Timesheet {$timesheet->timesheet_no} berhasil diperbarui.";
if ($operatingHours !== null && $operatingHours > 24) {
$successMsg .= " (Catatan: Total waktu operasi tercatat {$operatingHours} HM/Jam [> 24 jam]. Harap periksa apakah angka Start HM atau End HM sudah sesuai).";
}
return back()->with('success', $successMsg);
} }
/** /**
@@ -511,6 +597,9 @@ class SupportTimesheetController extends Controller
$rows = []; $rows = [];
foreach ($timesheets as $idx => $ts) { foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [ $rows[] = [
$idx + 1, $idx + 1,
$ts->timesheet_no, $ts->timesheet_no,
@@ -523,8 +612,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->nik ?: '-', $ts->operator?->nik ?: '-',
$ts->meter_type, $ts->meter_type,
number_format($ts->start_meter, 2, ',', '.'), number_format($ts->start_meter, 2, ',', '.'),
number_format($ts->end_meter, 2, ',', '.'), $endMeter !== null ? number_format($endMeter, 2, ',', '.') : '-',
number_format($ts->operating_hours, 2, ',', '.'), $opHours !== null ? number_format($opHours, 2, ',', '.') : '-',
number_format($ts->standby_hours, 2, ',', '.'), number_format($ts->standby_hours, 2, ',', '.'),
number_format($ts->breakdown_hours, 2, ',', '.'), number_format($ts->breakdown_hours, 2, ',', '.'),
$ts->location, $ts->location,
@@ -606,6 +695,9 @@ class SupportTimesheetController extends Controller
$rows = []; $rows = [];
foreach ($timesheets as $idx => $ts) { foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [ $rows[] = [
$idx + 1, $idx + 1,
$ts->date ? $ts->date->format('d/m/Y') : '-', $ts->date ? $ts->date->format('d/m/Y') : '-',
@@ -614,8 +706,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->name ? ($ts->operator->name . ' (' . ($ts->operator->employee_type ?: 'Karyawan') . ')') : '-', $ts->operator?->name ? ($ts->operator->name . ' (' . ($ts->operator->employee_type ?: 'Karyawan') . ')') : '-',
$ts->shift, $ts->shift,
number_format($ts->start_meter, 1, ',', '.'), number_format($ts->start_meter, 1, ',', '.'),
number_format($ts->end_meter, 1, ',', '.'), $endMeter !== null ? number_format($endMeter, 1, ',', '.') : '-',
number_format($ts->operating_hours, 1, ',', '.') . ' ' . $ts->meter_type, ($opHours !== null ? number_format($opHours, 1, ',', '.') : '-') . ' ' . $ts->meter_type,
$ts->location, $ts->location,
$ts->status, $ts->status,
]; ];
@@ -143,12 +143,48 @@ class UnitTransferController extends Controller
->map(fn($group) => $group->count()) ->map(fn($group) => $group->count())
->sortKeys(); ->sortKeys();
// 2. Daftar unit kendaraan kita untuk armada pengangkut (Truk, Flatbed, Lowbed, Towing, LV, dsb.) // 2. Daftar armada pengangkut khusus truk/alat angkut (Lowbed, Flatbed, Trailer, Dump Truck, Light Truck, Crane Truck)
$transporterCategories = [
'Low Bed',
'Flat Bed',
'Trailer',
'Dump Truck',
'Light Truck',
'Crane Truck',
];
$transporterUnits = Vehicle::trackableUnits() $transporterUnits = Vehicle::trackableUnits()
->orderBy('category') ->where(function (Builder $q) use ($transporterCategories) {
$q->whereIn('unit_category', $transporterCategories)
->orWhere(function (Builder $sub) {
$sub->where('code', 'like', 'LB %')
->orWhere('code', 'like', 'LB-%')
->orWhere('code', 'like', 'FB %')
->orWhere('code', 'like', 'FB-%')
->orWhere('code', 'like', 'TR %')
->orWhere('code', 'like', 'TR-%')
->orWhere('code', 'like', 'DT %')
->orWhere('code', 'like', 'DT-%')
->orWhere('code', 'like', 'LT %')
->orWhere('code', 'like', 'LT-%')
->orWhere('code', 'like', 'CT %')
->orWhere('code', 'like', 'CT-%');
});
})
->where(function (Builder $q) {
$q->where('code', 'not like', 'LV %')
->where('code', 'not like', 'LV-%')
->where('code', 'not like', 'LV/%')
->where('code', 'not like', 'LV_%');
})
->orderBy('code') ->orderBy('code')
->get(); ->get();
// Lokasi asal armada pengangkut internal yang tersedia beserta jumlah unitnya
$transporterLocations = $transporterUnits->groupBy(fn($u) => $u->location ?: 'Site Kerinci')
->map(fn($group) => $group->count())
->sortKeys();
// 3. Daftar pengemudi / operator // 3. Daftar pengemudi / operator
$drivers = Employee::where('is_operator', true) $drivers = Employee::where('is_operator', true)
->orderBy('name') ->orderBy('name')
@@ -166,6 +202,7 @@ class UnitTransferController extends Controller
'originLocations', 'originLocations',
'selectedOriginLocation', 'selectedOriginLocation',
'transporterUnits', 'transporterUnits',
'transporterLocations',
'drivers', 'drivers',
'locationSuggestions', 'locationSuggestions',
'defaultDocNumber', 'defaultDocNumber',
@@ -186,6 +223,8 @@ class UnitTransferController extends Controller
'to_site_status' => ['required', 'in:inside_site,outside_site'], 'to_site_status' => ['required', 'in:inside_site,outside_site'],
'description' => ['nullable', 'string', 'max:2000'], 'description' => ['nullable', 'string', 'max:2000'],
'reported_by' => ['required', 'string', 'max:255'], 'reported_by' => ['required', 'string', 'max:255'],
'transporter_type' => ['nullable', 'string', 'in:internal,external,none'],
'transporter_origin_location' => ['nullable', 'string', 'max:255'],
'transporter_vehicle_id' => ['nullable', 'integer', 'exists:vehicles,id'], 'transporter_vehicle_id' => ['nullable', 'integer', 'exists:vehicles,id'],
'transporter_unit_name' => ['nullable', 'string', 'max:255'], 'transporter_unit_name' => ['nullable', 'string', 'max:255'],
'transporter_driver_id' => ['nullable', 'integer', 'exists:employees,id'], 'transporter_driver_id' => ['nullable', 'integer', 'exists:employees,id'],
@@ -221,14 +260,25 @@ class UnitTransferController extends Controller
$fromLocation = $vehicle->location ?: ($validated['from_location'] ?? 'Site Kerinci'); $fromLocation = $vehicle->location ?: ($validated['from_location'] ?? 'Site Kerinci');
$fromSiteStatus = $vehicle->site_status ?: 'inside_site'; $fromSiteStatus = $vehicle->site_status ?: 'inside_site';
// Sumber Armada Pengangkut (Internal / External / None)
$transporterType = $validated['transporter_type'] ?? (!empty($validated['transporter_vehicle_id']) ? 'internal' : (!empty($validated['transporter_unit_name']) ? 'external' : 'none'));
$transporterVehicleId = ($transporterType === 'internal') ? ($validated['transporter_vehicle_id'] ?? null) : null;
$transporterOriginLocation = !empty($validated['transporter_origin_location']) ? trim($validated['transporter_origin_location']) : null;
// Nama armada pengangkut // Nama armada pengangkut
$transporterUnitName = !empty($validated['transporter_unit_name']) ? trim($validated['transporter_unit_name']) : null; $transporterUnitName = !empty($validated['transporter_unit_name']) ? trim($validated['transporter_unit_name']) : null;
if (empty($transporterUnitName) && !empty($validated['transporter_vehicle_id'])) { if ($transporterType === 'internal' && !empty($transporterVehicleId)) {
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']); $transporterVeh = Vehicle::find($transporterVehicleId);
if ($transporterVeh) { if ($transporterVeh) {
$plate = $transporterVeh->license_plate ? " ({$transporterVeh->license_plate})" : ''; $plate = $transporterVeh->license_plate ? " ({$transporterVeh->license_plate})" : '';
$transporterUnitName = "{$transporterVeh->code} - {$transporterVeh->brand_type}{$plate}"; $transporterUnitName = "{$transporterVeh->code} - {$transporterVeh->brand_type}{$plate}";
if (empty($transporterOriginLocation)) {
$transporterOriginLocation = $transporterVeh->location ?: 'Site Kerinci';
}
} }
} elseif ($transporterType === 'none') {
$transporterUnitName = 'Mobilisasi Mandiri (Tanpa Pengangkut)';
$transporterOriginLocation = null;
} }
// Nama driver pengangkut // Nama driver pengangkut
@@ -262,7 +312,9 @@ class UnitTransferController extends Controller
'description' => !empty($validated['description']) ? trim($validated['description']) : null, 'description' => !empty($validated['description']) ? trim($validated['description']) : null,
'reported_by' => $reportedBy, 'reported_by' => $reportedBy,
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'transporter_vehicle_id' => $validated['transporter_vehicle_id'] ?? null, 'transporter_type' => $transporterType,
'transporter_vehicle_id' => $transporterVehicleId,
'transporter_origin_location' => $transporterOriginLocation,
'transporter_unit_name' => $transporterUnitName, 'transporter_unit_name' => $transporterUnitName,
'transporter_driver_id' => $validated['transporter_driver_id'] ?? null, 'transporter_driver_id' => $validated['transporter_driver_id'] ?? null,
'transporter_driver_name' => $transporterDriverName, 'transporter_driver_name' => $transporterDriverName,
@@ -285,6 +337,9 @@ class UnitTransferController extends Controller
// 3. Catat di audit log riwayat pergerakan unit (VehicleLocationHistory) // 3. Catat di audit log riwayat pergerakan unit (VehicleLocationHistory)
$transporterSummary = $transporterUnitName ? " Pengangkut: {$transporterUnitName}" : ""; $transporterSummary = $transporterUnitName ? " Pengangkut: {$transporterUnitName}" : "";
if ($transporterOriginLocation) {
$transporterSummary .= " [Asal: {$transporterOriginLocation}]";
}
if ($transporterDriverName) { if ($transporterDriverName) {
$transporterSummary .= " (Driver: {$transporterDriverName})"; $transporterSummary .= " (Driver: {$transporterDriverName})";
} }
@@ -305,9 +360,9 @@ class UnitTransferController extends Controller
'recorded_at' => Carbon::now(), 'recorded_at' => Carbon::now(),
]); ]);
// 4. Jika opsi perbarui posisi truk pengangkut aktif // 4. Jika opsi perbarui posisi truk pengangkut aktif (Hanya armada internal)
if ($updateTransporter && !empty($validated['transporter_vehicle_id'])) { if ($transporterType === 'internal' && $updateTransporter && !empty($transporterVehicleId)) {
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']); $transporterVeh = Vehicle::find($transporterVehicleId);
if ($transporterVeh && $transporterVeh->id !== $vehicle->id) { if ($transporterVeh && $transporterVeh->id !== $vehicle->id) {
$transporterNote = $docNumber $transporterNote = $docNumber
? "Armada Pengangkut BAST {$docNumber} untuk {$vehicle->code} ke {$toLocation}" ? "Armada Pengangkut BAST {$docNumber} untuk {$vehicle->code} ke {$toLocation}"
@@ -320,9 +375,10 @@ class UnitTransferController extends Controller
'location_note' => $transporterNote, 'location_note' => $transporterNote,
]); ]);
$transporterHistNote = $docNumber $transporterHistNote = $docNumber
? "Armada Pengangkut: Mengantar {$vehicle->code} ({$vehicle->brand_type}) via BAST {$docNumber} ke {$toLocation}" ? "Armada Pengangkut: Mengantar {$vehicle->code} ({$vehicle->brand_type}) via BAST {$docNumber} ke {$toLocation}"
: "Armada Pengangkut: Mengantar {$vehicle->code} ({$vehicle->brand_type}) transfer internal ke {$toLocation}"; : "Armada Pengangkut: Mengantar {$vehicle->code} ({$vehicle->brand_type}) transfer internal ke {$toLocation}";
VehicleLocationHistory::create([ VehicleLocationHistory::create([
'vehicle_id' => $transporterVeh->id, 'vehicle_id' => $transporterVeh->id,
'site_status' => $validated['to_site_status'], 'site_status' => $validated['to_site_status'],
+500 -58
View File
@@ -277,56 +277,15 @@ class VehicleController extends Controller
/** /**
* Halaman khusus pengelolaan Kategori Kendaraan Berat (Heavy Equipment / Alat Berat). * Halaman khusus pengelolaan Kategori Kendaraan Berat (Heavy Equipment / Alat Berat).
* Mendukung navigasi hirarki 3 level:
* - Level 1: Kelompok Operasional (HAULING, LOADER, SUPPORT, HANDLING, DRILLING, PIT SERVICE)
* - Level 2: Tipe Alat Berat di dalam Kelompok (Dump Truck, Mixer Truck, Excavator, dll.)
* - Level 3: Daftar Unit Fisik individual (DT 01, EX 01, dll.)
*/ */
public function indexSupport(Request $request): View public function indexSupport(Request $request): View
{ {
$query = Vehicle::unitSupportCategories()->withCount('units'); $selectedGroup = $request->input('group');
$selectedType = $request->input('type');
// Filter Status Operasional
if ($request->filled('status')) {
$query->where('status', $request->input('status'));
}
// Filter Kategori Heavy Equipment (Excavator, Crane, Bulldozer, dll)
if ($request->filled('unit_category')) {
$query->where('unit_category', $request->input('unit_category'));
}
// Filter Pencarian Keyword Heavy Equipment
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('unit_type', 'like', "%{$search}%")
->orWhere('brand', 'like', "%{$search}%")
->orWhere('model_number', 'like', "%{$search}%")
->orWhere('location', 'like', "%{$search}%")
->orWhere('ownership', 'like', "%{$search}%")
->orWhere('division', 'like', "%{$search}%");
});
}
$perPage = (int) $request->input('per_page', 15);
if (!in_array($perPage, [15, 50, 100])) {
$perPage = 15;
}
$vehicles = $query->orderBy('code')->paginate($perPage)->withQueryString();
// Statistik Ringkasan Khusus Heavy Equipment
$totalSupport = Vehicle::unitSupportCategories()->count();
$totalUnits = Vehicle::unitSupportPhysical()->count();
$totalOperation = Vehicle::unitSupportCategories()->where('status', 'Operation')->count();
$totalStandby = Vehicle::unitSupportCategories()->where('status', 'Standby')->count();
$totalBreakdown = Vehicle::unitSupportCategories()->where('status', 'Breakdown')->count();
// Daftar kategori alat berat yang terdaftar untuk opsi filter
$availableCategories = Vehicle::unitSupportCategories()
->whereNotNull('unit_category')
->distinct()
->pluck('unit_category');
// Master data daftar divisi perusahaan (gabungan standar + data existing di Employee & Vehicle) // Master data daftar divisi perusahaan (gabungan standar + data existing di Employee & Vehicle)
$standardDivisions = collect([ $standardDivisions = collect([
@@ -353,17 +312,364 @@ class VehicleController extends Controller
->values() ->values()
->all(); ->all();
// Daftar semua kode Heavy Equipment untuk validasi unik langsung di form // Master data daftar kelompok operasional, kategori & tipe alat berat
$existingCodes = Vehicle::unitSupports()->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all(); $availableGroups = ['HAULING', 'LOADER', 'SUPPORT', 'HANDLING', 'DRILLING', 'PIT SERVICE'];
$groupTypesMap = [
'HAULING' => ['DUMP TRUCK', 'MIXER TRUCK', 'CAPSULE CEMENT', 'LOW BED', 'DUMP TRUCK FFT'],
'LOADER' => ['EXCAVATOR', 'WHEEL LOADER', 'MUCKING LOADER'],
'SUPPORT' => ['COMPRESSOR', 'CONCRETE PUMP', 'ENGINE GENSET', 'CONCRETE PUMP TRUCK', 'LIGHT TRUCK', 'SHOTCRETE', 'WET SHOTCRETE TRUCK', 'FUEL TRUCK', 'WATER TRUCK', 'SILENT SHEET PILE', 'SKYLIFT TRUCK', 'ASPHALT PATCH MIXER'],
'HANDLING' => ['FORKLIFT', 'CRANE TRUCK', 'ROUGHTER CRANE', 'BOOMLIFT', 'CRAWLER CRANE', 'SCISSOR LIFT', 'TRAILER', 'TOWER CRANE', 'FLAT BED', 'CARRYDECK CRANE', 'LOW BED', 'MOBILE CRANE'],
'DRILLING' => ['CRAWLER ROCK DRILL', 'BORE PILE', 'JUMBO DRILL', 'WHEEL RIG DRILL'],
'PIT SERVICE' => ['BULLDOZER', 'VIBRO', 'WATER TRUCK', 'MOTOR GRADER'],
];
// Gabungkan tipe dari database agar dinamis jika ada custom type baru
$dbGroupTypes = Vehicle::where('category', 'unit_support')
->whereNotNull('operational_group')
->whereNotNull('unit_type')
->where('unit_type', '!=', '')
->select('operational_group', 'unit_type')
->distinct()
->get();
foreach ($dbGroupTypes as $gt) {
$grpKey = strtoupper(trim($gt->operational_group));
$tVal = strtoupper(trim($gt->unit_type));
if (!isset($groupTypesMap[$grpKey])) {
$groupTypesMap[$grpKey] = [];
}
if (!in_array($tVal, $groupTypesMap[$grpKey])) {
$groupTypesMap[$grpKey][] = $tVal;
}
}
foreach ($groupTypesMap as $grpKey => &$tList) {
sort($tList);
}
unset($tList);
$availableLocations = Vehicle::whereNotNull('location')
->where('location', '!=', '')
->distinct()
->pluck('location')
->sort()
->values()
->all();
$availableBrands = Vehicle::where('category', 'unit_support')
->whereNotNull('brand')
->where('brand', '!=', '')
->distinct()
->pluck('brand')
->sort()
->values()
->all();
$availableCategories = Vehicle::where('category', 'unit_support')
->whereNotNull('unit_category')
->where('unit_category', '!=', '')
->distinct()
->pluck('unit_category');
$availableTypes = Vehicle::where('category', 'unit_support')
->whereNotNull('unit_type')
->where('unit_type', '!=', '')
->distinct()
->orderBy('unit_type')
->pluck('unit_type');
$existingCodes = Vehicle::where('category', 'unit_support')->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
// Metadata kelompok operasional (icon, badge style, keterangan)
$groupMetadata = [
'HAULING' => [
'icon' => 'fa-truck-moving',
'color' => 'indigo',
'badge' => 'bg-indigo-50 text-indigo-700 border-indigo-200',
'icon_bg' => 'bg-indigo-100 text-indigo-800 border-indigo-300',
'desc' => 'Armada pengangkutan material tanah, batuan, semen, beton curah, dan mobilisasi berat (Dump Truck, Truk Mixer, Capsule Cement, Low Bed).',
],
'LOADER' => [
'icon' => 'fa-truck-monster',
'color' => 'amber',
'badge' => 'bg-amber-50 text-amber-800 border-amber-200',
'icon_bg' => 'bg-amber-100 text-amber-800 border-amber-300',
'desc' => 'Alat pemuatan material, penggalian tanah dan batuan terowongan proyek (Excavator, Wheel Loader, Mucking Loader).',
],
'SUPPORT' => [
'icon' => 'fa-gears',
'color' => 'emerald',
'badge' => 'bg-emerald-50 text-emerald-800 border-emerald-200',
'icon_bg' => 'bg-emerald-100 text-emerald-800 border-emerald-300',
'desc' => 'Unit penunjang operasional, kelistrikan, suplai angin kompresi, dan pengecoran (Compressor, Genset, Concrete Pump, Fuel Truck, Light Truck).',
],
'HANDLING' => [
'icon' => 'fa-boxes-stacked',
'color' => 'purple',
'badge' => 'bg-purple-50 text-purple-700 border-purple-200',
'icon_bg' => 'bg-purple-100 text-purple-800 border-purple-300',
'desc' => 'Alat pengangkatan dan penanganan material konstruksi serta akses ketinggian (Mobile Crane, Crane Truck, Crawler Crane, Forklift, Boomlift, Scissorlift).',
],
'DRILLING' => [
'icon' => 'fa-arrows-down-to-line',
'color' => 'rose',
'badge' => 'bg-rose-50 text-rose-700 border-rose-200',
'icon_bg' => 'bg-rose-100 text-rose-800 border-rose-300',
'desc' => 'Alat pengeboran batuan keras, tiang pancang, dan pekerjaan bawah tanah (Crawler Rock Drill, Bore Pile, Jumbo Drill, Wheel Rig Drill).',
],
'PIT SERVICE' => [
'icon' => 'fa-mountain',
'color' => 'cyan',
'badge' => 'bg-cyan-50 text-cyan-800 border-cyan-200',
'icon_bg' => 'bg-cyan-100 text-cyan-800 border-cyan-300',
'desc' => 'Alat pemeliharaan jalan tambang, perataan tanah, dan penyiraman debu lintasan proyek (Bulldozer, Motor Grader, Vibro Roller, Water Truck).',
],
];
// Global statistik untuk header
$allSupportQuery = Vehicle::where('category', 'unit_support');
$totalUnits = (clone $allSupportQuery)->count();
$totalOperation = (clone $allSupportQuery)->where('status', 'Operation')->count();
$totalStandby = (clone $allSupportQuery)->where('status', 'Standby')->count();
$totalBreakdown = (clone $allSupportQuery)->where('status', 'Breakdown')->count();
$totalSupport = (clone $allSupportQuery)->whereNotNull('unit_type')->where('unit_type', '!=', '')->distinct('unit_type')->count('unit_type');
$totalGroups = count($availableGroups);
$perPage = (int) $request->input('per_page', 15);
if (!in_array($perPage, [15, 50, 100])) {
$perPage = 15;
}
// =========================================================================
// LEVEL 3: JIKA USER MEMILIH TIPE TERTENTU (Daftar Unit Fisik)
// =========================================================================
if ($selectedType) {
$level = 'units';
// Auto-detect group jika tidak disuplai
if (!$selectedGroup) {
$sampleUnit = Vehicle::where('category', 'unit_support')
->where(function ($q) use ($selectedType) {
$q->where('unit_type', $selectedType)->orWhere('unit_category', $selectedType);
})->first();
$selectedGroup = $sampleUnit?->operational_group ?: 'SUPPORT';
}
$unitsQuery = Vehicle::where('category', 'unit_support')
->where(function ($q) use ($selectedType) {
$q->where('unit_type', $selectedType)
->orWhere('unit_category', $selectedType);
});
if ($request->filled('status')) {
$unitsQuery->where('status', $request->input('status'));
}
if ($request->filled('site_status')) {
$unitsQuery->where('site_status', $request->input('site_status'));
}
if ($request->filled('location')) {
$unitsQuery->where('location', $request->input('location'));
}
if ($request->filled('search')) {
$search = trim($request->input('search'));
$unitsQuery->where(function ($q) use ($search) {
$q->where('code', 'like', "%{$search}%")
->orWhere('brand', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('model_number', 'like', "%{$search}%")
->orWhere('serial_number', 'like', "%{$search}%")
->orWhere('license_plate', 'like', "%{$search}%")
->orWhere('location', 'like', "%{$search}%");
});
}
$typeUnits = $unitsQuery->orderBy('code')->paginate($perPage)->withQueryString();
$vehicles = $typeUnits;
// Statistik Khusus Tipe Terpilih
$allOfType = Vehicle::where('category', 'unit_support')
->where(function ($q) use ($selectedType) {
$q->where('unit_type', $selectedType)
->orWhere('unit_category', $selectedType);
})
->get();
$totalUnitsOfType = $allOfType->count();
$opCount = $allOfType->where('status', 'Operation')->count();
$stCount = $allOfType->where('status', 'Standby')->count();
$bdCount = $allOfType->where('status', 'Breakdown')->count();
$insideCount = $allOfType->where('site_status', 'inside_site')->count();
$outsideCount = $allOfType->where('site_status', 'outside_site')->count();
return view('qma.vehicles_support', compact(
'level',
'selectedGroup',
'selectedType',
'typeUnits',
'vehicles',
'totalUnitsOfType',
'opCount',
'stCount',
'bdCount',
'insideCount',
'outsideCount',
'totalSupport',
'totalGroups',
'totalUnits',
'totalOperation',
'totalStandby',
'totalBreakdown',
'groupMetadata',
'groupTypesMap',
'availableLocations',
'availableBrands',
'availableGroups',
'availableCategories',
'availableTypes',
'availableDivisions',
'existingCodes'
));
}
// =========================================================================
// LEVEL 2: JIKA USER MEMILIH KELOMPOK OPERASIONAL (Daftar Tipe Alat di Kelompok Tersebut)
// =========================================================================
if ($selectedGroup) {
$level = 'types';
$groupUnitsQuery = Vehicle::where('category', 'unit_support')->where('operational_group', $selectedGroup);
$groupTotalUnits = (clone $groupUnitsQuery)->count();
$groupOpCount = (clone $groupUnitsQuery)->where('status', 'Operation')->count();
$groupStCount = (clone $groupUnitsQuery)->where('status', 'Standby')->count();
$groupBdCount = (clone $groupUnitsQuery)->where('status', 'Breakdown')->count();
$groupInsideCount = (clone $groupUnitsQuery)->where('site_status', 'inside_site')->count();
$groupOutsideCount = (clone $groupUnitsQuery)->where('site_status', 'outside_site')->count();
$groupTypesCount = (clone $groupUnitsQuery)->whereNotNull('unit_type')->where('unit_type', '!=', '')->distinct('unit_type')->count('unit_type');
$typesQuery = Vehicle::where('category', 'unit_support')
->where('operational_group', $selectedGroup)
->select(
'unit_type',
DB::raw('MAX(unit_category) as unit_category'),
DB::raw('COUNT(*) as units_count'),
DB::raw("SUM(CASE WHEN status = 'Operation' THEN 1 ELSE 0 END) as total_operation"),
DB::raw("SUM(CASE WHEN status = 'Standby' THEN 1 ELSE 0 END) as total_standby"),
DB::raw("SUM(CASE WHEN status = 'Breakdown' THEN 1 ELSE 0 END) as total_breakdown"),
DB::raw("SUM(CASE WHEN site_status = 'inside_site' THEN 1 ELSE 0 END) as inside_site_count"),
DB::raw("SUM(CASE WHEN site_status = 'outside_site' THEN 1 ELSE 0 END) as outside_site_count"),
DB::raw('MAX(brand_type) as sample_brand_type'),
DB::raw('MAX(photo_path) as sample_photo'),
DB::raw('MIN(id) as sample_id'),
DB::raw('MIN(code) as code')
)
->groupBy('unit_type');
if ($request->filled('unit_category')) {
$typesQuery->where('unit_category', $request->input('unit_category'));
}
if ($request->filled('search')) {
$search = trim($request->input('search'));
$typesQuery->where(function ($q) use ($search) {
$q->where('unit_type', 'like', "%{$search}%")
->orWhere('unit_category', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('code', 'like', "%{$search}%");
});
}
$types = $typesQuery->orderByDesc(DB::raw('COUNT(*)'))->paginate($perPage)->withQueryString();
$vehicles = $types;
return view('qma.vehicles_support', compact(
'level',
'selectedGroup',
'types',
'vehicles',
'groupTotalUnits',
'groupOpCount',
'groupStCount',
'groupBdCount',
'groupInsideCount',
'groupOutsideCount',
'groupTypesCount',
'totalSupport',
'totalGroups',
'totalUnits',
'totalOperation',
'totalStandby',
'totalBreakdown',
'groupMetadata',
'groupTypesMap',
'availableLocations',
'availableBrands',
'availableGroups',
'availableCategories',
'availableTypes',
'availableDivisions',
'existingCodes'
));
}
// =========================================================================
// LEVEL 1: TAMPILAN UTAMA (6 KELOMPOK OPERASIONAL BESAR)
// =========================================================================
$level = 'groups';
$groupsQuery = Vehicle::where('category', 'unit_support')
->select(
'operational_group',
DB::raw('COUNT(DISTINCT unit_type) as types_count'),
DB::raw('COUNT(*) as units_count'),
DB::raw("SUM(CASE WHEN status = 'Operation' THEN 1 ELSE 0 END) as total_operation"),
DB::raw("SUM(CASE WHEN status = 'Standby' THEN 1 ELSE 0 END) as total_standby"),
DB::raw("SUM(CASE WHEN status = 'Breakdown' THEN 1 ELSE 0 END) as total_breakdown"),
DB::raw("SUM(CASE WHEN site_status = 'inside_site' THEN 1 ELSE 0 END) as inside_site_count"),
DB::raw("SUM(CASE WHEN site_status = 'outside_site' THEN 1 ELSE 0 END) as outside_site_count"),
DB::raw('MIN(code) as sample_code')
)
->groupBy('operational_group');
if ($request->filled('search')) {
$search = trim($request->input('search'));
$groupsQuery->where(function ($q) use ($search) {
$q->where('operational_group', 'like', "%{$search}%")
->orWhere('unit_type', 'like', "%{$search}%")
->orWhere('unit_category', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('code', 'like', "%{$search}%");
});
}
$groups = $groupsQuery
->orderByRaw("CASE operational_group
WHEN 'HAULING' THEN 1
WHEN 'LOADER' THEN 2
WHEN 'SUPPORT' THEN 3
WHEN 'HANDLING' THEN 4
WHEN 'DRILLING' THEN 5
WHEN 'PIT SERVICE' THEN 6
ELSE 7 END")
->paginate($perPage)
->withQueryString();
$vehicles = $groups;
return view('qma.vehicles_support', compact( return view('qma.vehicles_support', compact(
'level',
'groups',
'vehicles', 'vehicles',
'totalSupport', 'totalSupport',
'totalGroups',
'totalUnits', 'totalUnits',
'totalOperation', 'totalOperation',
'totalStandby', 'totalStandby',
'totalBreakdown', 'totalBreakdown',
'groupMetadata',
'groupTypesMap',
'availableLocations',
'availableBrands',
'availableGroups',
'availableCategories', 'availableCategories',
'availableTypes',
'availableDivisions', 'availableDivisions',
'existingCodes' 'existingCodes'
)); ));
@@ -378,6 +684,19 @@ class VehicleController extends Controller
$query = $category->units(); $query = $category->units();
if ($request->filled('group') || $request->filled('operational_group')) {
$grp = $request->input('group') ?: $request->input('operational_group');
$query->where('operational_group', $grp);
}
if ($request->filled('type') || $request->filled('unit_type')) {
$t = $request->input('type') ?: $request->input('unit_type');
$query->where(function ($q) use ($t) {
$q->where('unit_type', $t)
->orWhere('unit_category', $t);
});
}
if ($request->filled('status')) { if ($request->filled('status')) {
$query->where('status', $request->input('status')); $query->where('status', $request->input('status'));
} }
@@ -455,6 +774,19 @@ class VehicleController extends Controller
{ {
$query = Vehicle::unitSupportPhysical()->with('parent'); $query = Vehicle::unitSupportPhysical()->with('parent');
if ($request->filled('group') || $request->filled('operational_group')) {
$grp = $request->input('group') ?: $request->input('operational_group');
$query->where('operational_group', $grp);
}
if ($request->filled('type') || $request->filled('unit_type')) {
$t = $request->input('type') ?: $request->input('unit_type');
$query->where(function ($q) use ($t) {
$q->where('unit_type', $t)
->orWhere('unit_category', $t);
});
}
if ($request->filled('status')) { if ($request->filled('status')) {
$query->where('status', $request->input('status')); $query->where('status', $request->input('status'));
} }
@@ -494,6 +826,19 @@ class VehicleController extends Controller
{ {
$query = Vehicle::unitSupportCategories()->withCount('units'); $query = Vehicle::unitSupportCategories()->withCount('units');
if ($request->filled('group') || $request->filled('operational_group')) {
$grp = $request->input('group') ?: $request->input('operational_group');
$query->where('operational_group', $grp);
}
if ($request->filled('type') || $request->filled('unit_type')) {
$t = $request->input('type') ?: $request->input('unit_type');
$query->where(function ($q) use ($t) {
$q->where('unit_type', $t)
->orWhere('unit_category', $t);
});
}
if ($request->filled('status')) { if ($request->filled('status')) {
$query->where('status', $request->input('status')); $query->where('status', $request->input('status'));
} }
@@ -744,6 +1089,19 @@ class VehicleController extends Controller
$category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id); $category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id);
$query = $category->units(); $query = $category->units();
if ($request->filled('group') || $request->filled('operational_group')) {
$grp = $request->input('group') ?: $request->input('operational_group');
$query->where('operational_group', $grp);
}
if ($request->filled('type') || $request->filled('unit_type')) {
$t = $request->input('type') ?: $request->input('unit_type');
$query->where(function ($q) use ($t) {
$q->where('unit_type', $t)
->orWhere('unit_category', $t);
});
}
if ($request->filled('status')) { if ($request->filled('status')) {
$query->where('status', $request->input('status')); $query->where('status', $request->input('status'));
} }
@@ -821,6 +1179,19 @@ class VehicleController extends Controller
$category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id); $category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id);
$query = $category->units(); $query = $category->units();
if ($request->filled('group') || $request->filled('operational_group')) {
$grp = $request->input('group') ?: $request->input('operational_group');
$query->where('operational_group', $grp);
}
if ($request->filled('type') || $request->filled('unit_type')) {
$t = $request->input('type') ?: $request->input('unit_type');
$query->where(function ($q) use ($t) {
$q->where('unit_type', $t)
->orWhere('unit_category', $t);
});
}
if ($request->filled('status')) { if ($request->filled('status')) {
$query->where('status', $request->input('status')); $query->where('status', $request->input('status'));
} }
@@ -986,7 +1357,7 @@ class VehicleController extends Controller
$rules = [ $rules = [
'code' => ['required', 'string', 'max:50', 'unique:vehicles,code'], 'code' => ['required', 'string', 'max:50', 'unique:vehicles,code'],
'category' => ['required', 'in:light_vehicle,unit_support'], 'category' => ['required', 'in:light_vehicle,unit_support'],
'brand_type' => ['required', 'string', 'max:150'], 'brand_type' => [$category === 'unit_support' ? 'nullable' : 'required', 'string', 'max:150'],
'license_plate' => ['nullable', 'string', 'max:30'], 'license_plate' => ['nullable', 'string', 'max:30'],
'serial_number' => ['nullable', 'string', 'max:100'], 'serial_number' => ['nullable', 'string', 'max:100'],
'ownership' => ['nullable', 'string', 'max:150'], 'ownership' => ['nullable', 'string', 'max:150'],
@@ -1001,12 +1372,14 @@ class VehicleController extends Controller
// Atribut opsional spesifik Heavy Equipment (Kendaraan Berat) // Atribut opsional spesifik Heavy Equipment (Kendaraan Berat)
if ($category === 'unit_support') { if ($category === 'unit_support') {
$rules = array_merge($rules, [ $rules = array_merge($rules, [
'operational_group' => ['required', 'string', 'max:50'],
'unit_type' => ['required', 'string', 'max:100'],
'unit_category' => ['nullable', 'string', 'max:100'], 'unit_category' => ['nullable', 'string', 'max:100'],
'unit_type' => ['nullable', 'string', 'max:100'],
'brand' => ['nullable', 'string', 'max:100'], 'brand' => ['nullable', 'string', 'max:100'],
'model_number' => ['nullable', 'string', 'max:100'], 'model_number' => ['nullable', 'string', 'max:100'],
'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)], 'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)],
'location' => ['nullable', 'string', 'max:150'], 'location' => ['nullable', 'string', 'max:150'],
'site_status' => ['nullable', 'in:inside_site,outside_site'],
'fuel_consumption' => ['nullable', 'numeric', 'min:0'], 'fuel_consumption' => ['nullable', 'numeric', 'min:0'],
'silo_document' => ['nullable', 'string', 'max:150'], 'silo_document' => ['nullable', 'string', 'max:150'],
'stnk_document' => ['nullable', 'string', 'max:150'], 'stnk_document' => ['nullable', 'string', 'max:150'],
@@ -1018,6 +1391,8 @@ class VehicleController extends Controller
$validated = $request->validate($rules, [ $validated = $request->validate($rules, [
'code.required' => 'Kode kendaraan wajib diisi.', 'code.required' => 'Kode kendaraan wajib diisi.',
'code.unique' => 'Kode sudah ada, silakan gunakan kode lain.', 'code.unique' => 'Kode sudah ada, silakan gunakan kode lain.',
'operational_group.required' => 'Kelompok operasional wajib dipilih.',
'unit_type.required' => 'Tipe alat berat wajib dipilih/diisi.',
'brand_type.required' => 'Merek dan spesifikasi/tipe wajib diisi.', 'brand_type.required' => 'Merek dan spesifikasi/tipe wajib diisi.',
'current_km.required' => 'Nilai KM / HM awal wajib diisi.', 'current_km.required' => 'Nilai KM / HM awal wajib diisi.',
'status.required' => 'Status operasional wajib dipilih.', 'status.required' => 'Status operasional wajib dipilih.',
@@ -1026,6 +1401,37 @@ class VehicleController extends Controller
if ($category === 'unit_support') { if ($category === 'unit_support') {
$validated['status'] = $validated['status'] ?? 'Operation'; $validated['status'] = $validated['status'] ?? 'Operation';
$validated['current_km'] = $validated['current_km'] ?? 0; $validated['current_km'] = $validated['current_km'] ?? 0;
$validated['code'] = strtoupper(trim($validated['code']));
$validated['operational_group'] = strtoupper(trim($validated['operational_group']));
$validated['unit_type'] = strtoupper(trim($validated['unit_type']));
$validated['unit_category'] = !empty($validated['unit_category']) ? $validated['unit_category'] : $validated['unit_type'];
// Jika brand_type kosong, susun otomatis dari brand dan model_number
if (empty($validated['brand_type'])) {
$brandPart = trim(($validated['brand'] ?? '') . ' ' . ($validated['model_number'] ?? ''));
$validated['brand_type'] = $brandPart ?: $validated['unit_type'];
}
// Site status auto-detection jika kosong
if (empty($validated['site_status']) && !empty($validated['location'])) {
$upperLoc = strtoupper($validated['location']);
$outsideKeywords = ['PT.', 'HO', 'LAMPUNG', 'JAKARTA', 'CIDAS', 'POSO', 'MEDCO', 'SULINDO', 'BMS', 'BHARA', 'BUKAKA', 'ACEH'];
$isOutside = false;
foreach ($outsideKeywords as $kw) {
if (str_contains($upperLoc, $kw)) {
$isOutside = true;
break;
}
}
$validated['site_status'] = $isOutside ? 'outside_site' : 'inside_site';
} elseif (empty($validated['site_status'])) {
$validated['site_status'] = 'inside_site';
}
if (!empty($validated['location'])) {
$validated['location_updated_at'] = now();
$validated['location_updated_by'] = auth()->user()?->name ?? 'Admin QMA';
}
} }
$validated['is_timesheet_mobile'] = $request->boolean('is_timesheet_mobile'); $validated['is_timesheet_mobile'] = $request->boolean('is_timesheet_mobile');
@@ -1039,19 +1445,20 @@ class VehicleController extends Controller
$vehicle = Vehicle::create($validated); $vehicle = Vehicle::create($validated);
if ($vehicle->isSupportCategory()) { if ($vehicle->isSupportCategory()) {
// Otomatis buatkan Master Template P2H baru (default kosong tanpa butir pertanyaan) // Otomatis buatkan Master Template P2H baru jika belum ada
$templateCode = $vehicle->unit_type ?: $vehicle->code;
$template = P2hTemplate::firstOrCreate( $template = P2hTemplate::firstOrCreate(
['code' => $vehicle->code], ['code' => $templateCode],
[ [
'name' => $vehicle->unit_category ?: $vehicle->brand_type, 'name' => $vehicle->unit_type ?: $vehicle->brand_type,
'description' => "Template form inspeksi P2H resmi untuk kategori {$vehicle->brand_type} (Kode: {$vehicle->code}).", 'description' => "Template form inspeksi P2H resmi untuk {$vehicle->unit_type} (Kode: {$templateCode}).",
'is_active' => true, 'is_active' => true,
] ]
); );
$vehicle->update(['p2h_template_id' => $template->id]); $vehicle->update(['p2h_template_id' => $template->id]);
} }
$categoryLabel = $vehicle->isLightVehicle() ? 'Light Vehicle (LV)' : 'Kategori Heavy Equipment'; $categoryLabel = $vehicle->isLightVehicle() ? 'Light Vehicle (LV)' : 'Unit Heavy Equipment';
return back()->with('success', "Data {$categoryLabel} [{$vehicle->code}] berhasil ditambahkan ke sistem."); return back()->with('success', "Data {$categoryLabel} [{$vehicle->code}] berhasil ditambahkan ke sistem.");
} }
@@ -1069,19 +1476,21 @@ class VehicleController extends Controller
$rules = [ $rules = [
'code' => ['required', 'string', 'max:50', Rule::unique('vehicles', 'code')->ignore($vehicle->id)], 'code' => ['required', 'string', 'max:50', Rule::unique('vehicles', 'code')->ignore($vehicle->id)],
'category' => ['required', 'in:light_vehicle,unit_support'], 'category' => ['required', 'in:light_vehicle,unit_support'],
'brand_type' => ['required', 'string', 'max:150'], 'brand_type' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'string', 'max:150'],
'license_plate' => ['nullable', 'string', 'max:30'], 'license_plate' => ['nullable', 'string', 'max:30'],
'serial_number' => ['nullable', 'string', 'max:100'], 'serial_number' => ['nullable', 'string', 'max:100'],
'ownership' => ['nullable', 'string', 'max:150'], 'ownership' => ['nullable', 'string', 'max:150'],
'division' => ['nullable', 'string', 'max:100'], 'division' => ['nullable', 'string', 'max:100'],
'status' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'], 'status' => ['required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
'current_km' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'numeric', 'min:0'], 'current_km' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'numeric', 'min:0'],
'operational_group' => ['nullable', 'string', 'max:50'],
'unit_category' => ['nullable', 'string', 'max:100'], 'unit_category' => ['nullable', 'string', 'max:100'],
'unit_type' => ['nullable', 'string', 'max:100'], 'unit_type' => ['nullable', 'string', 'max:100'],
'brand' => ['nullable', 'string', 'max:100'], 'brand' => ['nullable', 'string', 'max:100'],
'model_number' => ['nullable', 'string', 'max:100'], 'model_number' => ['nullable', 'string', 'max:100'],
'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)], 'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)],
'location' => ['nullable', 'string', 'max:150'], 'location' => ['nullable', 'string', 'max:150'],
'site_status' => ['nullable', 'in:inside_site,outside_site'],
'fuel_consumption' => ['nullable', 'numeric', 'min:0'], 'fuel_consumption' => ['nullable', 'numeric', 'min:0'],
'silo_document' => ['nullable', 'string', 'max:150'], 'silo_document' => ['nullable', 'string', 'max:150'],
'stnk_document' => ['nullable', 'string', 'max:150'], 'stnk_document' => ['nullable', 'string', 'max:150'],
@@ -1099,6 +1508,39 @@ class VehicleController extends Controller
'current_km.required' => 'Nilai KM / HM wajib diisi.', 'current_km.required' => 'Nilai KM / HM wajib diisi.',
]); ]);
if ($vehicle->isSupportCategory()) {
$validated['code'] = strtoupper(trim($validated['code']));
if (!empty($validated['operational_group'])) {
$validated['operational_group'] = strtoupper(trim($validated['operational_group']));
}
if (!empty($validated['unit_type'])) {
$validated['unit_type'] = strtoupper(trim($validated['unit_type']));
$validated['unit_category'] = !empty($validated['unit_category']) ? $validated['unit_category'] : $validated['unit_type'];
}
if (empty($validated['brand_type'])) {
$brandPart = trim(($validated['brand'] ?? '') . ' ' . ($validated['model_number'] ?? ''));
$validated['brand_type'] = $brandPart ?: ($vehicle->brand_type ?: $validated['code']);
}
if ($request->filled('site_status')) {
$validated['site_status'] = $request->input('site_status');
} elseif (!empty($validated['location']) && $validated['location'] !== $vehicle->location) {
$upperLoc = strtoupper($validated['location']);
$outsideKeywords = ['PT.', 'HO', 'LAMPUNG', 'JAKARTA', 'CIDAS', 'POSO', 'MEDCO', 'SULINDO', 'BMS', 'BHARA', 'BUKAKA', 'ACEH'];
$isOutside = false;
foreach ($outsideKeywords as $kw) {
if (str_contains($upperLoc, $kw)) {
$isOutside = true;
break;
}
}
$validated['site_status'] = $isOutside ? 'outside_site' : 'inside_site';
}
if (!empty($validated['location']) && $validated['location'] !== $vehicle->location) {
$validated['location_updated_at'] = now();
$validated['location_updated_by'] = auth()->user()?->name ?? 'Admin QMA';
}
}
if ($request->hasFile('photo')) { if ($request->hasFile('photo')) {
ImageCompressionService::deleteIfExists($vehicle->photo_path); ImageCompressionService::deleteIfExists($vehicle->photo_path);
$validated['photo_path'] = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75); $validated['photo_path'] = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75);
+52
View File
@@ -45,6 +45,11 @@ class UnitSupportTimesheet extends Model
'fuel_liters' => 'decimal:2', 'fuel_liters' => 'decimal:2',
]; ];
protected $appends = [
'effective_end_meter',
'effective_operating_hours',
];
public function vehicle(): BelongsTo public function vehicle(): BelongsTo
{ {
return $this->belongsTo(Vehicle::class); return $this->belongsTo(Vehicle::class);
@@ -60,6 +65,53 @@ class UnitSupportTimesheet extends Model
return $this->belongsTo(User::class, 'created_by_user_id'); return $this->belongsTo(User::class, 'created_by_user_id');
} }
/**
* Dapatkan meter akhir efektif.
* Jika end_meter sudah diisi, gunakan nilainya.
* Jika belum, cari dari start_meter entri berikutnya untuk unit yang sama.
*/
public function getEffectiveEndMeterAttribute(): ?float
{
if ($this->end_meter !== null && (float) $this->end_meter > 0) {
return (float) $this->end_meter;
}
$next = static::where('vehicle_id', $this->vehicle_id)
->where(function ($q) {
$q->where('date', '>', $this->date)
->orWhere(function ($sq) {
$sq->where('date', $this->date)
->where('id', '>', $this->id);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($next && $next->start_meter !== null && (float) $next->start_meter >= (float) $this->start_meter) {
return (float) $next->start_meter;
}
return null;
}
/**
* Dapatkan jam kerja operasional efektif (1 HM = 1 Jam).
*/
public function getEffectiveOperatingHoursAttribute(): ?float
{
if ($this->operating_hours !== null && (float) $this->operating_hours > 0) {
return (float) $this->operating_hours;
}
$end = $this->effective_end_meter;
if ($end !== null && $this->start_meter !== null) {
return max(0.0, (float) $end - (float) $this->start_meter);
}
return null;
}
/** /**
* Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001). * Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001).
* Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records. * Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records.
+2
View File
@@ -24,7 +24,9 @@ class UnitTransfer extends Model
'description', 'description',
'reported_by', 'reported_by',
'user_id', 'user_id',
'transporter_type',
'transporter_vehicle_id', 'transporter_vehicle_id',
'transporter_origin_location',
'transporter_unit_name', 'transporter_unit_name',
'transporter_driver_id', 'transporter_driver_id',
'transporter_driver_name', 'transporter_driver_name',
+1
View File
@@ -29,6 +29,7 @@ class Vehicle extends Model
'photo_path', 'photo_path',
'unit_category', 'unit_category',
'unit_type', 'unit_type',
'operational_group',
'brand', 'brand',
'model_number', 'model_number',
'production_year', 'production_year',
-240
View File
@@ -203,43 +203,6 @@ class DatabaseBackupService
} }
} }
// Kumpulkan statistik tabel dan sampel data untuk pratinjau instan di manifest
$tableDetails = [];
foreach ($targetTables as $tableName) {
try {
$q = DB::table($tableName);
if (Schema::hasColumn($tableName, 'deleted_at')) {
$q->whereNull('deleted_at');
}
$totalRows = $q->count();
$samples = $q->limit(5)->get()->map(function ($row) {
$arr = (array) $row;
foreach (['password', 'remember_token', 'two_factor_secret'] as $secret) {
if (isset($arr[$secret])) {
$arr[$secret] = '••••••••';
}
}
return $arr;
})->all();
$cols = !empty($samples) ? array_keys($samples[0]) : (Schema::hasTable($tableName) ? Schema::getColumnListing($tableName) : []);
$tableDetails[$tableName] = [
'name' => $tableName,
'rows_count' => $totalRows,
'columns' => $cols,
'samples' => $samples,
];
} catch (\Throwable $e) {
$tableDetails[$tableName] = [
'name' => $tableName,
'rows_count' => 0,
'columns' => [],
'samples' => [],
];
}
}
// Manifest informasi arsip .kmh // Manifest informasi arsip .kmh
$manifest = [ $manifest = [
'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)', 'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)',
@@ -249,7 +212,6 @@ class DatabaseBackupService
'database' => $database, 'database' => $database,
'table_count' => count($targetTables), 'table_count' => count($targetTables),
'tables' => $targetTables, 'tables' => $targetTables,
'table_details' => $tableDetails,
'has_media' => $includeMedia, 'has_media' => $includeMedia,
'laravel_version' => app()->version(), 'laravel_version' => app()->version(),
'php_version' => PHP_VERSION, 'php_version' => PHP_VERSION,
@@ -275,208 +237,6 @@ class DatabaseBackupService
} }
} }
/**
* Inspeksi dan baca metadata isi file arsip .kmh tanpa melakukan restore atau manipulasi database.
* Mengembalikan manifest, daftar tabel terarsip, metrik data, dan status integritas enkripsi.
*
* @return array<string, mixed>
*/
public function inspectKmhFile(string $filePath): array
{
@set_time_limit(180);
@ini_set('memory_limit', '512M');
if (!File::exists($filePath)) {
throw new RuntimeException("Berkas file backup tidak ditemukan: {$filePath}");
}
$content = file_get_contents($filePath);
$headerLen = strlen(self::KMH_MAGIC_HEADER);
if (substr($content, 0, $headerLen) !== self::KMH_MAGIC_HEADER) {
throw new RuntimeException("Berkas bukan format arsip .kmh yang sah atau file rusak (Magic Header tidak cocok).");
}
// Dekripsi payload (verifikasi HMAC & kunci enkripsi)
$decryptedZip = $this->decryptFromKmh($content);
// Buka zip sementara untuk membaca manifest dan statistik file
$tempZip = tempnam(sys_get_temp_dir(), 'kmh_inspect_');
file_put_contents($tempZip, $decryptedZip);
try {
$zip = new ZipArchive();
if ($zip->open($tempZip) !== true) {
throw new RuntimeException("Gagal membuka struktur arsip ZIP internal di dalam berkas .kmh.");
}
$manifestJson = $zip->getFromName('manifest.json');
$manifest = $manifestJson ? json_decode($manifestJson, true) : [];
$filesCount = $zip->numFiles;
$mediaCount = 0;
$sqlSize = 0;
$mediaSamples = [];
for ($i = 0; $i < $filesCount; $i++) {
$stat = $zip->statIndex($i);
$name = $stat['name'] ?? '';
$size = $stat['size'] ?? 0;
if (str_starts_with($name, 'storage/')) {
$mediaCount++;
if (count($mediaSamples) < 5) {
$mediaSamples[] = basename($name);
}
} elseif (str_ends_with($name, '.sql') || $name === 'database.sql') {
$sqlSize = $size;
}
}
$tables = $manifest['tables'] ?? [];
$tableCount = count($tables);
// Ambil rincian tabel & sampel data (dari manifest langsung atau fallback parse dari database.sql)
$tableDetails = $manifest['table_details'] ?? null;
if (empty($tableDetails)) {
$tableDetails = $this->parseTableDetailsFromSqlStream($zip, $tables);
}
$zip->close();
$hasMedia = (bool) ($manifest['has_media'] ?? ($mediaCount > 0));
$createdAt = isset($manifest['created_at']) ? Carbon::parse($manifest['created_at']) : Carbon::createFromTimestamp(filemtime($filePath));
return [
'is_valid' => true,
'filename' => basename($filePath),
'file_size' => filesize($filePath),
'file_size_human' => $this->formatBytes(filesize($filePath)),
'format' => $manifest['format'] ?? 'KMH_ENCRYPTED_V1',
'system' => $manifest['system'] ?? 'PT Kerinci Merangin Hidro (RKM)',
'created_at' => $createdAt->toIso8601String(),
'created_at_human' => $createdAt->translatedFormat('d F Y, H:i:s') . ' WIB',
'created_at_diff' => $createdAt->diffForHumans(),
'type' => $manifest['type'] ?? ($hasMedia ? 'semua' : 'pilihan'),
'type_label' => ($manifest['type'] ?? '') === 'semua' || $hasMedia
? 'Backup Semua (Database + Media Foto)'
: 'Pilih Backup (Tabel Tertentu)',
'database' => $manifest['database'] ?? config('database.connections.mysql.database', 'rkm_kmh'),
'table_count' => $tableCount,
'tables' => $tables,
'table_details' => $tableDetails,
'has_media' => $hasMedia,
'media_file_count' => $mediaCount,
'media_samples' => $mediaSamples,
'sql_size' => $sqlSize,
'sql_size_human' => $this->formatBytes($sqlSize),
'laravel_version' => $manifest['laravel_version'] ?? app()->version(),
'php_version' => $manifest['php_version'] ?? PHP_VERSION,
'encryption_cipher' => 'AES-256-CBC',
'hmac_verification' => 'SHA-256 Terverifikasi Sah',
];
} finally {
if (is_file($tempZip)) {
@unlink($tempZip);
}
}
}
/**
* Parse rincian nama kolom, total baris data, dan sampel 5 baris pertama
* langsung dari stream database.sql untuk file arsip yang belum memiliki table_details di manifest.
*
* @param ZipArchive $zip
* @param array<int, string> $tables
* @return array<string, array<string, mixed>>
*/
protected function parseTableDetailsFromSqlStream(ZipArchive $zip, array $tables): array
{
$details = [];
foreach ($tables as $t) {
$details[$t] = [
'name' => $t,
'rows_count' => 0,
'columns' => [],
'samples' => [],
];
}
$fp = $zip->getStream('database.sql');
if (!$fp) {
return $details;
}
$currentTable = null;
$currentColumns = [];
$collectingSamples = false;
while (($line = fgets($fp, 65536)) !== false) {
$trimmed = trim($line);
if (empty($trimmed)) continue;
if (preg_match('/^--\s*Struktur Tabel untuk\s*`([^`]+)`/i', $trimmed, $m)) {
$currentTable = $m[1];
if (!isset($details[$currentTable])) {
$details[$currentTable] = [
'name' => $currentTable,
'rows_count' => 0,
'columns' => [],
'samples' => [],
];
}
$currentColumns = [];
$collectingSamples = false;
continue;
}
if (preg_match('/^INSERT INTO\s*`([^`]+)`\s*\(([^)]+)\)\s*VALUES/i', $trimmed, $m)) {
$currentTable = $m[1];
if (!isset($details[$currentTable])) {
$details[$currentTable] = [
'name' => $currentTable,
'rows_count' => 0,
'columns' => [],
'samples' => [],
];
}
$rawCols = explode(',', $m[2]);
$currentColumns = array_map(fn($c) => trim($c, " \t\n\r\0\x0B`'\""), $rawCols);
$details[$currentTable]['columns'] = $currentColumns;
$collectingSamples = true;
continue;
}
if ($currentTable && $collectingSamples) {
if (str_starts_with($trimmed, '(')) {
$details[$currentTable]['rows_count']++;
if (count($details[$currentTable]['samples']) < 5) {
$endPos = strrpos($trimmed, ')');
if ($endPos !== false) {
$valuesStr = substr($trimmed, 1, $endPos - 1);
$parsedValues = str_getcsv($valuesStr, ',', "'", "\\");
$rowAssoc = [];
foreach ($currentColumns as $idx => $colName) {
$val = $parsedValues[$idx] ?? null;
if ($val === 'NULL') $val = null;
if (in_array($colName, ['password', 'remember_token', 'two_factor_secret'])) {
$val = '••••••••';
}
$rowAssoc[$colName] = $val;
}
$details[$currentTable]['samples'][] = $rowAssoc;
}
}
} elseif (str_starts_with($trimmed, '--') || str_starts_with($trimmed, 'DROP TABLE')) {
$collectingSamples = false;
}
}
}
fclose($fp);
return $details;
}
/** /**
* Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback). * Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback).
*/ */
+671
View File
@@ -0,0 +1,671 @@
<?php
namespace App\Services;
use Carbon\Carbon;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use RuntimeException;
use ZipArchive;
class KmhConverterService
{
public function __construct(
protected DatabaseBackupService $backupService
) {}
/**
* Periksa metadata dan daftar tabel dari berkas .kmh yang diunggah dari PC.
* Menyimpan berkas sementara dengan token aman agar saat klik konversi tidak perlu upload ulang 2x.
*
* @return array{
* token: string,
* filename: string,
* size_human: string,
* created_at_human: string,
* created_at_diff: string,
* table_count: int,
* tables: array<string>,
* database: string,
* has_media: bool
* }
*/
public function inspectUploadedFile(UploadedFile $file): array
{
$realPath = $file->getRealPath();
if (!$realPath || !is_file($realPath)) {
throw new RuntimeException("Berkas unggahan tidak ditemukan atau korup.");
}
$kmhContent = file_get_contents($realPath);
if ($kmhContent === false) {
throw new RuntimeException("Gagal membaca berkas .kmh yang diunggah.");
}
// Dekripsi arsip .kmh menggunakan kunci sistem untuk verifikasi & inspeksi
$decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
unset($kmhContent);
$tempZipPath = storage_path('app/temp_inspect_' . uniqid() . '.zip');
file_put_contents($tempZipPath, $decryptedZipContent);
unset($decryptedZipContent);
$zip = new ZipArchive();
if ($zip->open($tempZipPath) !== true) {
@unlink($tempZipPath);
throw new RuntimeException("Konten terdekripsi bukan merupakan arsip ZIP yang sah.");
}
try {
$manifestJson = $zip->getFromName('manifest.json');
$manifest = $manifestJson ? json_decode($manifestJson, true) : [];
$tables = $manifest['tables'] ?? [];
// Jika manifest tidak memiliki daftar tabel, baca cepat dari struktur database.sql
if (empty($tables)) {
$sqlContent = $zip->getFromName('database.sql');
if ($sqlContent) {
preg_match_all('/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?([a-zA-Z0-9_]+)`?/i', $sqlContent, $matches);
$tables = array_values(array_unique($matches[1] ?? []));
}
}
sort($tables);
$createdAt = isset($manifest['created_at'])
? Carbon::parse($manifest['created_at'])
: Carbon::createFromTimestamp($file->getMTime());
// Simpan cache berkas sementara dengan token aman untuk mencegah upload ulang ganda
$tempDir = storage_path('app/temp_converter');
File::ensureDirectoryExists($tempDir);
// Bersihkan file sementara yang lebih tua dari 30 menit
foreach (File::files($tempDir) as $f) {
if ((time() - $f->getMTime()) > 1800) {
@unlink($f->getPathname());
}
}
$token = bin2hex(random_bytes(16));
$cachedKmhPath = $tempDir . '/' . $token . '.kmh';
copy($realPath, $cachedKmhPath);
return [
'token' => $token,
'filename' => $file->getClientOriginalName(),
'size_human' => $this->backupService->formatBytes($file->getSize()),
'created_at_human' => $createdAt->translatedFormat('d F Y, H:i') . ' WIB',
'created_at_diff' => $createdAt->diffForHumans(),
'table_count' => count($tables),
'tables' => $tables,
'database' => $manifest['database'] ?? 'rkm_kmh',
'has_media' => (bool) ($manifest['has_media'] ?? false),
];
} finally {
$zip->close();
if (is_file($tempZipPath)) {
@unlink($tempZipPath);
}
}
}
/**
* Konversi berkas .kmh menggunakan token sesi yang sudah diunggah sebelumnya.
*/
public function convertByToken(string $token, array $selectedTables, string $format): array
{
$tempDir = storage_path('app/temp_converter');
$cleanToken = preg_replace('/[^a-zA-Z0-9]/', '', $token);
$cachedPath = $tempDir . '/' . $cleanToken . '.kmh';
if (!is_file($cachedPath)) {
throw new RuntimeException("Sesi berkas telah kadaluarsa atau tidak ditemukan di server. Silakan unggah kembali berkas .kmh Anda.");
}
try {
return $this->convertKmhFilePath($cachedPath, 'arsip.kmh', $selectedTables, $format);
} finally {
@unlink($cachedPath);
}
}
/**
* Konversi berkas .kmh langsung dari UploadedFile.
*/
public function convertUploadedFile(UploadedFile $file, array $selectedTables, string $format): array
{
$realPath = $file->getRealPath();
if (!$realPath || !is_file($realPath)) {
throw new RuntimeException("Berkas unggahan tidak ditemukan.");
}
return $this->convertKmhFilePath($realPath, $file->getClientOriginalName(), $selectedTables, $format);
}
/**
* Method inti konversi dari file path .kmh ke format tujuan (xlsx, csv, sql, media).
*
* @param string $kmhFilePath
* @param string $originalFilename
* @param array<string> $selectedTables
* @param string $format 'xlsx' | 'csv' | 'sql' | 'media'
* @return array{
* path: string,
* filename: string,
* mime: string,
* work_dir: string
* }
*/
public function convertKmhFilePath(string $kmhFilePath, string $originalFilename, array $selectedTables, string $format): array
{
$format = strtolower($format);
if (!in_array($format, ['xlsx', 'csv', 'sql', 'media'], true)) {
throw new RuntimeException("Format konversi tidak didukung: {$format}");
}
if ($format !== 'media' && empty($selectedTables)) {
throw new RuntimeException("Silakan pilih minimal 1 tabel untuk dikonversi.");
}
$workDir = storage_path('app/temp_kmh_conv_' . uniqid());
File::ensureDirectoryExists($workDir);
$tempZipPath = $workDir . '/package.zip';
$sqlPath = $workDir . '/database.sql';
try {
// 1. Dekripsi payload .kmh
$kmhContent = file_get_contents($kmhFilePath);
if ($kmhContent === false) {
throw new RuntimeException("Gagal membaca berkas .kmh untuk konversi.");
}
$decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
unset($kmhContent);
file_put_contents($tempZipPath, $decryptedZipContent);
unset($decryptedZipContent);
$timestamp = now()->format('Ymd_His');
// Format KHUSUS: Ekstraksi Folder Media/Foto Asli
if ($format === 'media') {
$outputFilename = 'Arsip_KMH_Media_Foto_' . $timestamp . '.zip';
$outputPath = $workDir . '/' . $outputFilename;
$zipIn = new ZipArchive();
if ($zipIn->open($tempZipPath) !== true) {
throw new RuntimeException("Gagal membuka arsip kontainer untuk ekstraksi media.");
}
$zipOut = new ZipArchive();
if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
$zipIn->close();
throw new RuntimeException("Gagal membuat arsip ZIP untuk media.");
}
$mediaCount = 0;
for ($i = 0; $i < $zipIn->numFiles; $i++) {
$stat = $zipIn->statIndex($i);
$name = $stat['name'];
if (str_starts_with($name, 'storage/') && !str_ends_with($name, '/')) {
$content = $zipIn->getFromIndex($i);
$relativeName = substr($name, 8); // buang prefix 'storage/'
$zipOut->addFromString($relativeName, $content);
$mediaCount++;
}
}
$zipIn->close();
$zipOut->close();
@unlink($tempZipPath);
if ($mediaCount === 0) {
throw new RuntimeException("Berkas arsip .kmh ini tidak memiliki lampiran media foto fisik.");
}
return [
'path' => $outputPath,
'filename' => $outputFilename,
'mime' => 'application/zip',
'work_dir' => $workDir,
];
}
// 2. Ekstrak database.sql saja
$zip = new ZipArchive();
if ($zip->open($tempZipPath) !== true) {
throw new RuntimeException("Gagal membuka arsip kontainer backup.");
}
$zip->extractTo($workDir, ['database.sql']);
$zip->close();
@unlink($tempZipPath);
if (!is_file($sqlPath)) {
throw new RuntimeException("Berkas database.sql tidak ditemukan di dalam arsip .kmh.");
}
// 3. Proses berdasarkan format SQL
if ($format === 'sql') {
$outputFilename = 'Arsip_KMH_SQL_' . $timestamp . '.sql';
$outputPath = $workDir . '/' . $outputFilename;
$this->extractFilteredSql($sqlPath, $selectedTables, $outputPath);
@unlink($sqlPath);
return [
'path' => $outputPath,
'filename' => $outputFilename,
'mime' => 'application/sql',
'work_dir' => $workDir,
];
}
// Ekstrak data tabel ke bentuk CSV sementara di disk (Memory-Safe Streaming)
$csvDir = $workDir . '/csv_tables';
File::ensureDirectoryExists($csvDir);
$extractedTables = $this->streamSqlToCsvFiles($sqlPath, $selectedTables, $csvDir);
@unlink($sqlPath);
// Format CSV
if ($format === 'csv') {
$outputFilename = 'Arsip_KMH_CSV_' . $timestamp . '.zip';
$outputPath = $workDir . '/' . $outputFilename;
$zipOut = new ZipArchive();
if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException("Gagal membuat arsip ZIP untuk file CSV.");
}
foreach ($extractedTables as $tbl => $csvFile) {
if (is_file($csvFile)) {
$zipOut->addFile($csvFile, $tbl . '.csv');
}
}
$zipOut->close();
File::deleteDirectory($csvDir);
return [
'path' => $outputPath,
'filename' => $outputFilename,
'mime' => 'application/zip',
'work_dir' => $workDir,
];
}
// Format XLSX
if (count($selectedTables) === 1) {
// Single table -> langsung 1 file .xlsx
$tbl = $selectedTables[0];
$outputFilename = 'Tabel_' . $tbl . '_' . $timestamp . '.xlsx';
$outputPath = $workDir . '/' . $outputFilename;
$csvFile = $csvDir . '/' . $tbl . '.csv';
$this->convertCsvToXlsx($csvFile, $tbl, $outputPath);
File::deleteDirectory($csvDir);
return [
'path' => $outputPath,
'filename' => $outputFilename,
'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'work_dir' => $workDir,
];
} else {
// Multiple tables -> dikemas dalam 1 file .zip berisi masing-masing .xlsx
$outputFilename = 'Arsip_KMH_Excel_' . $timestamp . '.zip';
$outputPath = $workDir . '/' . $outputFilename;
$zipOut = new ZipArchive();
if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException("Gagal membuat paket ZIP Excel.");
}
foreach ($extractedTables as $tbl => $csvFile) {
if (is_file($csvFile)) {
$tblXlsxPath = $workDir . '/' . $tbl . '.xlsx';
$this->convertCsvToXlsx($csvFile, $tbl, $tblXlsxPath);
$zipOut->addFile($tblXlsxPath, $tbl . '.xlsx');
}
}
$zipOut->close();
File::deleteDirectory($csvDir);
return [
'path' => $outputPath,
'filename' => $outputFilename,
'mime' => 'application/zip',
'work_dir' => $workDir,
];
}
} catch (\Throwable $e) {
$this->cleanDirectory($workDir);
throw $e;
}
}
/**
* Memfilter isi database.sql hanya untuk tabel terpilih dan menulis ke file output SQL.
*/
protected function extractFilteredSql(string $inputSqlPath, array $selectedTables, string $outputSqlPath): void
{
$inHandle = fopen($inputSqlPath, 'r');
$outHandle = fopen($outputSqlPath, 'w');
if (!$inHandle || !$outHandle) {
if ($inHandle) fclose($inHandle);
if ($outHandle) fclose($outHandle);
throw new RuntimeException("Gagal membuka berkas SQL untuk operasi filter.");
}
try {
$nowStr = now()->format('Y-m-d H:i:s');
$tablesStr = implode(', ', $selectedTables);
fwrite($outHandle, "-- ==============================================================\n");
fwrite($outHandle, "-- RKM-KMH SECURE DATABASE DUMP - HASIL FILTER KONVERSI\n");
fwrite($outHandle, "-- Waktu Ekstrak : {$nowStr} WIB\n");
fwrite($outHandle, "-- Tabel Terpilih: {$tablesStr}\n");
fwrite($outHandle, "-- ==============================================================\n\n");
fwrite($outHandle, "SET NAMES utf8mb4;\n");
fwrite($outHandle, "SET FOREIGN_KEY_CHECKS = 0;\n\n");
$selectedMap = array_fill_keys($selectedTables, true);
$currentTable = null;
$writing = false;
while (($line = fgets($inHandle)) !== false) {
// Deteksi nama tabel pada komentar, DROP TABLE, CREATE TABLE, atau INSERT INTO
if (preg_match('/(?:DROP\s+TABLE\s+IF\s+EXISTS|CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|INSERT\s+INTO)\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
$tbl = $m[1];
$currentTable = $tbl;
$writing = isset($selectedMap[$tbl]);
} elseif (preg_match('/^--\s+(?:Struktur|Dumping\s+Data)\s+untuk\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
$tbl = $m[1];
$currentTable = $tbl;
$writing = isset($selectedMap[$tbl]);
}
if ($writing) {
fwrite($outHandle, $line);
}
}
fwrite($outHandle, "\nSET FOREIGN_KEY_CHECKS = 1;\n");
fwrite($outHandle, "-- END OF FILTERED DUMP\n");
} finally {
fclose($inHandle);
fclose($outHandle);
}
}
/**
* Membaca stream SQL dan mengekstrak tabel-tabel yang dipilih ke file CSV terpisah.
* Sangat hemat memori (RAM usage < 5MB).
*
* @return array<string, string> Map tableName => csvFilePath
*/
protected function streamSqlToCsvFiles(string $sqlPath, array $selectedTables, string $csvOutputDir): array
{
$handle = fopen($sqlPath, 'r');
if (!$handle) {
throw new RuntimeException("Gagal membuka file database.sql untuk pembacaan stream.");
}
$selectedMap = array_fill_keys($selectedTables, true);
$csvHandles = [];
$headerWritten = [];
$activeTable = null;
$activeColumns = [];
try {
while (($line = fgets($handle)) !== false) {
$trimmed = trim($line);
if ($trimmed === '' || str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*')) {
continue;
}
// Cek baris INSERT INTO `tableName` (`col1`, `col2`, ...) VALUES
if (preg_match('/^INSERT\s+INTO\s+`?([a-zA-Z0-9_]+)`?\s*(?:\(([^)]+)\))?\s*VALUES/i', $trimmed, $m)) {
$tbl = $m[1];
if (isset($selectedMap[$tbl])) {
$activeTable = $tbl;
if (!isset($csvHandles[$tbl])) {
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
$csvHandles[$tbl] = fopen($csvPath, 'w');
// Tulis UTF-8 BOM agar Excel membukanya dengan karakter yang sempurna
fwrite($csvHandles[$tbl], "\xEF\xBB\xBF");
}
if (!empty($m[2]) && empty($headerWritten[$tbl])) {
preg_match_all('/`?([a-zA-Z0-9_]+)`?/', $m[2], $colMatches);
$activeColumns = array_values(array_filter(array_map('trim', $colMatches[1] ?? [])));
if (!empty($activeColumns)) {
fputcsv($csvHandles[$tbl], $activeColumns);
$headerWritten[$tbl] = true;
}
}
} else {
$activeTable = null;
}
continue;
}
// Jika sedang membaca baris data dari activeTable
if ($activeTable && isset($csvHandles[$activeTable])) {
$tuples = $this->extractTuplesFromSqlLine($trimmed);
foreach ($tuples as $tupleStr) {
$values = $this->parseTupleValues($tupleStr);
fputcsv($csvHandles[$activeTable], $values);
}
if (str_ends_with($trimmed, ';')) {
$activeTable = null;
}
}
}
// Pastikan semua tabel terpilih memiliki file CSV, meskipun kosong
foreach ($selectedTables as $tbl) {
if (!isset($csvHandles[$tbl])) {
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
$h = fopen($csvPath, 'w');
fwrite($h, "\xEF\xBB\xBF");
fputcsv($h, ['(Tabel kosong / Tidak ada data)']);
fclose($h);
}
}
} finally {
fclose($handle);
foreach ($csvHandles as $h) {
if (is_resource($h)) fclose($h);
}
}
$result = [];
foreach ($selectedTables as $tbl) {
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
if (is_file($csvPath)) {
$result[$tbl] = $csvPath;
}
}
return $result;
}
/**
* Mengonversi berkas CSV tabel menjadi berkas OpenXML .xlsx menggunakan SimpleXlsxExporter.
*/
protected function convertCsvToXlsx(string $csvPath, string $tableName, string $targetXlsxPath): void
{
if (!is_file($csvPath)) {
return;
}
$h = fopen($csvPath, 'r');
if (!$h) return;
// Skip UTF-8 BOM jika ada
$bom = fread($h, 3);
if ($bom !== "\xEF\xBB\xBF") {
rewind($h);
}
$headers = [];
$rows = [];
$rowCount = 0;
$firstRow = fgetcsv($h);
if ($firstRow && !empty($firstRow)) {
$headerMap = [];
foreach ($firstRow as $idx => $colName) {
$headerMap[$colName ?: ('Kolom_' . ($idx + 1))] = 18;
}
$headers = $headerMap;
// Baca baris data (maksimal 50.000 baris untuk kenyamanan memori sheet tunggal)
while (($row = fgetcsv($h)) !== false && $rowCount < 50000) {
$rowCount++;
$rows[] = $row;
}
}
fclose($h);
if (empty($headers)) {
$headers = ['Kolom' => 20];
$rows = [['(Tabel kosong)']];
}
$title = 'DATA ARSIP TABEL: ' . strtoupper($tableName);
$metaLines = [
'Total Data: ' . count($rows) . ' Baris Data',
'Diekstrak dari Arsip .kmh pada: ' . now()->translatedFormat('d F Y, H:i') . ' WIB',
];
$xlsxBinary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, [], $tableName);
file_put_contents($targetXlsxPath, $xlsxBinary);
}
/**
* Ekstrak potongan tuple tuple '(val1, val2, ...)' dari satu baris SQL.
*
* @return array<string>
*/
protected function extractTuplesFromSqlLine(string $content): array
{
$tuples = [];
$inQuotes = false;
$quoteChar = "'";
$inTuple = false;
$tupleBuffer = '';
$len = strlen($content);
for ($i = 0; $i < $len; $i++) {
$c = $content[$i];
if ($inQuotes) {
$tupleBuffer .= $c;
if ($c === '\\') {
$i++;
if ($i < $len) {
$tupleBuffer .= $content[$i];
}
} elseif ($c === $quoteChar) {
if ($i + 1 < $len && $content[$i + 1] === $quoteChar) {
$tupleBuffer .= $content[$i + 1];
$i++;
} else {
$inQuotes = false;
}
}
} else {
if ($c === "'" || $c === '"') {
$inQuotes = true;
$quoteChar = $c;
if ($inTuple) {
$tupleBuffer .= $c;
}
} elseif ($c === '(') {
$inTuple = true;
$tupleBuffer = '';
} elseif ($c === ')' && $inTuple) {
$inTuple = false;
$tuples[] = $tupleBuffer;
$tupleBuffer = '';
} elseif ($inTuple) {
$tupleBuffer .= $c;
}
}
}
return $tuples;
}
/**
* Parsing nilai-nilai di dalam satu tuple SQL menjadi array PHP yang bersih.
*
* @return array<int, mixed>
*/
protected function parseTupleValues(string $tupleStr): array
{
$values = [];
$len = strlen($tupleStr);
$inQuotes = false;
$curr = '';
$quoteChar = "'";
for ($i = 0; $i < $len; $i++) {
$char = $tupleStr[$i];
if ($inQuotes) {
if ($char === '\\') {
$next = $tupleStr[$i + 1] ?? '';
$curr .= match($next) {
'n' => "\n",
'r' => "\r",
't' => "\t",
"'" => "'",
'"' => '"',
'\\' => '\\',
default => $next
};
$i++;
} elseif ($char === $quoteChar) {
if (($tupleStr[$i + 1] ?? '') === $quoteChar) {
$curr .= $quoteChar;
$i++;
} else {
$inQuotes = false;
}
} else {
$curr .= $char;
}
} else {
if ($char === "'" || $char === '"') {
$inQuotes = true;
$quoteChar = $char;
} elseif ($char === ',') {
$val = trim($curr);
$values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
$curr = '';
} else {
$curr .= $char;
}
}
}
$val = trim($curr);
$values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
return $values;
}
/**
* Hapus direktori kerja sementara secara menyeluruh.
*/
public function cleanDirectory(?string $directory): void
{
if ($directory && File::isDirectory($directory)) {
File::deleteDirectory($directory);
}
}
}
+33 -31
View File
@@ -306,51 +306,53 @@ class P2hInspectionPdfExporter extends FPDF
} }
// ------------------------------------------------------------- // -------------------------------------------------------------
// BLOK PENGESAHAN & TANDA TANGAN (3 Kolom) // BLOK PENGESAHAN & TANDA TANGAN (2 Pihak: Operator & Admin QMA)
// ------------------------------------------------------------- // -------------------------------------------------------------
if ($pdf->GetY() > 240) { if ($pdf->GetY() > 235) {
$pdf->AddPage(); $pdf->AddPage();
} }
$pdf->Ln(6); $pdf->Ln(6);
$sigY = $pdf->GetY(); $sigY = $pdf->GetY();
$pdf->SetFont('Arial', 'B', 7.5); $colWidth = 75;
$pdf->SetTextColor(15, 23, 42); $x1 = 20;
$x2 = 115;
// Kolom 1: Operator Lapangan // Kolom 1: Operator Lapangan
$pdf->SetXY(15, $sigY); $pdf->SetXY($x1, $sigY);
$pdf->Cell(56, 4, 'Diperiksa Oleh (Operator):', 0, 1, 'C');
$pdf->SetXY(15, $sigY + 16);
$pdf->SetFont('Arial', 'B', 8); $pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(56, 4, '( ' . ($record->employee->name ?? '..................................') . ' )', 0, 1, 'C');
$pdf->SetFont('Arial', '', 7);
$pdf->SetTextColor(100, 116, 139);
$pdf->Cell(56, 3.5, 'NIK: ' . ($record->employee->nik ?? '-'), 0, 1, 'C');
// Kolom 2: Verifikator QMA
$pdf->SetXY(77, $sigY);
$pdf->SetFont('Arial', 'B', 7.5);
$pdf->SetTextColor(15, 23, 42); $pdf->SetTextColor(15, 23, 42);
$pdf->Cell(56, 4, 'Diverifikasi Oleh (Admin QMA):', 0, 1, 'C'); $pdf->Cell($colWidth, 4, 'Diperiksa Oleh (Operator):', 0, 1, 'C');
$pdf->SetXY(77, $sigY + 16);
$pdf->SetXY($x1, $sigY + 18);
$pdf->SetFont('Arial', 'B', 8.5);
$empName = $record->employee->name ?? '..............................................';
$pdf->Cell($colWidth, 4, '( ' . $empName . ' )', 0, 1, 'C');
$pdf->SetXY($x1, $sigY + 22.5);
$pdf->SetFont('Arial', '', 7.5);
$pdf->SetTextColor(100, 116, 139);
$empNik = $record->employee->nik ?? '-';
$empUnit = $record->employee->unit_kerja ?? '';
$empSub = $empUnit ? "NIK: {$empNik} | {$empUnit}" : "NIK: {$empNik}";
$pdf->Cell($colWidth, 3.5, $empSub, 0, 1, 'C');
// Kolom 2: Verifikator Admin QMA
$pdf->SetXY($x2, $sigY);
$pdf->SetFont('Arial', 'B', 8); $pdf->SetFont('Arial', 'B', 8);
$pdf->SetTextColor(15, 23, 42);
$pdf->Cell($colWidth, 4, 'Diverifikasi Oleh (Admin QMA):', 0, 1, 'C');
$pdf->SetXY($x2, $sigY + 18);
$pdf->SetFont('Arial', 'B', 8.5);
$valName = $record->validator->name ?? 'Admin QMA'; $valName = $record->validator->name ?? 'Admin QMA';
$pdf->Cell(56, 4, '( ' . $valName . ' )', 0, 1, 'C'); $pdf->Cell($colWidth, 4, '( ' . $valName . ' )', 0, 1, 'C');
$pdf->SetFont('Arial', '', 7);
$pdf->SetTextColor(100, 116, 139);
$pdf->Cell(56, 3.5, 'Quality & Maintenance Assets', 0, 1, 'C');
// Kolom 3: Pengawas K3 / HSE $pdf->SetXY($x2, $sigY + 22.5);
$pdf->SetXY(139, $sigY); $pdf->SetFont('Arial', '', 7.5);
$pdf->SetFont('Arial', 'B', 7.5);
$pdf->SetTextColor(15, 23, 42);
$pdf->Cell(56, 4, 'Mengetahui (Pengawas K3/HSE):', 0, 1, 'C');
$pdf->SetXY(139, $sigY + 16);
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(56, 4, '( .............................................. )', 0, 1, 'C');
$pdf->SetFont('Arial', '', 7);
$pdf->SetTextColor(100, 116, 139); $pdf->SetTextColor(100, 116, 139);
$pdf->Cell(56, 3.5, 'Safety / HSE Officer', 0, 1, 'C'); $valTime = $record->validated_at ? 'Diverifikasi: ' . $record->validated_at->format('d/m/Y H:i') . ' WIB' : 'Quality & Maintenance Assets (QMA)';
$pdf->Cell($colWidth, 3.5, $valTime, 0, 1, 'C');
return $pdf->Output('S'); return $pdf->Output('S');
} }
+33 -22
View File
@@ -104,14 +104,15 @@ class SimperPdfExporter extends FPDF
$this->SetFont('Arial', 'B', 7.5); $this->SetFont('Arial', 'B', 7.5);
$cols = [ $cols = [
['NO', 10, 'C'], ['NO', 8, 'C'],
['NIK', 30, 'C'], ['NIK', 25, 'C'],
['NAMA KARYAWAN', 62, 'L'], ['NAMA KARYAWAN', 52, 'L'],
['JABATAN', 45, 'L'], ['JABATAN', 38, 'L'],
['UNIT / DIVISI', 40, 'L'], ['UNIT / DIVISI', 34, 'L'],
['STATUS DRIVER', 26, 'C'], ['DRIVER', 22, 'C'],
['MASA BERLAKU', 26, 'C'], ['JENIS SIMPER', 34, 'C'],
['STATUS SIMPER', 28, 'C'], ['MASA BERLAKU', 25, 'C'],
['STATUS', 29, 'C'],
]; ];
foreach ($cols as $col) { foreach ($cols as $col) {
@@ -180,32 +181,42 @@ class SimperPdfExporter extends FPDF
// Kolom 1: No // Kolom 1: No
$pdf->SetFont('Arial', '', 7.5); $pdf->SetFont('Arial', '', 7.5);
$pdf->Cell(10, 6.5, (string) ($idx + 1), 'B', 0, 'C', $fill); $pdf->Cell(8, 6.5, (string) ($idx + 1), 'B', 0, 'C', $fill);
// Kolom 2: NIK (Bold) // Kolom 2: NIK (Bold)
$pdf->SetFont('Arial', 'B', 7.5); $pdf->SetFont('Arial', 'B', 7.5);
$pdf->Cell(30, 6.5, $emp->nik, 'B', 0, 'C', $fill); $pdf->Cell(25, 6.5, $emp->nik, 'B', 0, 'C', $fill);
// Kolom 3: Nama Lengkap (Bold, Truncate jika > 36 karakter) // Kolom 3: Nama Lengkap (Bold, Truncate jika > 30 karakter)
$nama = mb_strimwidth($emp->name, 0, 36, '...'); $nama = mb_strimwidth($emp->name, 0, 30, '...');
$pdf->Cell(62, 6.5, ' ' . $nama, 'B', 0, 'L', $fill); $pdf->Cell(52, 6.5, ' ' . $nama, 'B', 0, 'L', $fill);
// Kolom 4: Jabatan // Kolom 4: Jabatan
$pdf->SetFont('Arial', '', 7.5); $pdf->SetFont('Arial', '', 7.5);
$jabatan = mb_strimwidth($emp->position ?: '-', 0, 26, '...'); $jabatan = mb_strimwidth($emp->position ?: '-', 0, 22, '...');
$pdf->Cell(45, 6.5, ' ' . $jabatan, 'B', 0, 'L', $fill); $pdf->Cell(38, 6.5, ' ' . $jabatan, 'B', 0, 'L', $fill);
// Kolom 5: Unit / Divisi // Kolom 5: Unit / Divisi
$unit = mb_strimwidth($emp->unit_kerja ?: ($emp->division ?: '-'), 0, 24, '...'); $unit = mb_strimwidth($emp->unit_kerja ?: ($emp->division ?: '-'), 0, 20, '...');
$pdf->Cell(40, 6.5, ' ' . $unit, 'B', 0, 'L', $fill); $pdf->Cell(34, 6.5, ' ' . $unit, 'B', 0, 'L', $fill);
// Kolom 6: Status Driver // Kolom 6: Status Driver
$pdf->Cell(26, 6.5, $isDriver ? 'Driver' : 'Non-Driver', 'B', 0, 'C', $fill); $pdf->Cell(22, 6.5, $isDriver ? 'Driver' : 'Non-Driver', 'B', 0, 'C', $fill);
// Kolom 7: Masa Berlaku // Kolom 7: Rincian Jenis SIMPER
$pdf->Cell(26, 6.5, $expDate, 'B', 0, 'C', $fill); $simperList = $emp->simpers->map(function ($s) {
$code = $s->simperType?->code ?: 'SIMPER';
return str_replace('SIMPER-', '', $code);
})->filter()->unique()->values();
$simperTypesText = $simperList->isNotEmpty() ? $simperList->join(', ') : ($isDriver ? 'LV' : '-');
$pdf->SetFont('Arial', 'B', 7);
$pdf->Cell(34, 6.5, $simperTypesText, 'B', 0, 'C', $fill);
// Kolom 8: Status SIMPER (Berwarna) // Kolom 8: Masa Berlaku
$pdf->SetFont('Arial', '', 7.5);
$pdf->Cell(25, 6.5, $expDate, 'B', 0, 'C', $fill);
// Kolom 9: Status SIMPER (Berwarna)
if ($statusText === 'Masih Berlaku') { if ($statusText === 'Masih Berlaku') {
$pdf->SetTextColor(4, 120, 87); // #047857 Green $pdf->SetTextColor(4, 120, 87); // #047857 Green
} elseif ($statusText === 'Segera Habis') { } elseif ($statusText === 'Segera Habis') {
@@ -216,7 +227,7 @@ class SimperPdfExporter extends FPDF
$pdf->SetTextColor(100, 116, 139); // #64748b Slate $pdf->SetTextColor(100, 116, 139); // #64748b Slate
} }
$pdf->SetFont('Arial', 'B', 7.5); $pdf->SetFont('Arial', 'B', 7.5);
$pdf->Cell(28, 6.5, $statusText, 'B', 0, 'C', $fill); $pdf->Cell(29, 6.5, $statusText, 'B', 0, 'C', $fill);
$pdf->Ln(); $pdf->Ln();
$fill = ! $fill; $fill = ! $fill;
+3 -2
View File
@@ -16,7 +16,7 @@ class SimpleXlsxExporter
* @param array $alignments Optional per-column alignment: 'center' or 'left' * @param array $alignments Optional per-column alignment: 'center' or 'left'
* @return string Raw zip content * @return string Raw zip content
*/ */
public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = []): string public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = [], ?string $sheetName = null): string
{ {
$numCols = count($headers); $numCols = count($headers);
$lastColLetter = self::colLetter($numCols); $lastColLetter = self::colLetter($numCols);
@@ -143,10 +143,11 @@ class SimpleXlsxExporter
</cellXfs> </cellXfs>
</styleSheet>'; </styleSheet>';
$cleanSheetName = htmlspecialchars(mb_substr($sheetName ?: 'Data', 0, 31), ENT_XML1);
$workbookXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> $workbookXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> <workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheets> <sheets>
<sheet name="Data SIMPER" sheetId="1" r:id="rId1" /> <sheet name="' . $cleanSheetName . '" sheetId="1" r:id="rId1" />
</sheets> </sheets>
</workbook>'; </workbook>';
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Artisan;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
if (app()->environment('testing')) {
return;
}
$filePath = base_path('Berkas/DATA LOKASI TERBARU RKM KMH.xlsx');
if (file_exists($filePath)) {
Artisan::call('qma:sync-excel-locations');
}
}
/**
* Reverse the migrations.
*/
public function down(): void
{
// No-op
}
};
@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('unit_transfers', function (Blueprint $table) {
$table->string('transporter_type', 30)->default('internal')->after('user_id');
$table->string('transporter_origin_location', 255)->nullable()->after('transporter_vehicle_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('unit_transfers', function (Blueprint $table) {
$table->dropColumn(['transporter_type', 'transporter_origin_location']);
});
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('vehicles', function (Blueprint $table) {
if (!Schema::hasColumn('vehicles', 'operational_group')) {
$table->string('operational_group', 50)->nullable()->after('unit_type')->index();
}
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('vehicles', function (Blueprint $table) {
if (Schema::hasColumn('vehicles', 'operational_group')) {
$table->dropColumn('operational_group');
}
});
}
};
+7 -1
View File
@@ -9,6 +9,11 @@ server {
index index.php index.html; index index.php index.html;
client_max_body_size 500M; client_max_body_size 500M;
client_body_buffer_size 1M;
client_body_timeout 600s;
client_header_timeout 600s;
send_timeout 600s;
keepalive_timeout 600s;
# Security Headers # Security Headers
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Frame-Options "SAMEORIGIN" always;
@@ -56,7 +61,8 @@ server {
fastcgi_hide_header X-Powered-By; fastcgi_hide_header X-Powered-By;
fastcgi_buffers 16 16k; fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k; fastcgi_buffer_size 32k;
fastcgi_read_timeout 300; fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
} }
location ~ /\.(?!well-known).* { location ~ /\.(?!well-known).* {
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"resources/css/app.css": { "resources/css/app.css": {
"file": "assets/app-CmcfnDoH.css", "file": "assets/app-C1c9fBHF.css",
"src": "resources/css/app.css", "src": "resources/css/app.css",
"isEntry": true, "isEntry": true,
"name": "app", "name": "app",
File diff suppressed because it is too large Load Diff
+419 -134
View File
@@ -9,7 +9,7 @@
<div> <div>
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5"> <h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5">
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span> <span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span>
<span>Matriks Peran & Hak Akses Pengguna</span> <span>Matriks Role & Hak Akses Pengguna</span>
<!-- Tooltip Super Admin Priviledge --> <!-- Tooltip Super Admin Priviledge -->
<div class="relative group/tip inline-flex"> <div class="relative group/tip inline-flex">
<button type="button" <button type="button"
@@ -75,167 +75,294 @@
</div> </div>
@endif @endif
<!-- Ringkasan Role Cards --> <!-- Selector Tab Role Interaktif (Compact & User Friendly) -->
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3"> <div class="space-y-3">
@foreach($roles as $role) <div class="flex items-center justify-between">
@php <span class="text-xs font-bold uppercase tracking-wider text-slate-500 flex items-center gap-1.5">
$isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']); <i class="fa-solid fa-id-badge text-indigo-600"></i>
$badgeColor = match($role->name) { <span>Pilih Peran Pengguna (Role):</span>
'super_admin' => 'bg-indigo-600 text-white', </span>
'hse_admin' => 'bg-emerald-600 text-white', <span class="text-[11px] text-slate-400">Pilih salah satu peran untuk melihat dan mengatur izinnya</span>
'qma_admin' => 'bg-blue-600 text-white', </div>
'pg_admin' => 'bg-purple-600 text-white',
'gate_officer' => 'bg-amber-600 text-white', <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
default => 'bg-slate-700 text-white' @foreach($roles as $role)
}; @php
@endphp $isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']);
<div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm flex flex-col justify-between"> $dotColor = match($role->name) {
<div> 'super_admin' => 'bg-indigo-600',
<div class="flex items-center justify-between mb-2"> 'hse_admin' => 'bg-emerald-600',
<span class="w-2.5 h-2.5 rounded-full {{ $badgeColor }}"></span> 'qma_admin' => 'bg-blue-600',
@if(!$isCoreRole) 'pg_admin' => 'bg-purple-600',
<button type="button" 'gate_officer' => 'bg-amber-600',
onclick='openDeleteRoleModal({{ $role->id }}, "{{ $role->name }}")' default => 'bg-slate-700'
class="text-slate-400 hover:text-rose-600 transition" };
title="Hapus Role Kustom"> @endphp
<i class="fa-solid fa-trash-can text-xs"></i> <button type="button"
</button> onclick="switchRoleTab({{ $role->id }})"
id="tab-btn-{{ $role->id }}"
class="role-tab-btn text-left p-3.5 rounded-2xl border transition duration-200 relative group flex flex-col justify-between {{ $loop->first ? 'border-indigo-600 bg-indigo-50/60 ring-2 ring-indigo-500/20 shadow-sm' : 'border-slate-200/80 bg-white hover:bg-slate-50 hover:border-slate-300' }}">
<div class="w-full">
<div class="flex items-center justify-between mb-2">
<span class="w-2.5 h-2.5 rounded-full {{ $dotColor }}"></span>
@if(!$isCoreRole)
<span onclick="event.stopPropagation(); openDeleteRoleModal({{ $role->id }}, '{{ $role->name }}')"
class="text-slate-300 hover:text-rose-600 p-1 -mr-1 transition"
title="Hapus Role Kustom">
<i class="fa-solid fa-trash-can text-xs"></i>
</span>
@else
<span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Peran Utama</span>
@endif
</div>
<h2 class="text-xs font-bold text-slate-800 capitalize leading-snug">
{{ str_replace('_', ' ', $role->name) }}
</h2>
<p class="text-[10px] text-slate-400 font-mono mt-0.5 truncate">{{ $role->name }}</p>
</div>
<div class="mt-3 pt-2 border-t border-slate-100 flex items-center justify-between text-[11px] w-full">
<span class="text-slate-500">Izin Akses:</span>
@if($role->name === 'super_admin')
<span class="font-black text-indigo-700 flex items-center gap-1">
<i class="fa-solid fa-crown text-[9px] text-amber-500"></i>
<span>Penuh</span>
</span>
@else @else
<span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Peran Utama</span> <span class="font-bold text-indigo-700 role-perm-badge-count" data-role-id="{{ $role->id }}">
{{ $role->permissions->count() }} Izin
</span>
@endif @endif
</div> </div>
<h2 class="text-xs font-bold text-slate-800 capitalize">{{ str_replace('_', ' ', $role->name) }}</h2> </button>
<p class="text-[10px] text-slate-400 mt-0.5 font-mono">{{ $role->name }}</p> @endforeach
</div> </div>
<div class="mt-3 pt-2.5 border-t border-slate-100 flex items-center justify-between text-[11px]">
<span class="text-slate-500">Jumlah Hak Akses:</span>
@if($role->name === 'super_admin')
<div class="relative group/tip inline-flex">
<span class="font-bold text-indigo-700 cursor-help flex items-center gap-1">
<span>Akses Lengkap</span>
<i class="fa-solid fa-circle-info text-[10px] text-indigo-400"></i>
</span>
<div class="absolute right-0 bottom-full mb-2 hidden group-hover/tip:block z-50 w-72 p-3 bg-slate-900 text-white text-xs rounded-xl shadow-xl pointer-events-none">
<div class="flex items-start gap-2">
<i class="fa-solid fa-crown text-amber-400 text-xs mt-0.5 flex-shrink-0"></i>
<div>
<strong class="font-bold text-white text-xs block">Hak Akses Penuh Super Administrator</strong>
<p class="text-slate-300 text-[11px] mt-0.5 leading-relaxed">
Secara otomatis memiliki akses penuh ke seluruh menu dan modul sistem tanpa batasan.
</p>
</div>
</div>
<div class="absolute -bottom-1 right-3 w-2 h-2 bg-slate-900 rotate-45"></div>
</div>
</div>
@else
<span class="font-bold text-indigo-700">
{{ $role->permissions->count() . ' Izin' }}
</span>
@endif
</div>
</div>
@endforeach
</div> </div>
<!-- Matriks Role & Permissions Table --> <!-- Kontainer Panel Hak Akses Per Role (Hanya Role Aktif yang Ditampilkan) -->
<div class="space-y-6"> <div class="space-y-6">
@foreach($roles as $role) @foreach($roles as $role)
<div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden"> @php
<div class="px-5 py-3.5 bg-slate-50 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3"> $rolePermNames = $role->permissions->pluck('name')->toArray();
<div class="flex items-center gap-3"> $isSuperAdmin = $role->name === 'super_admin';
<div class="w-8 h-8 rounded-xl bg-indigo-50 border border-indigo-100 text-indigo-700 flex items-center justify-center font-bold text-xs"> @endphp
<div id="role-panel-{{ $role->id }}"
class="role-panel bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden {{ $loop->first ? '' : 'hidden' }}">
<!-- Panel Header Sticky/Top Bar -->
<div class="px-5 py-4 bg-slate-50/80 border-b border-slate-200/70 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div class="flex items-start sm:items-center gap-3">
<div class="w-10 h-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center font-bold text-sm shadow-sm flex-shrink-0">
<i class="fa-solid fa-shield-halved"></i> <i class="fa-solid fa-shield-halved"></i>
</div> </div>
<div> <div>
<h2 class="text-sm font-bold text-slate-900 capitalize flex items-center gap-2"> <div class="flex items-center gap-2 flex-wrap">
<span>Peran: {{ str_replace('_', ' ', $role->name) }}</span> <h2 class="text-base font-extrabold text-slate-800 capitalize">
@if($role->name === 'super_admin') Pengaturan Hak Akses: {{ str_replace('_', ' ', $role->name) }}
<div class="relative group/satip inline-flex"> </h2>
<span class="px-2 py-0.5 rounded-full text-[9px] font-black bg-indigo-100 text-indigo-800 flex items-center gap-1 cursor-help"> @if($isSuperAdmin)
<i class="fa-solid fa-crown text-[8px]"></i> <span class="px-2.5 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200 inline-flex items-center gap-1">
<span>AKSES LENGKAP</span> <i class="fa-solid fa-crown text-[9px]"></i>
<i class="fa-solid fa-circle-info text-[9px] text-indigo-500"></i> <span>BYPASS PENUH</span>
</span> </span>
<div class="absolute left-0 top-full mt-2 hidden group-hover/satip:block z-50 w-72 sm:w-80 p-3 bg-slate-900 text-white text-xs rounded-xl shadow-xl pointer-events-none"> @else
<div class="flex items-start gap-2.5"> <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-indigo-100 text-indigo-800 border border-indigo-200">
<i class="fa-solid fa-crown text-amber-400 text-xs mt-0.5 flex-shrink-0"></i> Peran: <code class="font-mono">{{ $role->name }}</code>
<div> </span>
<strong class="font-bold text-white text-xs block">Hak Akses Penuh Super Administrator</strong>
<p class="text-slate-300 text-[11px] mt-0.5 leading-relaxed">
Akun dengan peran <strong>Super Administrator</strong> secara otomatis memiliki akses penuh ke seluruh menu dan modul sistem tanpa batasan. Pilihan centang di bawah digunakan untuk mengatur batasan akses peran staf operasional lainnya.
</p>
</div>
</div>
<div class="absolute -top-1 left-4 w-2 h-2 bg-slate-900 rotate-45"></div>
</div>
</div>
@endif @endif
</h2> </div>
<p class="text-[11px] text-slate-400">Atur centang hak akses menu yang diizinkan untuk peran pengguna ini.</p> <p class="text-xs text-slate-500 mt-0.5">
@if($isSuperAdmin)
Peran ini adalah tingkat tertinggi sistem. Seluruh hak akses otomatis aktif secara permanen.
@else
Centang fitur atau menu yang boleh diakses dan dijalankan oleh pengguna dengan peran ini.
@endif
</p>
</div> </div>
</div> </div>
@if($role->name !== 'super_admin') <!-- Tombol Aksi & Simpan -->
<button type="submit" <div class="flex items-center gap-2 self-end md:self-auto flex-wrap">
form="form-role-{{ $role->id }}" @if(!$isSuperAdmin)
class="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-sm transition self-end sm:self-auto"> <button type="button"
<i class="fa-solid fa-floppy-disk"></i> onclick="toggleAllRolePermissions({{ $role->id }}, true)"
<span>Simpan Hak Akses</span> class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5"
</button> title="Centang semua hak akses untuk peran ini">
@endif <i class="fa-solid fa-check-double text-indigo-600"></i>
<span>Pilih Semua</span>
</button>
<button type="button"
onclick="toggleAllRolePermissions({{ $role->id }}, false)"
class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5"
title="Hilangkan semua centang untuk peran ini">
<i class="fa-solid fa-rotate-left text-slate-500"></i>
<span>Kosongkan</span>
</button>
<button type="submit"
form="form-role-{{ $role->id }}"
class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-md shadow-indigo-600/20 transition">
<i class="fa-solid fa-floppy-disk"></i>
<span>Simpan Perubahan</span>
</button>
@endif
</div>
</div> </div>
@if($isSuperAdmin)
<!-- Notifikasi Super Admin Bypass -->
<div class="m-5 p-4 rounded-xl bg-amber-50/70 border border-amber-200/80 flex items-start gap-3 text-amber-900 text-xs">
<i class="fa-solid fa-circle-exclamation text-amber-600 text-base mt-0.5 flex-shrink-0"></i>
<div>
<strong class="font-bold block">Hak Akses Super Administrator Tidak Terbatas</strong>
<p class="text-amber-800 text-[11px] mt-0.5 leading-relaxed">
Sesuai arsitektur keamanan Spatie RBAC, pengguna dengan peran <code>super_admin</code> memiliki hak <em>Gate::before bypass</em> yang mengizinkan akses ke seluruh API, controller, rute, dan menu tanpa perlu diverifikasi satu per satu.
</p>
</div>
</div>
@else
<!-- Search Filter Bar per Role -->
<div class="px-5 pt-4 pb-2 flex flex-col sm:flex-row items-center justify-between gap-3 border-b border-slate-100">
<div class="relative w-full sm:w-80">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="search-role-{{ $role->id }}"
oninput="filterRolePermissions({{ $role->id }}, this.value)"
placeholder="Cari izin / nama menu (misal: p2h, simper, gate)..."
class="w-full pl-9 pr-8 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-indigo-500 focus:bg-white focus:border-indigo-500 transition">
<button type="button"
onclick="clearRoleSearch({{ $role->id }})"
id="clear-search-{{ $role->id }}"
class="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 hidden text-xs">
<i class="fa-solid fa-circle-xmark"></i>
</button>
</div>
<div class="text-[11px] text-slate-500 flex items-center gap-2">
<span class="w-2 h-2 rounded-full bg-emerald-500"></span>
<span>Total Terpilih:</span>
<strong class="font-bold text-slate-800" id="selected-stat-{{ $role->id }}">{{ count($rolePermNames) }}</strong>
<span class="text-slate-400">izin aktif</span>
</div>
</div>
@endif
<!-- Form Modul & Permission Checklists -->
<form id="form-role-{{ $role->id }}" <form id="form-role-{{ $role->id }}"
action="{{ route('admin.roles.permissions.update', $role->id) }}" action="{{ route('admin.roles.permissions.update', $role->id) }}"
method="POST" method="POST"
class="p-5"> class="p-5">
@csrf @csrf
@php <div id="module-grid-{{ $role->id }}" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
$rolePermNames = $role->permissions->pluck('name')->toArray();
@endphp
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
@foreach($modules as $moduleKey => $module) @foreach($modules as $moduleKey => $module)
<div class="bg-slate-50/70 border border-slate-200/60 rounded-xl p-4 space-y-3"> @php
<h3 class="text-xs font-bold text-slate-800 flex items-center justify-between pb-2 border-b border-slate-200/60"> $totalInModule = count($module['permissions']);
<span class="flex items-center gap-1.5"> $activeInModule = 0;
<i class="{{ $module['icon'] }} text-indigo-600 text-xs"></i> foreach($module['permissions'] as $pKey => $pMeta) {
<span>{{ $module['name'] }}</span> if ($isSuperAdmin || in_array($pKey, $rolePermNames)) {
</span> $activeInModule++;
<span class="text-[10px] text-slate-400 font-semibold">{{ count($module['permissions']) }} hak akses</span> }
</h3> }
@endphp
<div class="space-y-2"> <div class="perm-module-card bg-slate-50/70 border border-slate-200/70 rounded-xl p-4 flex flex-col justify-between space-y-3 transition"
@foreach($module['permissions'] as $permKey => $permMeta) data-module-key="{{ $moduleKey }}">
@php <div>
$isChecked = $role->name === 'super_admin' || in_array($permKey, $rolePermNames); <!-- Header Modul -->
@endphp <div class="flex items-center justify-between pb-2.5 border-b border-slate-200/60 mb-2.5">
<label class="flex items-start gap-2.5 text-xs text-slate-700 cursor-pointer select-none group p-2 rounded-lg hover:bg-white hover:shadow-xs border border-transparent hover:border-slate-200/60 transition"> <div class="flex items-center gap-2">
<input type="checkbox" <div class="w-6 h-6 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center text-xs">
name="permissions[]" <i class="{{ $module['icon'] }}"></i>
value="{{ $permKey }}"
{{ $isChecked ? 'checked' : '' }}
{{ $role->name === 'super_admin' ? 'disabled' : '' }}
class="mt-1 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 transition">
<div>
<span class="text-xs font-bold text-slate-800 group-hover:text-indigo-600 transition block">
{{ $permMeta['label'] }}
</span>
<p class="text-[11px] text-slate-500 mt-0.5 leading-snug">
{{ $permMeta['description'] }}
</p>
<span class="font-mono text-[10px] text-slate-400 mt-1 block">
{{ $permKey }}
</span>
</div> </div>
</label> <h3 class="text-xs font-bold text-slate-800 leading-snug">
@endforeach {{ $module['name'] }}
</h3>
</div>
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-500 bg-white px-2 py-0.5 rounded-md border border-slate-200/80 module-counter"
id="mod-count-{{ $role->id }}-{{ $moduleKey }}">
{{ $activeInModule }}/{{ $totalInModule }}
</span>
@if(!$isSuperAdmin)
<div class="flex items-center space-x-1">
<button type="button"
onclick="toggleModuleCheckboxes({{ $role->id }}, '{{ $moduleKey }}', true)"
class="text-[10px] font-bold text-indigo-600 hover:text-indigo-800 px-1 py-0.5 hover:bg-indigo-50 rounded transition"
title="Centang semua di modul ini">
Semua
</button>
<span class="text-slate-300 text-[10px]">|</span>
<button type="button"
onclick="toggleModuleCheckboxes({{ $role->id }}, '{{ $moduleKey }}', false)"
class="text-[10px] font-bold text-slate-500 hover:text-slate-700 px-1 py-0.5 hover:bg-slate-200/50 rounded transition"
title="Batalkan centang modul ini">
Batal
</button>
</div>
@endif
</div>
</div>
<!-- Daftar Permission -->
<div class="space-y-1.5">
@foreach($module['permissions'] as $permKey => $permMeta)
@php
$isChecked = $isSuperAdmin || in_array($permKey, $rolePermNames);
@endphp
<label class="perm-item flex items-start gap-2.5 text-xs text-slate-700 cursor-pointer select-none group p-2 rounded-lg hover:bg-white hover:shadow-xs border border-transparent hover:border-slate-200/60 transition {{ $isChecked ? 'bg-indigo-50/20' : '' }}"
data-search-text="{{ strtolower($permMeta['label'] . ' ' . $permMeta['description'] . ' ' . $permKey . ' ' . $module['name']) }}">
<input type="checkbox"
name="permissions[]"
value="{{ $permKey }}"
data-module="{{ $moduleKey }}"
onchange="onPermissionChange({{ $role->id }}, '{{ $moduleKey }}')"
{{ $isChecked ? 'checked' : '' }}
{{ $isSuperAdmin ? 'disabled' : '' }}
class="perm-checkbox-{{ $role->id }} mt-0.5 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 transition">
<div class="flex-1 min-w-0">
<span class="text-xs font-bold text-slate-800 group-hover:text-indigo-600 transition block">
{{ $permMeta['label'] }}
</span>
<p class="text-[11px] text-slate-500 mt-0.5 leading-snug">
{{ $permMeta['description'] }}
</p>
<span class="font-mono text-[9px] text-slate-400 mt-0.5 block truncate">
{{ $permKey }}
</span>
</div>
</label>
@endforeach
</div>
</div> </div>
</div> </div>
@endforeach @endforeach
</div> </div>
<!-- Empty Search Result State -->
<div id="empty-search-{{ $role->id }}" class="hidden py-12 text-center">
<div class="w-12 h-12 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto mb-2 text-base">
<i class="fa-solid fa-magnifying-glass"></i>
</div>
<h4 class="text-xs font-bold text-slate-700">Tidak ada hak akses yang cocok</h4>
<p class="text-[11px] text-slate-400 mt-0.5">Coba gunakan kata kunci pencarian yang lain.</p>
<button type="button" onclick="clearRoleSearch({{ $role->id }})" class="mt-3 px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg text-xs font-bold transition">
Reset Pencarian
</button>
</div>
@if(!$isSuperAdmin)
<!-- Bottom Action Bar -->
<div class="mt-6 pt-4 border-t border-slate-100 flex items-center justify-between">
<p class="text-xs text-slate-400">
Pastikan klik tombol <strong>Simpan Perubahan</strong> untuk menerapkan hak akses ke pengguna terkait.
</p>
<button type="submit"
class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-md shadow-indigo-600/20 transition">
<i class="fa-solid fa-floppy-disk"></i>
<span>Simpan Perubahan</span>
</button>
</div>
@endif
</form> </form>
</div> </div>
@endforeach @endforeach
@@ -306,6 +433,164 @@
</div> </div>
<script> <script>
// Tab switching antar Role
function switchRoleTab(roleId) {
// Sembunyikan semua panel role
document.querySelectorAll('.role-panel').forEach(panel => {
panel.classList.add('hidden');
});
// Non-aktifkan semua styling tombol tab
document.querySelectorAll('.role-tab-btn').forEach(btn => {
btn.classList.remove('border-indigo-600', 'bg-indigo-50/60', 'ring-2', 'ring-indigo-500/20', 'shadow-sm');
btn.classList.add('border-slate-200/80', 'bg-white');
});
// Tampilkan panel role terpilih
const activePanel = document.getElementById(`role-panel-${roleId}`);
if (activePanel) {
activePanel.classList.remove('hidden');
}
// Aktifkan styling tab terpilih
const activeBtn = document.getElementById(`tab-btn-${roleId}`);
if (activeBtn) {
activeBtn.classList.remove('border-slate-200/80', 'bg-white');
activeBtn.classList.add('border-indigo-600', 'bg-indigo-50/60', 'ring-2', 'ring-indigo-500/20', 'shadow-sm');
}
}
// Toggle semua checkbox untuk role tertentu
function toggleAllRolePermissions(roleId, checked) {
const checkboxes = document.querySelectorAll(`.perm-checkbox-${roleId}`);
checkboxes.forEach(cb => {
if (!cb.disabled) {
cb.checked = checked;
}
});
updateRoleStats(roleId);
}
// Toggle checkbox per modul
function toggleModuleCheckboxes(roleId, moduleKey, checked) {
const checkboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${moduleKey}"]`);
checkboxes.forEach(cb => {
if (!cb.disabled) {
cb.checked = checked;
}
});
onPermissionChange(roleId, moduleKey);
}
// Handler ketika ada checkbox yang berubah
function onPermissionChange(roleId, moduleKey) {
// Update counter per modul
const modCheckboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${moduleKey}"]`);
const checkedInMod = Array.from(modCheckboxes).filter(cb => cb.checked).length;
const totalInMod = modCheckboxes.length;
const counterEl = document.getElementById(`mod-count-${roleId}-${moduleKey}`);
if (counterEl) {
counterEl.textContent = `${checkedInMod}/${totalInMod}`;
}
updateRoleStats(roleId);
}
// Update counter total hak akses aktif untuk suatu role
function updateRoleStats(roleId) {
const allCheckboxes = document.querySelectorAll(`.perm-checkbox-${roleId}`);
const totalChecked = Array.from(allCheckboxes).filter(cb => cb.checked).length;
// Update badge di header panel
const statEl = document.getElementById(`selected-stat-${roleId}`);
if (statEl) {
statEl.textContent = totalChecked;
}
// Update badge di tombol tab atas
const tabBadge = document.querySelector(`.role-perm-badge-count[data-role-id="${roleId}"]`);
if (tabBadge) {
tabBadge.textContent = `${totalChecked} Izin`;
}
// Update semua counter modul
const modules = new Set();
allCheckboxes.forEach(cb => {
const m = cb.getAttribute('data-module');
if (m) modules.add(m);
});
modules.forEach(m => {
const modCheckboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${m}"]`);
const checkedInMod = Array.from(modCheckboxes).filter(cb => cb.checked).length;
const totalInMod = modCheckboxes.length;
const counterEl = document.getElementById(`mod-count-${roleId}-${m}`);
if (counterEl) {
counterEl.textContent = `${checkedInMod}/${totalInMod}`;
}
});
}
// Live Search Filter Hak Akses
function filterRolePermissions(roleId, rawKeyword) {
const keyword = (rawKeyword || '').toLowerCase().trim();
const clearBtn = document.getElementById(`clear-search-${roleId}`);
if (clearBtn) {
clearBtn.classList.toggle('hidden', keyword.length === 0);
}
const panel = document.getElementById(`role-panel-${roleId}`);
if (!panel) return;
const moduleCards = panel.querySelectorAll('.perm-module-card');
let totalVisibleCards = 0;
moduleCards.forEach(card => {
const items = card.querySelectorAll('.perm-item');
let visibleInCard = 0;
items.forEach(item => {
const text = item.getAttribute('data-search-text') || '';
if (!keyword || text.includes(keyword)) {
item.classList.remove('hidden');
visibleInCard++;
} else {
item.classList.add('hidden');
}
});
if (visibleInCard > 0) {
card.classList.remove('hidden');
totalVisibleCards++;
} else {
card.classList.add('hidden');
}
});
const emptyState = document.getElementById(`empty-search-${roleId}`);
const moduleGrid = document.getElementById(`module-grid-${roleId}`);
if (emptyState && moduleGrid) {
if (totalVisibleCards === 0 && keyword.length > 0) {
emptyState.classList.remove('hidden');
moduleGrid.classList.add('hidden');
} else {
emptyState.classList.add('hidden');
moduleGrid.classList.remove('hidden');
}
}
}
function clearRoleSearch(roleId) {
const input = document.getElementById(`search-role-${roleId}`);
if (input) {
input.value = '';
filterRolePermissions(roleId, '');
input.focus();
}
}
// Modal Manajemen Role
function openCreateRoleModal() { function openCreateRoleModal() {
document.getElementById('createRoleModal').classList.remove('hidden'); document.getElementById('createRoleModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open'); document.documentElement.classList.add('modal-open');
+17
View File
@@ -197,6 +197,23 @@
<span>Berlaku s.d. {{ $log->simper_expired_at->locale('id')->translatedFormat('d M Y') }} ({{ $log->simper_expired_at->locale('id')->diffForHumans() }})</span> <span>Berlaku s.d. {{ $log->simper_expired_at->locale('id')->translatedFormat('d M Y') }} ({{ $log->simper_expired_at->locale('id')->diffForHumans() }})</span>
</p> </p>
@endif @endif
<!-- Rincian Badge Multi-SIMPER Personil -->
@if($log->simpers && $log->simpers->isNotEmpty())
<div class="flex items-center gap-1.5 flex-wrap mt-1.5 pt-1.5 border-t border-slate-100">
@foreach($log->simpers as $smp)
@php
$smpValid = $smp->isValid();
$smpCode = $smp->simperType?->code ?: 'SIMPER';
$shortCode = str_replace('SIMPER-', '', $smpCode);
@endphp
<span class="inline-flex items-center px-2 py-0.5 rounded text-[9px] font-bold font-mono {{ $smpValid ? 'bg-emerald-50 text-emerald-800 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200' }}" title="{{ $smp->simperType?->name }}: s/d {{ $smp->expired_at ? $smp->expired_at->format('d/m/Y') : '-' }}">
<i class="fa-solid {{ $smpValid ? 'fa-circle-check text-emerald-600' : 'fa-circle-xmark text-rose-600' }} mr-1 text-[8px]"></i>
<span>{{ $shortCode }}: {{ $smp->expired_at ? $smp->expired_at->format('d/m/y') : '-' }}</span>
</span>
@endforeach
</div>
@endif
</div> </div>
<!-- Badge Kanan --> <!-- Badge Kanan -->
+15 -2
View File
@@ -242,9 +242,11 @@
</label> </label>
<input type="text" <input type="text"
name="simper_assignments[{{ $st->id }}][simper_number]" name="simper_assignments[{{ $st->id }}][simper_number]"
id="inputSimperNum_{{ $st->id }}"
value="{{ $simperNum }}" value="{{ $simperNum }}"
{{ $isChecked ? '' : 'disabled' }}
placeholder="Contoh: SMP-LV-001" placeholder="Contoh: SMP-LV-001"
class="w-full text-xs px-3 py-2 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-emerald-600"> class="w-full text-xs px-3 py-2 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-emerald-600 disabled:opacity-50 disabled:bg-slate-100">
</div> </div>
<div> <div>
<label class="block text-[11px] font-bold text-slate-600 mb-1"> <label class="block text-[11px] font-bold text-slate-600 mb-1">
@@ -252,8 +254,10 @@
</label> </label>
<input type="date" <input type="date"
name="simper_assignments[{{ $st->id }}][expired_at]" name="simper_assignments[{{ $st->id }}][expired_at]"
id="inputSimperExp_{{ $st->id }}"
value="{{ $simperExp }}" value="{{ $simperExp }}"
class="w-full text-xs px-3 py-2 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-emerald-600"> {{ $isChecked ? '' : 'disabled' }}
class="w-full text-xs px-3 py-2 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-emerald-600 disabled:opacity-50 disabled:bg-slate-100">
</div> </div>
</div> </div>
</div> </div>
@@ -359,11 +363,20 @@
function toggleSimperRow(id) { function toggleSimperRow(id) {
const chk = document.getElementById(`chkSimper_${id}`); const chk = document.getElementById(`chkSimper_${id}`);
const fields = document.getElementById(`fieldsSimper_${id}`); const fields = document.getElementById(`fieldsSimper_${id}`);
const numInp = document.getElementById(`inputSimperNum_${id}`);
const expInp = document.getElementById(`inputSimperExp_${id}`);
if (chk && fields) { if (chk && fields) {
if (chk.checked) { if (chk.checked) {
fields.classList.remove('hidden'); fields.classList.remove('hidden');
if (numInp) numInp.disabled = false;
if (expInp) expInp.disabled = false;
} else { } else {
fields.classList.add('hidden'); fields.classList.add('hidden');
if (numInp) numInp.disabled = true;
if (expInp) {
expInp.disabled = true;
expInp.value = '';
}
} }
} }
} }
+440 -45
View File
@@ -281,7 +281,7 @@
<i class="fa-solid fa-up-right-from-square text-[11px]"></i> <i class="fa-solid fa-up-right-from-square text-[11px]"></i>
</a> </a>
<span class="text-slate-200">|</span> <span class="text-slate-200">|</span>
<button onclick="openRenewModal({{ $emp->id }}, '{{ addslashes($emp->name) }}', '{{ $emp->simper_expired_at ? $emp->simper_expired_at->format('Y-m-d') : '' }}', {{ $emp->is_operator ? '1' : '0' }})" <button onclick='openRenewModal(@json($emp))'
class="text-emerald-700 hover:text-emerald-900 font-bold underline text-[11px] px-1 cursor-pointer" class="text-emerald-700 hover:text-emerald-900 font-bold underline text-[11px] px-1 cursor-pointer"
title="Perpanjang Masa Berlaku SIMPER"> title="Perpanjang Masa Berlaku SIMPER">
Perpanjang Perpanjang
@@ -633,43 +633,123 @@
</div> </div>
</div> </div>
<!-- Modal Dialog Perpanjang SIMPER (Clean White Card) --> <!-- Modal Dialog Perpanjang SIMPER (Clean White Card dengan Dukungan Multi-SIMPER) -->
<div id="renewModal" data-backdrop="static" class="hidden fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4"> <div id="renewModal" data-backdrop="static" class="hidden fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl shadow-2xl max-w-md w-full p-7 border border-slate-100 overflow-hidden"> <div class="bg-white rounded-3xl shadow-2xl max-w-lg w-full p-6 sm:p-7 border border-slate-100 overflow-hidden animate-scale-in max-h-[92vh] flex flex-col">
<div class="flex items-center justify-between pb-4 border-b border-slate-100"> <div class="flex items-center justify-between pb-3.5 border-b border-slate-100 flex-shrink-0">
<h3 class="text-xl font-bold text-slate-900 tracking-tight">Perpanjang SIMPER</h3> <div>
<h3 class="text-base sm:text-lg font-bold text-slate-900 tracking-tight flex items-center gap-2">
<div class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center text-sm border border-emerald-100">
<i class="fa-solid fa-id-card-clip"></i>
</div>
<span>Perpanjang Masa Berlaku SIMPER</span>
</h3>
<p class="text-xs text-slate-500 mt-0.5">Pilih jenis SIMPER personel dan tentukan tanggal masa berlaku operasional baru.</p>
</div>
<button type="button" onclick="closeRenewModal()" class="text-slate-400 hover:text-slate-600 transition p-1"> <button type="button" onclick="closeRenewModal()" class="text-slate-400 hover:text-slate-600 transition p-1">
<i class="fa-solid fa-xmark text-lg"></i> <i class="fa-solid fa-xmark text-lg"></i>
</button> </button>
</div> </div>
<form id="renewForm" method="POST" action="" class="mt-5 space-y-4"> <form id="renewForm" method="POST" action="" class="mt-4 space-y-4 overflow-y-auto pr-1">
@csrf @csrf
<div class="bg-slate-50 p-3.5 rounded-2xl border border-slate-200/80"> <!-- Identitas Personel (Karyawan / Sukon) -->
<span class="text-xs text-slate-400 block font-medium">Pengemudi:</span> <div class="bg-slate-50/90 p-3.5 rounded-2xl border border-slate-200/80 flex items-start justify-between gap-3">
<strong id="renewName" class="block text-base text-slate-900 font-bold mt-0.5"></strong> <div class="min-w-0">
<span class="text-[10px] text-slate-400 block font-bold uppercase tracking-wider">Personel / Operator:</span>
<strong id="renewName" class="block text-sm text-slate-900 font-extrabold mt-0.5 truncate"></strong>
<div class="flex items-center gap-2 mt-1 flex-wrap">
<span id="renewNik" class="text-[11px] font-mono font-bold text-slate-600 bg-white px-2 py-0.5 rounded border border-slate-200"></span>
<span id="renewUnitDept" class="text-[11px] text-slate-500"></span>
</div>
</div>
<div class="flex flex-col items-end gap-1 flex-shrink-0">
<span id="renewCategoryBadge" class="px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-slate-200/70 text-slate-700">
Karyawan
</span>
<span class="px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-emerald-100 text-[#1b5e20] border border-emerald-200/80">
Driver / Operator
</span>
</div>
</div> </div>
<!-- Status Driver (Hidden input default 1) -->
<input type="hidden" name="is_operator" id="renewOperator" value="1">
<!-- Ringkasan SIMPER yang Sedang Dimiliki Saat Ini -->
<div class="p-3.5 rounded-2xl bg-indigo-50/30 border border-indigo-100/70 space-y-2">
<div class="flex items-center justify-between">
<span class="text-xs font-bold text-slate-800 flex items-center gap-1.5">
<i class="fa-solid fa-shield-halved text-indigo-600 text-xs"></i>
<span>SIMPER yang Sedang Dimiliki Saat Ini:</span>
</span>
<span id="renewSimperBadge" class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-white text-indigo-700 border border-indigo-200 font-mono"></span>
</div>
<div id="renewCurrentSimperCards" class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
<!-- Dinamis via JavaScript -->
</div>
</div>
<!-- Dropdown Pilihan Jenis SIMPER yang Diperpanjang -->
<div> <div>
<label class="block text-sm font-bold text-slate-800 mb-2">Status Driver</label> <label for="renewSimperTypeSelect" class="block text-xs font-bold text-slate-800 mb-1.5 flex items-center justify-between">
<select name="is_operator" id="renewOperator" onchange="toggleSimperInput('renew')" <span>Pilih SIMPER yang Ingin Diperpanjang <span class="text-rose-500">*</span></span>
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition"> <span class="text-[10px] text-slate-400 font-normal">Pilih satu atau semua</span>
<option value="1">YA (Aktif Mengemudi)</option> </label>
<option value="0">TIDAK (Bukan Driver)</option> <select name="renew_simper_type_id" id="renewSimperTypeSelect" onchange="onRenewSimperTypeChange(this.value)" required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-300 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition shadow-xs">
<!-- Dinamis via JavaScript -->
</select> </select>
</div> </div>
<div>
<label class="block text-sm font-bold text-slate-800 mb-2">Masa Berlaku Baru <span class="text-rose-500">*</span></label> <!-- Detail SIMPER Terpilih (Live Information Box) -->
<input type="date" name="simper_expired_at" id="renewDate" required <div id="renewSelectedDetailBox" class="p-3 rounded-xl bg-slate-50 border border-slate-200/80 text-xs space-y-1">
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition"> <div class="flex items-center justify-between">
<span class="text-[11px] text-slate-500">Masa Berlaku Saat Ini:</span>
<strong id="renewCurrentExpText" class="text-slate-800 font-mono text-[11px]">-</strong>
</div>
<div class="flex items-center justify-between">
<span class="text-[11px] text-slate-500">Status Izin:</span>
<span id="renewCurrentStatusBadge" class="text-[10px] font-bold px-2 py-0.2 rounded font-mono">-</span>
</div>
</div> </div>
<div class="pt-6 border-t border-slate-100 flex items-center justify-end space-x-3 mt-6">
<!-- Input Tanggal Kedaluwarsa Baru -->
<div>
<label for="renewDate" class="block text-xs font-bold text-slate-800 mb-1.5 flex items-center justify-between">
<span>Masa Berlaku Baru (Hasil Perpanjangan) <span class="text-rose-500">*</span></span>
<span class="text-[10px] text-emerald-700 font-semibold" id="renewRecommendLabel">Rekomendasi: +1 Tahun</span>
</label>
<input type="date" name="simper_expired_at" id="renewDate" required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-300 bg-white text-slate-800 font-bold font-mono focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition shadow-xs">
<!-- Quick Preset Buttons (+6 Bulan, +1 Tahun, +2 Tahun, +3 Tahun) -->
<div class="flex items-center gap-1.5 mt-2 flex-wrap">
<span class="text-[10px] text-slate-400 font-bold uppercase tracking-wider mr-1">Pintas Cepat:</span>
<button type="button" onclick="setRenewDateOffset(6)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+6 Bulan
</button>
<button type="button" onclick="setRenewDateOffset(12)" class="text-[11px] px-2.5 py-1 rounded-lg border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-[#1b5e20] font-bold transition cursor-pointer">
+1 Tahun (Standar)
</button>
<button type="button" onclick="setRenewDateOffset(24)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+2 Tahun
</button>
<button type="button" onclick="setRenewDateOffset(36)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+3 Tahun
</button>
</div>
</div>
<div class="pt-4 border-t border-slate-100 flex items-center justify-end space-x-2.5 mt-5">
<button type="button" onclick="closeRenewModal()" <button type="button" onclick="closeRenewModal()"
class="px-6 py-2.5 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 font-bold text-sm transition"> class="px-4 py-2 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 font-bold text-xs transition">
Batal Batal
</button> </button>
<button type="submit" <button type="submit"
class="px-6 py-2.5 rounded-xl bg-[#1b5e20] hover:bg-[#144919] text-white font-bold text-sm transition shadow-sm"> class="px-5 py-2.5 rounded-xl bg-[#1b5e20] hover:bg-[#144919] text-white font-bold text-xs transition shadow-md shadow-emerald-700/20 inline-flex items-center gap-1.5">
Simpan Data <i class="fa-solid fa-floppy-disk text-xs"></i>
<span>Simpan Perpanjangan</span>
</button> </button>
</div> </div>
</form> </form>
@@ -1152,13 +1232,20 @@
function toggleEditSimperFields(id) { function toggleEditSimperFields(id) {
const check = document.getElementById(`editSimperCheck_${id}`); const check = document.getElementById(`editSimperCheck_${id}`);
const fields = document.getElementById(`editSimperFields_${id}`); const fields = document.getElementById(`editSimperFields_${id}`);
const numInp = document.getElementById(`editSimperNum_${id}`);
const expInp = document.getElementById(`editSimperExp_${id}`);
if (check && fields) { if (check && fields) {
if (check.checked) { if (check.checked) {
fields.classList.remove('hidden'); fields.classList.remove('hidden');
if (numInp) numInp.disabled = false;
if (expInp) expInp.disabled = false;
} else { } else {
fields.classList.add('hidden'); fields.classList.add('hidden');
const expInp = document.getElementById(`editSimperExp_${id}`); if (numInp) numInp.disabled = true;
if (expInp) expInp.value = ''; if (expInp) {
expInp.disabled = true;
expInp.value = '';
}
} }
} }
syncEditPrimarySimperDate(); syncEditPrimarySimperDate();
@@ -1248,9 +1335,9 @@
const fields = document.getElementById(`editSimperFields_${id}`); const fields = document.getElementById(`editSimperFields_${id}`);
if (fields) fields.classList.add('hidden'); if (fields) fields.classList.add('hidden');
const num = document.getElementById(`editSimperNum_${id}`); const num = document.getElementById(`editSimperNum_${id}`);
if (num) num.value = ''; if (num) { num.value = ''; num.disabled = true; }
const exp = document.getElementById(`editSimperExp_${id}`); const exp = document.getElementById(`editSimperExp_${id}`);
if (exp) exp.value = ''; if (exp) { exp.value = ''; exp.disabled = true; }
}); });
// Isi checklist SIMPER dari data emp.simpers // Isi checklist SIMPER dari data emp.simpers
@@ -1263,8 +1350,8 @@
if (cb) { if (cb) {
cb.checked = true; cb.checked = true;
if (fields) fields.classList.remove('hidden'); if (fields) fields.classList.remove('hidden');
if (num) num.value = s.simper_number || ''; if (num) { num.value = s.simper_number || ''; num.disabled = false; }
if (exp && s.expired_at) exp.value = s.expired_at.substring(0, 10); if (exp && s.expired_at) { exp.value = s.expired_at.substring(0, 10); exp.disabled = false; }
} }
}); });
} else if (emp.is_operator && expDate) { } else if (emp.is_operator && expDate) {
@@ -1274,8 +1361,10 @@
const id = firstCb.id.replace('editSimperCheck_', ''); const id = firstCb.id.replace('editSimperCheck_', '');
const fields = document.getElementById(`editSimperFields_${id}`); const fields = document.getElementById(`editSimperFields_${id}`);
if (fields) fields.classList.remove('hidden'); if (fields) fields.classList.remove('hidden');
const num = document.getElementById(`editSimperNum_${id}`);
if (num) num.disabled = false;
const exp = document.getElementById(`editSimperExp_${id}`); const exp = document.getElementById(`editSimperExp_${id}`);
if (exp) exp.value = expDate; if (exp) { exp.value = expDate; exp.disabled = false; }
} }
} }
syncEditPrimarySimperDate(); syncEditPrimarySimperDate();
@@ -1320,28 +1409,310 @@
document.getElementById('editForm').action = `/hse/employees/${emp.id}`; document.getElementById('editForm').action = `/hse/employees/${emp.id}`;
document.getElementById('editModal').classList.remove('hidden'); document.getElementById('editModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
} }
function closeEditModal() { function closeEditModal() {
const modal = document.getElementById('editModal'); const modal = document.getElementById('editModal');
if (modal) modal.classList.add('hidden'); if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
} }
function openRenewModal(id, name, expiredDate, isOperator) { const allMasterSimperTypes = @json($availableSimperTypes ?? []);
document.getElementById('renewName').textContent = name; let currentRenewEmployee = null;
document.getElementById('renewOperator').value = isOperator ? '1' : '0';
document.getElementById('renewDate').value = expiredDate;
// Cek status driver untuk mengunci/membuka input SIMPER
toggleSimperInput('renew');
document.getElementById('renewForm').action = `/hse/employees/${id}`; function openRenewModal(empOrId, legacyName, legacyDate, legacyIsOp) {
let emp = null;
if (typeof empOrId === 'object' && empOrId !== null) {
emp = empOrId;
} else {
emp = {
id: empOrId,
name: legacyName || '',
nik: '',
unit_kerja: '',
division: '',
employee_type: 'Karyawan',
is_operator: legacyIsOp ? 1 : 0,
simper_expired_at: legacyDate || '',
simpers: []
};
}
currentRenewEmployee = emp;
// 1. Tampilkan Identitas Personel (Karyawan / Sukon)
document.getElementById('renewName').textContent = emp.name || '-';
document.getElementById('renewNik').textContent = emp.nik ? `NIK: ${emp.nik}` : 'Tanpa NIK';
const unitDeptText = [emp.unit_kerja, emp.division].filter(Boolean).join(' • ');
document.getElementById('renewUnitDept').textContent = unitDeptText ? `(${unitDeptText})` : '';
const catBadge = document.getElementById('renewCategoryBadge');
const empType = (emp.employee_type || 'Karyawan').trim();
const isSukon = empType.toLowerCase().includes('sukon');
catBadge.textContent = isSukon ? 'Sukon (Subkontraktor)' : 'Karyawan PT KMH';
catBadge.className = isSukon
? 'px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-amber-100 text-amber-800 border border-amber-200'
: 'px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-slate-200/80 text-slate-700';
document.getElementById('renewOperator').value = '1';
// 2. Baca Seluruh SIMPER yang Sedang Dimiliki Karyawan / Sukon
let simpers = Array.isArray(emp.simpers) ? [...emp.simpers] : [];
// Fallback jika belum tercatat di employee_simpers namun memiliki simper_expired_at di tabel utama
if (simpers.length === 0 && emp.simper_expired_at) {
const defaultMasterLv = allMasterSimperTypes.find(t => t.code === 'SIMPER-LV') || allMasterSimperTypes[0];
if (defaultMasterLv) {
simpers.push({
id: null,
employee_id: emp.id,
simper_type_id: defaultMasterLv.id,
simper_number: 'SMP-' + String(emp.id).padStart(4, '0'),
expired_at: emp.simper_expired_at,
status: 'active',
simper_type: defaultMasterLv
});
}
}
const simperCount = simpers.length;
const badgeEl = document.getElementById('renewSimperBadge');
const cardsContainer = document.getElementById('renewCurrentSimperCards');
cardsContainer.innerHTML = '';
const todayStr = new Date().toISOString().substring(0, 10);
const todayDate = new Date(todayStr);
if (simperCount > 0) {
badgeEl.textContent = `${simperCount} SIMPER Aktif`;
badgeEl.className = 'text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-emerald-50 text-emerald-800 border border-emerald-200 font-mono';
simpers.forEach(s => {
const st = s.simper_type || s.simperType || allMasterSimperTypes.find(t => t.id === s.simper_type_id) || {};
const typeName = st.name || `SIMPER ID #${s.simper_type_id}`;
const typeCode = st.code || '';
const expDateStr = s.expired_at ? s.expired_at.substring(0, 10) : '';
let statusLabel = 'Belum Diatur';
let statusClass = 'bg-slate-100 text-slate-600 border-slate-200';
let iconClass = 'fa-regular fa-clock';
if (expDateStr) {
const expDate = new Date(expDateStr);
const diffDays = Math.ceil((expDate - todayDate) / (1000 * 60 * 60 * 24));
if (diffDays < 0) {
statusLabel = `Kedaluwarsa (${Math.abs(diffDays)} hari lalu)`;
statusClass = 'bg-rose-50 text-rose-700 border-rose-200';
iconClass = 'fa-solid fa-circle-xmark text-rose-600';
} else if (diffDays <= 30) {
statusLabel = `Segera Habis (Sisa ${diffDays} hari)`;
statusClass = 'bg-amber-50 text-amber-700 border-amber-200';
iconClass = 'fa-solid fa-hourglass-half text-amber-600';
} else {
statusLabel = `Aktif (s/d ${expDateStr})`;
statusClass = 'bg-emerald-50 text-emerald-800 border border-emerald-200';
iconClass = 'fa-solid fa-circle-check text-emerald-600';
}
}
const card = document.createElement('div');
card.className = 'p-2.5 rounded-xl border bg-white shadow-2xs flex flex-col justify-between border-slate-200/80';
card.innerHTML = `
<div class="flex items-center justify-between">
<strong class="font-extrabold text-slate-800 text-xs">${typeName}</strong>
${typeCode ? `<span class="font-mono text-[9px] px-1.5 py-0.5 bg-slate-100 text-slate-600 rounded">${typeCode}</span>` : ''}
</div>
<div class="mt-1.5 flex items-center justify-between text-[11px]">
<span class="text-slate-400 font-mono text-[10px]">${s.simper_number || '-'}</span>
<span class="inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded ${statusClass}">
<i class="${iconClass} text-[9px]"></i>
<span>${statusLabel}</span>
</span>
</div>
`;
cardsContainer.appendChild(card);
});
} else {
badgeEl.textContent = 'Belum Ada SIMPER';
badgeEl.className = 'text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-slate-100 text-slate-500 border border-slate-200 font-mono';
const emptyNotice = document.createElement('div');
emptyNotice.className = 'col-span-full p-3 rounded-xl bg-slate-100/70 border border-slate-200 text-center text-xs text-slate-500 italic';
emptyNotice.innerHTML = '<i class="fa-solid fa-circle-info mr-1 text-slate-400"></i> Personel belum memiliki izin SIMPER terdaftar. Silakan pilih jenis SIMPER di bawah untuk menerbitkan perpanjangan.';
cardsContainer.appendChild(emptyNotice);
}
// 3. Bangun Dropdown Pilihan SIMPER
const select = document.getElementById('renewSimperTypeSelect');
select.innerHTML = '';
const ownedTypeIds = simpers.map(s => Number(s.simper_type_id)).filter(Boolean);
// Opsi A: Perpanjang Semua (jika punya lebih dari 1 SIMPER)
if (simperCount > 1) {
const allOpt = document.createElement('option');
allOpt.value = 'all';
allOpt.textContent = `★ Perpanjang Semua SIMPER Sekaligus (${simperCount} Izin Aktif)`;
allOpt.dataset.type = 'all';
select.appendChild(allOpt);
}
// Opsi B: Grup SIMPER yang Sedang Dimiliki
if (simperCount > 0) {
const ownedGroup = document.createElement('optgroup');
ownedGroup.label = '── SIMPER yang Sedang Dimiliki ──';
simpers.forEach(s => {
const st = s.simper_type || s.simperType || allMasterSimperTypes.find(t => t.id === s.simper_type_id) || {};
const typeName = st.name || `SIMPER #${s.simper_type_id}`;
const expDateStr = s.expired_at ? s.expired_at.substring(0, 10) : 'Belum diatur';
const opt = document.createElement('option');
opt.value = s.simper_type_id;
opt.dataset.type = 'owned';
opt.dataset.exp = s.expired_at ? s.expired_at.substring(0, 10) : '';
opt.dataset.name = typeName;
opt.dataset.code = st.code || '';
opt.textContent = `${typeName} (Masa berlaku saat ini: ${expDateStr})`;
ownedGroup.appendChild(opt);
});
select.appendChild(ownedGroup);
}
// Opsi C: Tambah / Perpanjang Jenis SIMPER Lain dari Master
const otherMasterTypes = allMasterSimperTypes.filter(t => !ownedTypeIds.includes(Number(t.id)));
if (otherMasterTypes.length > 0) {
const masterGroup = document.createElement('optgroup');
masterGroup.label = simperCount > 0 ? '── Tambah / Berikan Jenis SIMPER Lainnya ──' : '── Pilih Jenis SIMPER dari Master ──';
otherMasterTypes.forEach(mt => {
const opt = document.createElement('option');
opt.value = mt.id;
opt.dataset.type = 'new';
opt.dataset.exp = '';
opt.dataset.name = mt.name;
opt.dataset.code = mt.code || '';
opt.textContent = `+ ${mt.name} (${mt.code || 'Master SIMPER'})`;
masterGroup.appendChild(opt);
});
select.appendChild(masterGroup);
}
// 4. Sinkronisasi Informasi & Preset Tanggal Baru
onRenewSimperTypeChange(select.value);
document.getElementById('renewForm').action = `/hse/employees/${emp.id}`;
document.getElementById('renewModal').classList.remove('hidden'); document.getElementById('renewModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
}
function onRenewSimperTypeChange(val) {
const select = document.getElementById('renewSimperTypeSelect');
const selectedOpt = select.options[select.selectedIndex];
const dateInput = document.getElementById('renewDate');
const currentExpText = document.getElementById('renewCurrentExpText');
const statusBadge = document.getElementById('renewCurrentStatusBadge');
const recommendLabel = document.getElementById('renewRecommendLabel');
const optType = selectedOpt ? selectedOpt.dataset.type : '';
const currentExp = selectedOpt && selectedOpt.dataset.exp ? selectedOpt.dataset.exp : '';
const todayStr = new Date().toISOString().substring(0, 10);
const todayDate = new Date(todayStr);
let baseDateForRenewal = todayDate;
if (optType === 'all') {
currentExpText.textContent = 'Mencakup seluruh jenis SIMPER yang dimiliki';
statusBadge.textContent = 'Semua Izin';
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-indigo-50 text-indigo-700 border border-indigo-200';
// Cari tanggal maksimal dari simper yang dimiliki
if (currentRenewEmployee && Array.isArray(currentRenewEmployee.simpers) && currentRenewEmployee.simpers.length > 0) {
let maxExp = null;
currentRenewEmployee.simpers.forEach(s => {
if (s.expired_at) {
const d = s.expired_at.substring(0, 10);
if (!maxExp || d > maxExp) maxExp = d;
}
});
if (maxExp) {
const maxDateObj = new Date(maxExp);
if (!isNaN(maxDateObj) && maxDateObj > todayDate) {
baseDateForRenewal = maxDateObj;
}
}
}
} else if (optType === 'new') {
currentExpText.textContent = 'Belum aktif (Akan diterbitkan baru)';
statusBadge.textContent = 'Penerbitan Baru';
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-blue-50 text-blue-700 border border-blue-200';
baseDateForRenewal = todayDate;
} else if (currentExp) {
currentExpText.textContent = currentExp;
const expDateObj = new Date(currentExp);
const diffDays = Math.ceil((expDateObj - todayDate) / (1000 * 60 * 60 * 24));
if (diffDays < 0) {
statusBadge.textContent = `Kedaluwarsa (${Math.abs(diffDays)} hari lalu)`;
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-rose-50 text-rose-700 border border-rose-200';
baseDateForRenewal = todayDate;
} else if (diffDays <= 30) {
statusBadge.textContent = `Segera Habis (Sisa ${diffDays} hari)`;
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200';
baseDateForRenewal = expDateObj;
} else {
statusBadge.textContent = `Aktif (s/d ${currentExp})`;
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-emerald-50 text-emerald-800 border border-emerald-200';
baseDateForRenewal = expDateObj;
}
} else {
currentExpText.textContent = 'Belum pernah ditentukan';
statusBadge.textContent = 'Belum Diatur';
statusBadge.className = 'text-[10px] font-bold px-2 py-0.5 rounded bg-slate-100 text-slate-600 border border-slate-200';
baseDateForRenewal = todayDate;
}
// Hitung tanggal rekomendasi perpanjangan: +1 Tahun dari basis tanggal
const targetNewDate = new Date(baseDateForRenewal);
targetNewDate.setFullYear(targetNewDate.getFullYear() + 1);
dateInput.value = targetNewDate.toISOString().substring(0, 10);
recommendLabel.textContent = `Rekomendasi (+1 Tahun): ${dateInput.value}`;
}
function setRenewDateOffset(months) {
const select = document.getElementById('renewSimperTypeSelect');
const selectedOpt = select ? select.options[select.selectedIndex] : null;
const currentExp = selectedOpt && selectedOpt.dataset.exp ? selectedOpt.dataset.exp : '';
const todayDate = new Date();
let baseDate = todayDate;
if (currentExp) {
const expDateObj = new Date(currentExp);
if (!isNaN(expDateObj) && expDateObj > todayDate) {
baseDate = expDateObj;
}
}
const newDate = new Date(baseDate);
newDate.setMonth(newDate.getMonth() + months);
document.getElementById('renewDate').value = newDate.toISOString().substring(0, 10);
} }
function closeRenewModal() { function closeRenewModal() {
const modal = document.getElementById('renewModal'); const modal = document.getElementById('renewModal');
if (modal) modal.classList.add('hidden'); if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
currentRenewEmployee = null;
} }
function openDeleteEmployeeModal(id, name, nik) { function openDeleteEmployeeModal(id, name, nik) {
@@ -1349,12 +1720,20 @@
document.getElementById('deleteEmployeeNik').textContent = nik; document.getElementById('deleteEmployeeNik').textContent = nik;
document.getElementById('deleteEmployeeForm').action = `/hse/employees/${id}`; document.getElementById('deleteEmployeeForm').action = `/hse/employees/${id}`;
const modal = document.getElementById('deleteEmployeeModal'); const modal = document.getElementById('deleteEmployeeModal');
if (modal) modal.classList.remove('hidden'); if (modal) {
modal.classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
}
} }
function closeDeleteEmployeeModal() { function closeDeleteEmployeeModal() {
const modal = document.getElementById('deleteEmployeeModal'); const modal = document.getElementById('deleteEmployeeModal');
if (modal) modal.classList.add('hidden'); if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
} }
// Pencarian Server-side Otomatis (Global ke seluruh database) // Pencarian Server-side Otomatis (Global ke seluruh database)
@@ -1442,11 +1821,19 @@
}); });
const addSimperDateInp = document.getElementById('addSimperDateInput'); const addSimperDateInp = document.getElementById('addSimperDateInput');
if (addSimperDateInp) addSimperDateInp.value = ''; if (addSimperDateInp) addSimperDateInp.value = '';
if (modal) modal.classList.remove('hidden'); if (modal) {
modal.classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
}
} }
function closeAddKaryawanModal() { function closeAddKaryawanModal() {
const modal = document.getElementById('addKaryawanModal'); const modal = document.getElementById('addKaryawanModal');
if (modal) modal.classList.add('hidden'); if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
} }
function toggleAddSimperDate(val) { function toggleAddSimperDate(val) {
const wrapper = document.getElementById('addSimperDateWrapper'); const wrapper = document.getElementById('addSimperDateWrapper');
@@ -1472,11 +1859,19 @@
// Modal Impor Karyawan via Excel // Modal Impor Karyawan via Excel
function openImportKaryawanModal() { function openImportKaryawanModal() {
const modal = document.getElementById('importKaryawanModal'); const modal = document.getElementById('importKaryawanModal');
if (modal) modal.classList.remove('hidden'); if (modal) {
modal.classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
}
} }
function closeImportKaryawanModal() { function closeImportKaryawanModal() {
const modal = document.getElementById('importKaryawanModal'); const modal = document.getElementById('importKaryawanModal');
if (modal) modal.classList.add('hidden'); if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
} }
function handleImportFileChange(input) { function handleImportFileChange(input) {
const display = document.getElementById('importFileName'); const display = document.getElementById('importFileName');
+188 -28
View File
@@ -165,8 +165,13 @@
onclick="switchP2hSection('{{ $secKey }}')" onclick="switchP2hSection('{{ $secKey }}')"
id="p2h-tab-{{ $secKey }}" id="p2h-tab-{{ $secKey }}"
data-section-key="{{ $secKey }}" data-section-key="{{ $secKey }}"
class="p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 {{ $isFirst ? 'bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]' : 'bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300' }}"> data-section-index="{{ $loop->index }}"
class="p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 {{ $isFirst ? 'bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]' : 'bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300' }}">
<span class="step-num text-[10px] font-mono opacity-80">#{{ $loop->iteration }}</span>
<span>{{ $sectionName }}</span> <span>{{ $sectionName }}</span>
<span id="tab-check-{{ $secKey }}" class="tab-check-icon hidden text-emerald-400 font-black">
<i class="fa-solid fa-circle-check text-[11px]"></i>
</span>
</button> </button>
@endforeach @endforeach
</div> </div>
@@ -213,13 +218,13 @@
</div> </div>
@if(in_array($item->question_type, ['choice', 'condition', 'Multiple choice: only one answer', 'Matrix'])) @if(in_array($item->question_type, ['choice', 'condition', 'Multiple choice: only one answer', 'Matrix']))
<!-- Opsi Jawaban Radio: Baik & Rusak --> <!-- Opsi Jawaban Radio: Baik & Rusak (Kosongan secara Default, Wajib Dipilih Operator) -->
<div class="flex items-center space-x-2 flex-shrink-0"> <div class="flex items-center space-x-2 flex-shrink-0">
<label class="cursor-pointer"> <label class="cursor-pointer">
<input type="radio" <input type="radio"
name="items[{{ $item->id }}][condition]" name="items[{{ $item->id }}][condition]"
value="baik" value="baik"
checked {{ old("items.{$item->id}.condition") === 'baik' ? 'checked' : '' }}
onchange="handleConditionChange({{ $item->id }}, 'baik')" onchange="handleConditionChange({{ $item->id }}, 'baik')"
class="peer sr-only"> class="peer sr-only">
<span class="inline-flex items-center justify-center min-w-[62px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-[#1b5e20] peer-checked:text-white peer-checked:border-[#1b5e20] peer-checked:shadow-sm transition"> <span class="inline-flex items-center justify-center min-w-[62px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-[#1b5e20] peer-checked:text-white peer-checked:border-[#1b5e20] peer-checked:shadow-sm transition">
@@ -231,6 +236,7 @@
<input type="radio" <input type="radio"
name="items[{{ $item->id }}][condition]" name="items[{{ $item->id }}][condition]"
value="rusak" value="rusak"
{{ old("items.{$item->id}.condition") === 'rusak' ? 'checked' : '' }}
onchange="handleConditionChange({{ $item->id }}, 'rusak')" onchange="handleConditionChange({{ $item->id }}, 'rusak')"
class="peer sr-only"> class="peer sr-only">
<span class="inline-flex items-center justify-center space-x-1.5 min-w-[68px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-rose-600 peer-checked:text-white peer-checked:border-rose-600 peer-checked:shadow-sm transition"> <span class="inline-flex items-center justify-center space-x-1.5 min-w-[68px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-rose-600 peer-checked:text-white peer-checked:border-rose-600 peer-checked:shadow-sm transition">
@@ -289,15 +295,15 @@
@endforeach @endforeach
</div> </div>
<!-- Navigasi Cepat Antar Section (Sebelumnya & Selanjutnya) --> <!-- Navigasi Wizard Bertahap Antar Section -->
@if(count($groupedItems) > 1) @if(count($groupedItems) > 1)
<div class="px-4 py-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between"> <div class="px-4 py-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between">
@if($prevKey) @if($prevKey)
<button type="button" <button type="button"
onclick="switchP2hSection('{{ $prevKey }}')" onclick="switchP2hSection('{{ $prevKey }}')"
class="inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-100 transition shadow-2xs cursor-pointer"> class="inline-flex items-center space-x-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-100 transition shadow-2xs cursor-pointer">
<i class="fa-solid fa-chevron-left text-[10px]"></i> <i class="fa-solid fa-chevron-left text-[10px]"></i>
<span>Bagian Sebelumnya</span> <span>Kembali</span>
</button> </button>
@else @else
<div></div> <div></div>
@@ -305,15 +311,18 @@
@if($nextKey) @if($nextKey)
<button type="button" <button type="button"
onclick="switchP2hSection('{{ $nextKey }}')" onclick="completeAndNextSection('{{ $secKey }}', '{{ $nextKey }}')"
class="inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-bold text-emerald-800 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition shadow-2xs cursor-pointer"> class="inline-flex items-center space-x-1.5 px-4 py-2 rounded-xl text-xs font-bold text-white bg-[#1b5e20] hover:bg-[#144918] transition shadow-xs cursor-pointer">
<span>Bagian Selanjutnya</span> <span>Selesaikan Bagian Ini & Lanjut</span>
<i class="fa-solid fa-chevron-right text-[10px]"></i> <i class="fa-solid fa-chevron-right text-[10px]"></i>
</button> </button>
@else @else
<span class="text-[11px] font-semibold text-slate-400 flex items-center"> <button type="button"
<i class="fa-solid fa-flag-checkered mr-1.5 text-emerald-600"></i> Bagian Terakhir onclick="markLastSectionComplete('{{ $secKey }}')"
</span> class="inline-flex items-center space-x-1.5 px-4 py-2 rounded-xl text-xs font-bold text-emerald-800 bg-emerald-100 hover:bg-emerald-200 border border-emerald-300 transition shadow-xs cursor-pointer">
<i class="fa-solid fa-circle-check text-xs"></i>
<span>Selesaikan Pemeriksaan Bagian Terakhir</span>
</button>
@endif @endif
</div> </div>
@endif @endif
@@ -324,24 +333,36 @@
<!-- Card Catatan Umum Operator --> <!-- Card Catatan Umum Operator -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 space-y-3"> <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 space-y-3">
<label for="general_notes" class="block text-xs font-bold uppercase tracking-wider text-slate-700"> <label for="general_notes" class="flex items-center justify-between text-xs font-bold uppercase tracking-wider text-slate-700">
Catatan Umum / Keterangan Tambahan Operator <span>Catatan Umum / Keterangan Tambahan Operator</span>
<span class="text-[10px] font-medium text-slate-400 normal-case italic">(opsional / boleh dikosongkan)</span>
</label> </label>
<textarea name="general_notes" id="general_notes" rows="3" placeholder="Tuliskan temuan atau catatan umum lainnya mengenai kondisi Heavy Equipment hari ini..." class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-xs text-slate-800 focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition resize-none">{{ old('general_notes') }}</textarea> <textarea name="general_notes" id="general_notes" rows="3" placeholder="Tuliskan temuan atau catatan umum lainnya mengenai kondisi Heavy Equipment hari ini..." class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-xs text-slate-800 focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition resize-none">{{ old('general_notes') }}</textarea>
</div> </div>
<!-- Tombol Aksi Submit --> <!-- Card Tombol Aksi Submit P2H (Aktif Setelah Seluruh Bagian Ditinjau) -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 flex items-center justify-between gap-3"> <div id="p2hSubmitCard" class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 transition-all">
<a href="{{ route('p2h.index') }}" class="bg-slate-100 hover:bg-slate-200 text-slate-600 font-semibold py-2.5 px-4 rounded-xl transition text-xs"> <div id="p2hPendingNotice" class="{{ count($groupedItems) > 1 ? '' : 'hidden' }} flex items-center justify-between text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded-xl p-3 mb-3">
Batal <div class="flex items-center gap-2">
</a> <i class="fa-solid fa-circle-info text-amber-600 text-sm"></i>
<span>Harap selesaikan pemeriksaan pada seluruh bagian (section) di atas untuk memunculkan tombol pengiriman formulir P2H ke QMA.</span>
</div>
</div>
<button type="submit" <div class="flex items-center justify-between gap-3">
id="btnSubmitP2h" <a href="{{ route('p2h.index') }}" class="bg-slate-100 hover:bg-slate-200 text-slate-600 font-semibold py-2.5 px-4 rounded-xl transition text-xs">
class="bg-[#1b5e20] hover:bg-[#144918] active:scale-[0.99] text-white font-bold py-2.5 px-6 rounded-xl shadow-sm hover:shadow transition flex items-center space-x-2 text-xs sm:text-sm cursor-pointer"> Batal
<i class="fa-solid fa-paper-plane text-xs"></i> </a>
<span>Kirim Formulir P2H ke QMA</span>
</button> <div id="p2hSubmitBtnContainer" class="{{ count($groupedItems) > 1 ? 'hidden' : '' }}">
<button type="submit"
id="btnSubmitP2h"
class="bg-[#1b5e20] hover:bg-[#144918] active:scale-[0.99] text-white font-bold py-2.5 px-6 rounded-xl shadow-sm hover:shadow transition flex items-center space-x-2 text-xs sm:text-sm cursor-pointer">
<i class="fa-solid fa-paper-plane text-xs"></i>
<span>Kirim Formulir P2H ke QMA</span>
</button>
</div>
</div>
</div> </div>
</form> </form>
</div> </div>
@@ -349,20 +370,26 @@
@section('scripts') @section('scripts')
<script> <script>
const allSectionKeys = @json($sectionKeys);
const completedSections = {};
function switchP2hSection(secKey) { function switchP2hSection(secKey) {
// 1. Update tab styling // 1. Update tab styling
const allTabs = document.querySelectorAll('.p2h-section-tab'); const allTabs = document.querySelectorAll('.p2h-section-tab');
allTabs.forEach(tab => { allTabs.forEach(tab => {
const key = tab.dataset.sectionKey; const key = tab.dataset.sectionKey;
const isCompleted = !!completedSections[key];
if (key === secKey) { if (key === secKey) {
tab.className = 'p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]'; tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]';
tab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' }); tab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
} else if (isCompleted) {
tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-emerald-50 border border-emerald-200 text-emerald-800 hover:bg-emerald-100';
} else { } else {
tab.className = 'p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300'; tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300';
} }
}); });
// 2. Show active panel, hide others // 2. Tampilkan panel aktif, sembunyikan lainnya
const allPanels = document.querySelectorAll('.p2h-section-content'); const allPanels = document.querySelectorAll('.p2h-section-content');
allPanels.forEach(panel => { allPanels.forEach(panel => {
if (panel.id === 'p2h-content-' + secKey) { if (panel.id === 'p2h-content-' + secKey) {
@@ -371,6 +398,102 @@
panel.classList.add('hidden'); panel.classList.add('hidden');
} }
}); });
checkAllSectionsCompleted();
}
function validateSectionNotes(secKey) {
const panel = document.getElementById('p2h-content-' + secKey);
if (!panel) return true;
// 1. Validasi: Pastikan setiap butir pemeriksaan radio di bagian ini telah dipilih (Baik / Rusak)
const radioRows = panel.querySelectorAll('.p2h-item-card');
for (const row of radioRows) {
const radios = row.querySelectorAll('input[type="radio"]');
if (radios.length > 0) {
const isSelected = Array.from(radios).some(r => r.checked);
if (!isSelected) {
row.scrollIntoView({ behavior: 'smooth', block: 'center' });
row.classList.add('ring-2', 'ring-rose-500', 'bg-rose-50/50');
setTimeout(() => {
row.classList.remove('ring-2', 'ring-rose-500', 'bg-rose-50/50');
}, 3500);
alert('Harap periksa dan tentukan kondisi (Baik atau Rusak) untuk seluruh butir pemeriksaan pada bagian ini.');
return false;
}
}
}
// 2. Validasi: Jika ada yang rusak, wajib diisi catatan penjelasannya
const damagedRadios = panel.querySelectorAll('input[type="radio"][value="rusak"]:checked');
for (const radio of damagedRadios) {
const match = radio.name.match(/items\[(\d+)\]/);
if (match && match[1]) {
const notesInput = panel.querySelector(`input[name="items[${match[1]}][notes]"]`);
if (notesInput && !notesInput.value.trim()) {
notesInput.focus();
alert('Mohon isi catatan kerusakan pada butir yang Anda tandai "Rusak" sebelum melanjutkan.');
return false;
}
}
}
return true;
}
function completeAndNextSection(currentKey, nextKey) {
if (!validateSectionNotes(currentKey)) {
return;
}
completedSections[currentKey] = true;
const checkIcon = document.getElementById('tab-check-' + currentKey);
if (checkIcon) checkIcon.classList.remove('hidden');
switchP2hSection(nextKey);
}
function markLastSectionComplete(lastSecKey) {
if (!validateSectionNotes(lastSecKey)) {
return;
}
completedSections[lastSecKey] = true;
const checkIcon = document.getElementById('tab-check-' + lastSecKey);
if (checkIcon) checkIcon.classList.remove('hidden');
checkAllSectionsCompleted();
// Gulir halus ke tombol kirim di bawah
const submitCard = document.getElementById('p2hSubmitCard');
if (submitCard) {
submitCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
function checkAllSectionsCompleted() {
if (!allSectionKeys || allSectionKeys.length <= 1) {
showSubmitButton();
return;
}
let allDone = true;
for (const key of allSectionKeys) {
if (!completedSections[key]) {
allDone = false;
break;
}
}
if (allDone) {
showSubmitButton();
}
}
function showSubmitButton() {
const container = document.getElementById('p2hSubmitBtnContainer');
const notice = document.getElementById('p2hPendingNotice');
if (container) container.classList.remove('hidden');
if (notice) notice.classList.add('hidden');
} }
function handleConditionChange(itemId, condition) { function handleConditionChange(itemId, condition) {
@@ -396,5 +519,42 @@
} }
}); });
} }
// Inisialisasi awal & proteksi submit form
document.addEventListener('DOMContentLoaded', function() {
if (!allSectionKeys || allSectionKeys.length <= 1) {
showSubmitButton();
}
const form = document.getElementById('p2hForm');
if (form) {
form.addEventListener('submit', function(e) {
const unselectedCards = [];
document.querySelectorAll('.p2h-item-card').forEach(row => {
const radios = row.querySelectorAll('input[type="radio"]');
if (radios.length > 0 && !Array.from(radios).some(r => r.checked)) {
unselectedCards.push(row);
}
});
if (unselectedCards.length > 0) {
e.preventDefault();
const firstUnselected = unselectedCards[0];
const panel = firstUnselected.closest('.p2h-section-content');
if (panel) {
const secKey = panel.id.replace('p2h-content-', '');
switchP2hSection(secKey);
}
firstUnselected.scrollIntoView({ behavior: 'smooth', block: 'center' });
firstUnselected.classList.add('ring-2', 'ring-rose-500', 'bg-rose-50/50');
setTimeout(() => {
firstUnselected.classList.remove('ring-2', 'ring-rose-500', 'bg-rose-50/50');
}, 3500);
alert(`Terdapat ${unselectedCards.length} butir pemeriksaan yang belum dipilih. Harap tentukan kondisi (Baik / Rusak) untuk seluruh butir sebelum mengirim formulir.`);
return false;
}
});
}
});
</script> </script>
@endsection @endsection
@@ -471,6 +471,38 @@
openGateSelectionModal(true); openGateSelectionModal(true);
}); });
@endif @endif
// Modal Tolak Perjalanan Kendaraan di Pos Gerbang
function openRejectModal(id, unit, driver, direction) {
document.getElementById('rejectUnitDisplay').textContent = unit || '-';
document.getElementById('rejectDriverDisplay').textContent = driver || '-';
const dirEl = document.getElementById('rejectDirectionDisplay');
if (direction === 'in') {
dirEl.textContent = 'Masuk Gerbang (IN)';
dirEl.className = 'font-bold text-xs uppercase px-2 py-0.5 rounded-md bg-blue-100 text-blue-800';
} else {
dirEl.textContent = 'Keluar Gerbang (OUT)';
dirEl.className = 'font-bold text-xs uppercase px-2 py-0.5 rounded-md bg-amber-100 text-amber-800';
}
document.getElementById('rejectNoteInput').value = '';
document.getElementById('rejectForm').action = `/pg/gate-inspection/${id}/reject`;
const modal = document.getElementById('rejectModal');
if (modal) modal.classList.remove('hidden');
}
function closeRejectModal() {
const modal = document.getElementById('rejectModal');
if (modal) modal.classList.add('hidden');
}
function setQuickReason(text) {
const input = document.getElementById('rejectNoteInput');
if (input) {
input.value = text;
input.focus();
}
}
</script> </script>
<!-- MODAL LIGHTBOX PRATINJAU FOTO DRIVER & MOBIL LV --> <!-- MODAL LIGHTBOX PRATINJAU FOTO DRIVER & MOBIL LV -->
@@ -581,4 +613,111 @@
</div> </div>
</div> </div>
</div> </div>
<!-- ========================================================================= -->
<!-- MODAL POPUP: TOLAK PERJALANAN KENDARAAN (DENGAN DETAIL ALASAN) -->
<!-- ========================================================================= -->
<div id="rejectModal" data-backdrop="static" class="hidden fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
<div class="bg-white rounded-3xl shadow-2xl max-w-lg w-full p-6 sm:p-7 border border-slate-100 overflow-hidden animate-scale-in space-y-4">
<!-- Header Modal -->
<div class="flex items-start justify-between gap-3 pb-3 border-b border-slate-100">
<div class="flex items-center space-x-3">
<div class="w-12 h-12 rounded-2xl bg-rose-100 text-rose-700 flex items-center justify-center text-xl flex-shrink-0 shadow-2xs">
<i class="fa-solid fa-ban"></i>
</div>
<div>
<h3 class="text-base sm:text-lg font-black text-slate-900 tracking-tight">
Tolak Perjalanan Kendaraan
</h3>
<p class="text-xs text-slate-500 mt-0.5">
Berikan alasan penolakan secara jelas untuk catatan log audit & driver.
</p>
</div>
</div>
<button type="button" onclick="closeRejectModal()" class="text-slate-400 hover:text-slate-600 p-1.5 rounded-lg hover:bg-slate-100 transition cursor-pointer">
<i class="fa-solid fa-xmark text-sm"></i>
</button>
</div>
<!-- Identitas Kendaraan & Driver -->
<div class="bg-slate-50 p-3.5 rounded-2xl border border-slate-200/80 space-y-1.5">
<div class="flex items-center justify-between text-xs">
<span class="text-slate-500 font-bold">Kendaraan:</span>
<span id="rejectUnitDisplay" class="font-mono font-black text-slate-900"></span>
</div>
<div class="flex items-center justify-between text-xs">
<span class="text-slate-500 font-bold">Pengemudi:</span>
<span id="rejectDriverDisplay" class="font-bold text-slate-900"></span>
</div>
<div class="flex items-center justify-between text-xs">
<span class="text-slate-500 font-bold">Arah Perlintasan:</span>
<span id="rejectDirectionDisplay" class="font-bold text-xs uppercase px-2 py-0.5 rounded-md"></span>
</div>
</div>
<!-- Form Penolakan -->
<form id="rejectForm" method="POST" action="" class="space-y-4">
@csrf
@if($currentGuard)
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}">
@elseif($guards->isNotEmpty())
<div>
<label class="block text-xs font-bold text-slate-700 mb-1">
Petugas Satpam Pemeriksa <span class="text-rose-500">*</span>
</label>
<select name="security_guard_id" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-rose-600">
@foreach($guards as $g)
<option value="{{ $g->id }}">{{ $g->name }} (Reg: {{ $g->badge_id }})</option>
@endforeach
</select>
</div>
@endif
<!-- Quick Reason Chips -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Pilih Cepat Alasan Penolakan:
</label>
<div class="flex flex-wrap gap-1.5">
<button type="button" onclick="setQuickReason('Masa berlaku SIMPER pengemudi telah kedaluwarsa (Expired)')" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-rose-50 hover:border-rose-300 hover:text-rose-700 transition font-medium cursor-pointer">
SIMPER Expired
</button>
<button type="button" onclick="setQuickReason('Kondisi fisik kendaraan tidak layak jalan (Rem blong / Lampu mati / Ban botak)')" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-rose-50 hover:border-rose-300 hover:text-rose-700 transition font-medium cursor-pointer">
Fisik Tidak Layak
</button>
<button type="button" onclick="setQuickReason('Tujuan atau keperluan perjalanan tidak jelas / Tanpa instruksi kerja')" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-rose-50 hover:border-rose-300 hover:text-rose-700 transition font-medium cursor-pointer">
Tujuan Tidak Jelas
</button>
<button type="button" onclick="setQuickReason('Surat jalan / BAST belum lengkap')" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-rose-50 hover:border-rose-300 hover:text-rose-700 transition font-medium cursor-pointer">
Surat Jalan Kurang
</button>
<button type="button" onclick="setQuickReason('Pengemudi bukan operator / driver yang terdaftar untuk unit ini')" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-rose-50 hover:border-rose-300 hover:text-rose-700 transition font-medium cursor-pointer">
Bukan Driver Resmi
</button>
</div>
</div>
<!-- Detail Alasan Wajib -->
<div>
<label for="rejectNoteInput" class="block text-xs font-bold text-slate-700 mb-1.5">
Detail Catatan / Alasan Penolakan <span class="text-rose-500">*</span>
</label>
<textarea name="rejection_note" id="rejectNoteInput" rows="3" required
placeholder="Jelaskan alasan penolakan secara spesifik..."
class="w-full text-xs p-3 rounded-xl border border-slate-300 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-rose-600 focus:ring-2 focus:ring-rose-500/10 transition resize-none"></textarea>
</div>
<div class="pt-3 border-t border-slate-100 flex items-center justify-end gap-2.5">
<button type="button" onclick="closeRejectModal()" class="px-4 py-2 text-xs font-bold text-slate-600 hover:bg-slate-100 rounded-xl transition cursor-pointer">
Batal
</button>
<button type="submit"
onclick="if(!document.getElementById('rejectNoteInput').value.trim()){ alert('Alasan penolakan wajib diisi!'); return false; }"
class="px-5 py-2.5 bg-rose-600 hover:bg-rose-700 active:bg-rose-800 text-white font-bold text-xs rounded-xl shadow-xs transition flex items-center space-x-1.5 cursor-pointer">
<i class="fa-solid fa-ban text-xs"></i>
<span>Konfirmasi Tolak Perjalanan</span>
</button>
</div>
</form>
</div>
</div>
@endsection @endsection
@@ -113,32 +113,41 @@
</div> </div>
@endif @endif
<!-- Baris 4: Tombol Verifikasi Langsung di Card (Tanpa Popup & Tanpa Fitur Tolak) --> <!-- Baris 4: Tombol Aksi Verifikasi & Tolak Perjalanan -->
<div class="mt-3.5 pt-3 border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-2.5"> <div class="mt-3.5 pt-3 border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-2.5">
<span class="text-[11px] text-slate-400 font-medium hidden sm:inline flex items-center gap-1.5"> <span class="text-[11px] text-slate-400 font-medium hidden sm:inline flex items-center gap-1.5">
<i class="fa-solid fa-shield-check text-[#1b5e20]"></i> <i class="fa-solid fa-shield-check text-[#1b5e20]"></i>
<span>Cek fisik kendaraan lalu klik verifikasi untuk membuka portal</span> <span>Cek fisik kendaraan lalu pilih verifikasi atau tolak</span>
</span> </span>
@can('gate.approve') <div class="flex items-center gap-2 w-full sm:w-auto">
<form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-full sm:w-auto m-0"> @can('gate.reject')
@csrf <button type="button"
@if($currentGuard) onclick="openRejectModal({{ $act->id }}, '{{ addslashes($act->vehicle->code . ' (' . ($act->vehicle->license_plate ?? 'Tanpa Plat') . ')') }}', '{{ addslashes($act->driver->name ?? 'Pengemudi') }}', '{{ strtolower($act->direction) }}')"
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}"> class="w-1/2 sm:w-auto px-4 py-2.5 bg-rose-50 hover:bg-rose-100 active:bg-rose-200 text-rose-700 border border-rose-200 font-bold text-xs sm:text-sm rounded-xl transition flex items-center justify-center space-x-1.5 cursor-pointer shadow-2xs">
@elseif($guards->isNotEmpty()) <i class="fa-solid fa-ban text-xs"></i>
<input type="hidden" name="security_guard_id" value="{{ $guards->first()->id }}"> <span>Tolak</span>
@endif
<button type="submit"
onclick="this.disabled=true; this.innerHTML='<i class=\'fa-solid fa-spinner fa-spin text-xs\'></i> Memverifikasi...'; this.form.submit();"
class="w-full sm:w-auto px-6 py-2.5 bg-[#1b5e20] hover:bg-[#144919] active:bg-[#0f3613] text-white font-bold text-xs sm:text-sm rounded-xl shadow-xs hover:shadow transition flex items-center justify-center space-x-2 cursor-pointer">
<i class="fa-solid fa-clipboard-check text-sm"></i>
<span>Verifikasi</span>
</button> </button>
</form> @endcan
@else
<span class="text-xs text-slate-400 italic">Tidak memiliki izin verifikasi</span> @can('gate.approve')
@endcan <form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-1/2 sm:w-auto m-0">
@csrf
@if($currentGuard)
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}">
@elseif($guards->isNotEmpty())
<input type="hidden" name="security_guard_id" value="{{ $guards->first()->id }}">
@endif
<button type="submit"
onclick="this.disabled=true; this.innerHTML='<i class=\'fa-solid fa-spinner fa-spin text-xs\'></i> Memverifikasi...'; this.form.submit();"
class="w-full sm:w-auto px-6 py-2.5 bg-[#1b5e20] hover:bg-[#144919] active:bg-[#0f3613] text-white font-bold text-xs sm:text-sm rounded-xl shadow-xs hover:shadow transition flex items-center justify-center space-x-2 cursor-pointer">
<i class="fa-solid fa-clipboard-check text-sm"></i>
<span>Verifikasi</span>
</button>
</form>
@endcan
</div>
</div> </div>
</div> </div>
+194 -166
View File
@@ -301,11 +301,23 @@
</div> </div>
</td> </td>
<!-- Odometer Awal --> <!-- Odometer Awal & Akhir -->
<td class="py-3.5 px-4 text-center font-mono whitespace-nowrap"> <td class="py-3.5 px-4 text-center font-mono whitespace-nowrap">
<span class="text-xs font-bold text-slate-900 bg-slate-100 px-2.5 py-1 rounded-lg border border-slate-200"> <div class="text-xs font-bold text-slate-900 bg-slate-100 px-2.5 py-1 rounded-lg border border-slate-200 inline-block">
{{ number_format($ts->start_meter, 1, ',', '.') }} {{ $ts->meter_type }} {{ number_format($ts->start_meter, 1, ',', '.') }} {{ $ts->meter_type }}@if($ts->effective_end_meter) <span class="text-slate-400 font-normal">s/d</span> <span class="text-emerald-700">{{ number_format($ts->effective_end_meter, 1, ',', '.') }} {{ $ts->meter_type }}</span>@endif
</span> </div>
@if($ts->effective_operating_hours !== null && $ts->effective_operating_hours > 0)
<div class="text-[10px] text-emerald-700 font-semibold font-sans mt-0.5">
+{{ number_format($ts->effective_operating_hours, 1, ',', '.') }} Jam Operasi
</div>
@elseif($ts->effective_end_meter)
<div class="text-[10px] text-slate-400 font-sans mt-0.5">0.0 Jam</div>
@else
<div class="text-[10px] text-amber-600 font-sans mt-0.5 flex items-center justify-center gap-1">
<span class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
<span>Berjalan (Finish Otomatis)</span>
</div>
@endif
</td> </td>
<!-- Lokasi & Aktivitas --> <!-- Lokasi & Aktivitas -->
@@ -361,9 +373,9 @@
'operator_type' => $ts->operator?->employee_type ?: 'Karyawan', 'operator_type' => $ts->operator?->employee_type ?: 'Karyawan',
'operator_nik' => $ts->operator?->nik ?: '-', 'operator_nik' => $ts->operator?->nik ?: '-',
'start_meter' => number_format($ts->start_meter, 1, ',', '.'), 'start_meter' => number_format($ts->start_meter, 1, ',', '.'),
'end_meter' => number_format($ts->end_meter, 1, ',', '.'), 'end_meter' => $ts->effective_end_meter !== null ? number_format($ts->effective_end_meter, 1, ',', '.') : '-',
'meter_type' => $ts->meter_type, 'meter_type' => $ts->meter_type,
'operating_hours' => number_format($ts->operating_hours, 1, ',', '.'), 'operating_hours' => $ts->effective_operating_hours !== null ? number_format($ts->effective_operating_hours, 1, ',', '.') : '-',
'standby_hours' => number_format($ts->standby_hours, 1, ',', '.'), 'standby_hours' => number_format($ts->standby_hours, 1, ',', '.'),
'breakdown_hours' => number_format($ts->breakdown_hours, 1, ',', '.'), 'breakdown_hours' => number_format($ts->breakdown_hours, 1, ',', '.'),
'fuel_liters' => $ts->fuel_liters ? number_format($ts->fuel_liters, 0, ',', '.') : '-', 'fuel_liters' => $ts->fuel_liters ? number_format($ts->fuel_liters, 0, ',', '.') : '-',
@@ -479,37 +491,37 @@
<!-- Baris 1: Lokasi Kerja & Heavy Equipment --> <!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
Lokasi Kerja <span class="text-rose-500">*</span> <span>Lokasi Kerja <span class="text-rose-500">*</span></span>
<span class="sr-only">Tentukan Lokasi Dulu</span> <span class="sr-only">Tentukan Lokasi Dulu</span>
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
</label> </label>
<select id="addLocationSelect" <div class="relative">
required
onchange="onTimesheetLocationChanged(this.value, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@if(isset($otherLocations) && count($otherLocations))
<optgroup label="Lokasi Lainnya di Site">
@foreach($otherLocations as $otherLoc)
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
@endforeach
</optgroup>
@endif
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
</select>
<div id="addCustomLocationWrapper" class="hidden mt-2">
<input type="text" <input type="text"
id="addCustomLocationInput" id="addLocationInput"
name="custom_location" name="location"
placeholder="Ketik nama lokasi kerja baru..." list="addLocationsDatalist"
oninput="onCustomLocationTyped(this.value, 'add')" required
class="w-full text-xs px-3.5 py-2 rounded-xl border border-emerald-300 bg-emerald-50/40 text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20]"> autocomplete="off"
placeholder="Pilih atau ketik lokasi kerja..."
oninput="onTimesheetLocationTyped(this.value, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<datalist id="addLocationsDatalist">
<option value="[Semua Unit]">[Semua Lokasi / Tampilkan Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@foreach($locationSuggestions as $suggLoc)
@if(!isset($unitLocations[$suggLoc]))
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
@endif
@endforeach
</datalist>
</div> </div>
<input type="hidden" name="location" id="addFinalLocation" required> <input type="hidden" id="addFinalLocation" value="">
<p class="text-[10px] text-slate-400 mt-1">
Pilih dari daftar atau ketik lokasi baru (otomatis tersimpan ke database).
</p>
</div> </div>
<div> <div>
@@ -626,7 +638,7 @@
</div> </div>
</div> </div>
<!-- Baris 4: Meter Awal & Satuan Meteran --> <!-- Baris 4: Meter Awal & Meter Akhir (Finish HM) -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5">
@@ -644,6 +656,28 @@
</div> </div>
</div> </div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Meter Akhir (Finish HM/KM)</span>
<span class="text-[10px] text-emerald-700 font-semibold">Otomatis / Opsional</span>
</label>
<div class="relative">
<input type="number"
step="0.01"
name="end_meter"
id="addEndMeter"
placeholder="Dihitung otomatis jika kosong"
class="w-full text-xs pl-3.5 pr-14 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<span id="addEndMeterUnitLabel" class="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs font-extrabold text-slate-400">HM</span>
</div>
<p class="text-[10px] text-slate-400 mt-1">
<i class="fa-solid fa-clock text-emerald-600 mr-0.5"></i> 1 HM = 1 Jam. Dihitung otomatis saat entri berikutnya diinput.
</p>
</div>
</div>
<!-- Baris 4b: Satuan Meteran & Status Akhir Unit -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5">
Satuan Meteran <span class="text-rose-500">*</span> Satuan Meteran <span class="text-rose-500">*</span>
@@ -653,21 +687,21 @@
<option value="KM">KM (Odometer)</option> <option value="KM">KM (Odometer)</option>
</select> </select>
</div> </div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
</div> </div>
<!-- Baris 5: Status Akhir Unit (Shift diset otomatis) -->
<input type="hidden" name="shift" value="Shift Siang"> <input type="hidden" name="shift" value="Shift Siang">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
<!-- Baris 6: Rincian Tugas & Catatan --> <!-- Baris 6: Rincian Tugas & Catatan -->
<div> <div>
@@ -811,37 +845,37 @@
<!-- Baris 1: Lokasi Kerja & Heavy Equipment --> <!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
Lokasi Kerja <span class="text-rose-500">*</span> <span>Lokasi Kerja <span class="text-rose-500">*</span></span>
<span class="sr-only">Tentukan Lokasi Dulu</span> <span class="sr-only">Tentukan Lokasi Dulu</span>
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
</label> </label>
<select id="editLocationSelect" <div class="relative">
required
onchange="onTimesheetLocationChanged(this.value, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@if(isset($otherLocations) && count($otherLocations))
<optgroup label="Lokasi Lainnya di Site">
@foreach($otherLocations as $otherLoc)
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
@endforeach
</optgroup>
@endif
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
</select>
<div id="editCustomLocationWrapper" class="hidden mt-2">
<input type="text" <input type="text"
id="editCustomLocationInput" id="editLocationInput"
name="custom_location" name="location"
placeholder="Ketik nama lokasi kerja baru..." list="editLocationsDatalist"
oninput="onCustomLocationTyped(this.value, 'edit')" required
class="w-full text-xs px-3.5 py-2 rounded-xl border border-emerald-300 bg-emerald-50/40 text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20]"> autocomplete="off"
placeholder="Pilih atau ketik lokasi kerja..."
oninput="onTimesheetLocationTyped(this.value, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<datalist id="editLocationsDatalist">
<option value="[Semua Unit]">[Semua Lokasi / Tampilkan Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@foreach($locationSuggestions as $suggLoc)
@if(!isset($unitLocations[$suggLoc]))
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
@endif
@endforeach
</datalist>
</div> </div>
<input type="hidden" name="location" id="editFinalLocation" required> <input type="hidden" id="editFinalLocation" value="">
<p class="text-[10px] text-slate-400 mt-1">
Pilih dari daftar atau ketik lokasi baru (otomatis tersimpan).
</p>
</div> </div>
<div> <div>
@@ -956,7 +990,7 @@
</div> </div>
</div> </div>
<!-- Baris 4: Meter Awal & Satuan Meteran --> <!-- Baris 4: Meter Awal & Meter Akhir (Finish HM) -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5">
@@ -974,6 +1008,28 @@
</div> </div>
</div> </div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Meter Akhir (Finish HM/KM)</span>
<span class="text-[10px] text-emerald-700 font-semibold">Otomatis / Opsional</span>
</label>
<div class="relative">
<input type="number"
step="0.01"
name="end_meter"
id="editEndMeter"
placeholder="Dihitung otomatis jika kosong"
class="w-full text-xs pl-3.5 pr-14 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<span id="editEndMeterUnitLabel" class="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs font-extrabold text-slate-400">HM</span>
</div>
<p class="text-[10px] text-slate-400 mt-1">
<i class="fa-solid fa-clock text-emerald-600 mr-0.5"></i> 1 HM = 1 Jam. Dihitung otomatis saat entri berikutnya diinput.
</p>
</div>
</div>
<!-- Baris 4b: Satuan Meteran & Status Akhir Unit -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-1.5"> <label class="block text-xs font-bold text-slate-700 mb-1.5">
Satuan Meteran <span class="text-rose-500">*</span> Satuan Meteran <span class="text-rose-500">*</span>
@@ -983,21 +1039,22 @@
<option value="KM">KM (Odometer)</option> <option value="KM">KM (Odometer)</option>
</select> </select>
</div> </div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" id="editStatus" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
</div> </div>
<!-- Baris 5: Status Akhir Unit (Shift disimpan secara otomatis) --> <!-- Baris 5: Shift (disimpan otomatis) -->
<input type="hidden" name="shift" id="editShift" value="Shift Siang"> <input type="hidden" name="shift" id="editShift" value="Shift Siang">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" id="editStatus" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
<!-- Baris 6: Deskripsi & Catatan --> <!-- Baris 6: Deskripsi & Catatan -->
<div> <div>
@@ -1318,23 +1375,15 @@
const modal = document.getElementById('addTimesheetModal'); const modal = document.getElementById('addTimesheetModal');
if (modal) { if (modal) {
// Reset form pilihan lokasi & unit // Reset form pilihan lokasi & unit
const addLocSelect = document.getElementById('addLocationSelect'); const addLocInput = document.getElementById('addLocationInput');
if (addLocSelect) addLocSelect.selectedIndex = 0; if (addLocInput) addLocInput.value = '';
const customWrap = document.getElementById('addCustomLocationWrapper');
if (customWrap) customWrap.classList.add('hidden');
const customInput = document.getElementById('addCustomLocationInput');
if (customInput) customInput.value = '';
const finalLoc = document.getElementById('addFinalLocation'); const finalLoc = document.getElementById('addFinalLocation');
if (finalLoc) finalLoc.value = ''; if (finalLoc) finalLoc.value = '';
const vehSelect = document.getElementById('addVehicleSelect'); const endMeter = document.getElementById('addEndMeter');
if (vehSelect) { if (endMeter) endMeter.value = '';
vehSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
} onTimesheetLocationTyped('', 'add');
const counter = document.getElementById('addUnitCounterBadge');
if (counter) counter.classList.add('hidden');
const preview = document.getElementById('addVehiclePreview');
if (preview) preview.classList.add('hidden');
const startMeter = document.getElementById('addStartMeter'); const startMeter = document.getElementById('addStartMeter');
if (startMeter) startMeter.value = ''; if (startMeter) startMeter.value = '';
@@ -1424,37 +1473,14 @@
document.getElementById('editTimesheetSubtitle').textContent = `No: ${ts.timesheet_no} (${unitCode || '-'})`; document.getElementById('editTimesheetSubtitle').textContent = `No: ${ts.timesheet_no} (${unitCode || '-'})`;
// 1. Sinkronisasi Lokasi Kerja // 1. Sinkronisasi Lokasi Kerja
const locSelect = document.getElementById('editLocationSelect'); const locInput = document.getElementById('editLocationInput');
const finalLoc = document.getElementById('editFinalLocation'); const finalLoc = document.getElementById('editFinalLocation');
const customWrap = document.getElementById('editCustomLocationWrapper');
const targetLoc = ts.location || ''; const targetLoc = ts.location || '';
if (locInput) locInput.value = targetLoc;
finalLoc.value = targetLoc; if (finalLoc) finalLoc.value = targetLoc;
let matched = false;
if (locSelect) {
for (let i = 0; i < locSelect.options.length; i++) {
if (locSelect.options[i].value.toLowerCase() === targetLoc.toLowerCase()) {
locSelect.selectedIndex = i;
matched = true;
break;
}
}
if (!matched && targetLoc) {
// Tambahkan option lokasi baru jika belum terdaftar
const newOpt = document.createElement('option');
newOpt.value = targetLoc;
newOpt.textContent = `${targetLoc} (Lokasi Riwayat)`;
locSelect.appendChild(newOpt);
locSelect.value = targetLoc;
}
}
if (customWrap) customWrap.classList.add('hidden');
// Filter unit pada lokasi ini dengan memilih ts.vehicle_id // Filter unit pada lokasi ini dengan memilih ts.vehicle_id
onTimesheetLocationChanged(locSelect ? locSelect.value : targetLoc, 'edit', ts.vehicle_id); onTimesheetLocationTyped(targetLoc, 'edit', ts.vehicle_id);
// Cari jenis operator yang sedang diedit untuk mengaktifkan filter yang sesuai // Cari jenis operator yang sedang diedit untuk mengaktifkan filter yang sesuai
let selectedOpType = 'all'; let selectedOpType = 'all';
@@ -1487,6 +1513,10 @@
document.getElementById('editMeterType').value = ts.meter_type || 'HM'; document.getElementById('editMeterType').value = ts.meter_type || 'HM';
document.getElementById('editStartMeter').value = ts.start_meter; document.getElementById('editStartMeter').value = ts.start_meter;
const editEndMeter = document.getElementById('editEndMeter');
if (editEndMeter) {
editEndMeter.value = (ts.end_meter && ts.end_meter !== '-') ? ts.end_meter.replace('.', '').replace(',', '.') : '';
}
document.getElementById('editActivityType').value = ts.activity_type; document.getElementById('editActivityType').value = ts.activity_type;
document.getElementById('editStatus').value = ts.status || 'Operation'; document.getElementById('editStatus').value = ts.status || 'Operation';
@@ -1520,10 +1550,17 @@
modal.style.display = 'none'; modal.style.display = 'none';
} }
// 5. Handler saat Lokasi Kerja Dipilih (Filter Heavy Equipment yang Ready di Lokasi tersebut) // 5. Handler saat Lokasi Kerja Diketik / Dipilih via Datalist Input
function onTimesheetLocationTyped(val, prefix, preselectVehicleId = null) {
const trimmed = (val || '').trim();
const finalLoc = document.getElementById(`${prefix}FinalLocation`);
if (finalLoc) {
finalLoc.value = (trimmed === '[Semua Unit]' || trimmed === 'ALL') ? '' : trimmed;
}
onTimesheetLocationChanged(trimmed, prefix, preselectVehicleId);
}
function onTimesheetLocationChanged(selectedLoc, prefix, preselectVehicleId = null) { function onTimesheetLocationChanged(selectedLoc, prefix, preselectVehicleId = null) {
const customWrapper = document.getElementById(`${prefix}CustomLocationWrapper`);
const customInput = document.getElementById(`${prefix}CustomLocationInput`);
const finalLocation = document.getElementById(`${prefix}FinalLocation`); const finalLocation = document.getElementById(`${prefix}FinalLocation`);
const vehicleSelect = document.getElementById(`${prefix}VehicleSelect`); const vehicleSelect = document.getElementById(`${prefix}VehicleSelect`);
const counterBadge = document.getElementById(`${prefix}UnitCounterBadge`); const counterBadge = document.getElementById(`${prefix}UnitCounterBadge`);
@@ -1531,56 +1568,40 @@
if (!vehicleSelect) return; if (!vehicleSelect) return;
// Tangani pilihan custom atau ALL if (finalLocation) {
if (selectedLoc === '__CUSTOM__') { finalLocation.value = (selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]' || !selectedLoc) ? '' : selectedLoc;
if (customWrapper) customWrapper.classList.remove('hidden');
if (customInput) {
customInput.focus();
if (finalLocation) finalLocation.value = customInput.value.trim();
}
} else {
if (customWrapper) customWrapper.classList.add('hidden');
if (finalLocation) {
finalLocation.value = (selectedLoc === 'ALL' || !selectedLoc) ? '' : selectedLoc;
}
} }
const allUnits = window.unitSupportsData || []; const allUnits = window.unitSupportsData || [];
let filteredUnits = []; let filteredUnits = [];
if (!selectedLoc) { if (!selectedLoc || selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]') {
vehicleSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
if (counterBadge) counterBadge.classList.add('hidden');
if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
return;
} else if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
filteredUnits = allUnits; filteredUnits = allUnits;
} else { } else {
const norm = selectedLoc.trim().toLowerCase(); const norm = selectedLoc.trim().toLowerCase();
filteredUnits = allUnits.filter(u => { filteredUnits = allUnits.filter(u => {
const uLoc = (u.location || 'Site Kerinci').trim().toLowerCase(); const uLoc = (u.location || 'Site Kerinci').trim().toLowerCase();
return uLoc === norm; return uLoc === norm || uLoc.includes(norm);
}); });
// Jika lokasi yang diketik adalah lokasi baru, tetap tampilkan semua unit agar bisa dipilih
if (filteredUnits.length === 0) {
filteredUnits = allUnits;
}
}
// Jika dalam mode edit dan preselectVehicleId tidak ditemukan di lokasi ini (misal unit berpindah setelah ts dicatat), sertakan unit tersebut // Jika dalam mode edit dan preselectVehicleId tidak ditemukan di lokasi ini, sertakan unit tersebut
if (preselectVehicleId) { if (preselectVehicleId) {
const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId)); const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId));
if (!foundInFiltered) { if (!foundInFiltered) {
const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId)); const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId));
if (extra) filteredUnits.unshift(extra); if (extra) filteredUnits.unshift(extra);
}
} }
} }
// Update badge counter // Update badge counter
if (counterBadge) { if (counterBadge) {
counterBadge.classList.remove('hidden'); counterBadge.classList.remove('hidden');
if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') { counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
counterBadge.textContent = `${filteredUnits.length} Total Unit`;
} else {
counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
}
} }
// Render option heavy equipment // Render option heavy equipment
@@ -1590,7 +1611,7 @@
defaultPrompt.disabled = true; defaultPrompt.disabled = true;
defaultPrompt.textContent = filteredUnits.length > 0 defaultPrompt.textContent = filteredUnits.length > 0
? `-- Pilih Heavy Equipment (${filteredUnits.length} Unit Ready) --` ? `-- Pilih Heavy Equipment (${filteredUnits.length} Unit Ready) --`
: `-- Tidak ada unit di lokasi ini (Pilih 'Semua Unit') --`; : `-- Tidak ada unit (${allUnits.length} Unit Total) --`;
vehicleSelect.appendChild(defaultPrompt); vehicleSelect.appendChild(defaultPrompt);
let hasSelected = false; let hasSelected = false;
@@ -1670,10 +1691,13 @@
updateMeterUnitLabels(prefix); updateMeterUnitLabels(prefix);
} }
// Jika lokasi kerja dipilih 'ALL', sinkronkan finalLocation ke lokasi unit // Jika lokasi kerja dipilih 'ALL' atau kosong, sinkronkan ke lokasi unit
const locSelect = document.getElementById(`${prefix}LocationSelect`); const locInput = document.getElementById(`${prefix}LocationInput`);
const finalLoc = document.getElementById(`${prefix}FinalLocation`); const finalLoc = document.getElementById(`${prefix}FinalLocation`);
if (locSelect && locSelect.value === 'ALL' && finalLoc && !finalLoc.value) { if (locInput && (!locInput.value || locInput.value === 'ALL' || locInput.value === '[Semua Unit]')) {
locInput.value = unitLocation;
}
if (finalLoc && (!finalLoc.value || finalLoc.value === 'ALL' || finalLoc.value === '[Semua Unit]')) {
finalLoc.value = unitLocation; finalLoc.value = unitLocation;
} }
@@ -1690,6 +1714,10 @@
if (label) { if (label) {
label.textContent = unit; label.textContent = unit;
} }
const endLabel = document.getElementById(`${prefix}EndMeterUnitLabel`);
if (endLabel) {
endLabel.textContent = unit;
}
} }
document.getElementById('addMeterType')?.addEventListener('change', () => updateMeterUnitLabels('add')); document.getElementById('addMeterType')?.addEventListener('change', () => updateMeterUnitLabels('add'));
@@ -282,11 +282,55 @@
</div> </div>
<div> <div>
<h3 class="text-base font-extrabold text-slate-900">2. Armada & Supir Pengangkut (Transporter)</h3> <h3 class="text-base font-extrabold text-slate-900">2. Armada & Supir Pengangkut (Transporter)</h3>
<p class="text-xs text-slate-500">Truk pengangkut dapat dipilih dari lokasi yang sama atau dimobilisasi dari pool/workshop lain.</p> <p class="text-xs text-slate-500">Pilih kendaraan pengangkut dari armada internal proyek KMH atau input armada dari vendor/rekanan luar.</p>
</div> </div>
</div> </div>
<!-- Banner Info Logistik Rute (Muncul saat Truk dipilih) --> <!-- Pilihan Jenis Pengangkut: Dari Dalam KMH (Internal) vs Dari Luar KMH (Eksternal) -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-2">
Asal Armada Pengangkut <span class="text-rose-500">*</span>
</label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-xl">
<!-- Opsi 1: Dari Dalam KMH -->
<label id="card_transporter_internal" class="flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs">
<input type="radio"
name="transporter_type"
value="internal"
id="radio_transporter_internal"
{{ old('transporter_type', 'internal') === 'internal' ? 'checked' : '' }}
onchange="onTransporterTypeChanged(this.value)"
class="text-blue-600 focus:ring-blue-500">
<div class="text-left">
<span class="block text-xs font-bold flex items-center space-x-1.5">
<i class="fa-solid fa-building-shield text-blue-600"></i>
<span>Dari Dalam KMH (Armada Internal)</span>
</span>
<span class="text-[10px] text-slate-500 block mt-0.5">Pilih lokasi asal armada & unit pengangkut proyek</span>
</div>
</label>
<!-- Opsi 2: Dari Luar KMH -->
<label id="card_transporter_external" class="flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer">
<input type="radio"
name="transporter_type"
value="external"
id="radio_transporter_external"
{{ old('transporter_type') === 'external' ? 'checked' : '' }}
onchange="onTransporterTypeChanged(this.value)"
class="text-blue-600 focus:ring-blue-500">
<div class="text-left">
<span class="block text-xs font-bold flex items-center space-x-1.5">
<i class="fa-solid fa-truck-ramp-box text-slate-500"></i>
<span>Dari Luar KMH (Rental / Vendor)</span>
</span>
<span class="text-[10px] text-slate-500 block mt-0.5">Input manual lokasi asal & nama unit rekanan luar</span>
</div>
</label>
</div>
</div>
<!-- Banner Info Logistik Rute (Muncul saat Truk dipilih / terisi) -->
<div id="routeLogisticsBanner" class="hidden p-3.5 rounded-xl bg-blue-50/80 border border-blue-200 text-xs text-blue-900 flex items-start space-x-3"> <div id="routeLogisticsBanner" class="hidden p-3.5 rounded-xl bg-blue-50/80 border border-blue-200 text-xs text-blue-900 flex items-start space-x-3">
<i class="fa-solid fa-route text-blue-700 text-sm mt-0.5"></i> <i class="fa-solid fa-route text-blue-700 text-sm mt-0.5"></i>
<div class="flex-1"> <div class="flex-1">
@@ -295,64 +339,128 @@
</div> </div>
</div> </div>
<!-- Grid 2 Kolom: Pilih Mobil Pengangkut & Nama Pengangkut --> <!-- ============================================== -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <!-- KONTAINER 1: PENGANGKUT DARI DALAM KMH -->
<!-- Pilih Mobil dari Unit Kita --> <!-- ============================================== -->
<div> <div id="transporterInternalContainer" class="space-y-4">
<label for="transporter_vehicle_id" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<span>Pilih Kendaraan Pengangkut (Armada Kita)</span> <!-- KIRI: PILIH LOKASI ASAL PENGANGKUT (INTERNAL) -->
<span id="transporterLocationHint" class="text-[10px] text-slate-400 font-normal">Truk / Lowbed / Towing</span> <div>
</label> <label for="transporter_origin_location_select" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<select name="transporter_vehicle_id" <span>Lokasi Asal Kendaraan Pengangkut</span>
id="transporter_vehicle_id" <span class="text-[10px] text-blue-700 font-semibold">Filter Berdasarkan Posisi</span>
onchange="onTransporterSelected(this)" </label>
class="w-full px-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800"> <div class="relative">
<option value="">-- Tanpa Truk Pengangkut / Rental Luar / Mobilisasi Mandiri --</option> <i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
@foreach($transporterUnits as $tu) <select id="transporter_origin_location_select"
<option value="{{ $tu->id }}" onchange="onTransporterOriginChanged(this.value)"
data-code="{{ $tu->code }}" class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-bold">
data-name="{{ $tu->code }} - {{ $tu->brand_type }}{{ $tu->license_plate ? ' (' . $tu->license_plate . ')' : '' }}" <option value="" selected>-- Pilih Lokasi Asal Kendaraan Pengangkut --</option>
data-location="{{ $tu->location ?: 'Pool Workshop GA' }}" <option value="ALL">[Tampilkan Semua Lokasi / Semua Armada]</option>
{{ old('transporter_vehicle_id') == $tu->id ? 'selected' : '' }}> @foreach($transporterLocations as $tLoc => $tCount)
{{ $tu->code }} - {{ $tu->brand_type }} [Posisi: {{ $tu->location ?: 'Pool Workshop' }}] <option value="{{ $tLoc }}" {{ old('transporter_origin_location') === $tLoc ? 'selected' : '' }}>
</option> {{ $tLoc }} ({{ $tCount }} Unit Tersedia)
@endforeach </option>
</select> @endforeach
</div> </select>
</div>
<!-- Input / Snapshot Nama Armada Pengangkut --> <p class="text-[10px] text-slate-400 mt-1">Pilih lokasi asal untuk memfilter unit pengangkut yang standby di titik tersebut.</p>
<div>
<label for="transporter_unit_name" class="block text-xs font-bold text-slate-700 mb-1.5">
Identitas / Keterangan Kendaraan Pengangkut
</label>
<div class="relative">
<i class="fa-solid fa-truck absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
name="transporter_unit_name"
id="transporter_unit_name"
value="{{ old('transporter_unit_name') }}"
placeholder="Contoh: DT-05 Hino 500 / Truk Towing Rekanan Luar"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-semibold">
</div> </div>
<p class="text-[10px] text-slate-400 mt-1">Otomatis terisi jika memilih armada internal, atau ketik nama vendor/unit rekanan luar.</p>
<!-- KANAN: PILIH KENDARAAN PENGANGKUT (INPUT KETIKAN TERFILTER) -->
<div>
<label for="internal_transporter_search" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Kendaraan Pengangkut (Armada Kita)</span>
<span id="transporterCounterBadge" class="text-[10px] font-semibold text-blue-700 bg-blue-50 px-2 py-0.5 rounded border border-blue-200 hidden"></span>
</label>
<div class="relative">
<i class="fa-solid fa-truck-moving absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="internal_transporter_search"
list="internalTransporterSuggestionList"
placeholder="Ketik kode/tipe truk (cth: LB 01, DT 05, Lowbed...)"
oninput="onInternalTransporterInput(this.value)"
autocomplete="off"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik atau pilih dari rekomendasi truk pengangkut internal (Lowbed, Flatbed, Dump Truck, Trailer, dll.).</p>
<!-- Datalist Autocomplete Khusus Truk Pengangkut Internal -->
<datalist id="internalTransporterSuggestionList">
@foreach($transporterUnits as $tu)
<option value="{{ $tu->code }} - {{ $tu->brand_type }}{{ $tu->license_plate ? ' (' . $tu->license_plate . ')' : '' }} [Posisi: {{ $tu->location ?: 'Site Kerinci' }}]" data-id="{{ $tu->id }}">
@endforeach
</datalist>
<!-- Hidden ID untuk backend -->
<input type="hidden" name="transporter_vehicle_id" id="transporter_vehicle_id" value="{{ old('transporter_vehicle_id') }}">
</div>
</div>
<!-- Opsi Sinkronisasi Lokasi Truk Pengangkut Internal -->
<div id="transporterUpdateCheckboxWrapper" class="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center space-x-3">
<input type="checkbox"
name="update_transporter_location"
id="update_transporter_location"
value="1"
checked
class="w-4 h-4 rounded text-[#1b5e20] focus:ring-[#1b5e20] border-slate-300 cursor-pointer">
<label for="update_transporter_location" class="text-xs text-slate-700 font-semibold cursor-pointer select-none">
Perbarui juga posisi terkini truk pengangkut ke lokasi tujuan setelah proses pemindahan selesai
</label>
</div> </div>
</div> </div>
<!-- Opsi Sinkronisasi Lokasi Truk Pengangkut --> <!-- ============================================== -->
<div class="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center space-x-3"> <!-- KONTAINER 2: PENGANGKUT DARI LUAR KMH -->
<input type="checkbox" <!-- ============================================== -->
name="update_transporter_location" <div id="transporterExternalContainer" class="hidden space-y-4">
id="update_transporter_location" <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
value="1" <!-- KIRI: ASAL KENDARAAN PENGANGKUT (ISIAN TEKS MANUAL) -->
checked <div>
class="w-4 h-4 rounded text-[#1b5e20] focus:ring-[#1b5e20] border-slate-300 cursor-pointer"> <label for="transporter_origin_location_input" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<label for="update_transporter_location" class="text-xs text-slate-700 font-semibold cursor-pointer select-none"> <span>Asal Kendaraan Pengangkut (Luar)</span>
Perbarui juga posisi terkini truk pengangkut ke lokasi tujuan setelah proses pemindahan selesai <span class="text-[10px] text-slate-400 font-normal">Ketik Bebas / Rekomendasi</span>
</label> </label>
<div class="relative">
<i class="fa-solid fa-map-location-dot absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="transporter_origin_location_input"
list="locationSuggestionList"
placeholder="Contoh: Pool Jambi, Workshop Padang, PT Bhara Seva..."
oninput="onExternalOriginInput(this.value)"
value="{{ old('transporter_type') === 'external' ? old('transporter_origin_location') : '' }}"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik kota asal, pool rekanan, atau nama subkon penyedia armada.</p>
</div>
<!-- KANAN: IDENTITAS / NAMA KENDARAAN PENGANGKUT (ISIAN TEKS MANUAL) -->
<div>
<label for="transporter_unit_name_input" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Identitas / Nama Kendaraan Pengangkut</span>
<span class="text-[10px] text-slate-400 font-normal">Isian Teks Bebas</span>
</label>
<div class="relative">
<i class="fa-solid fa-truck absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="transporter_unit_name_input"
placeholder="Contoh: Truk Tronton Hino BA 1234 XY / Lowbed Rental PT Surya"
oninput="onExternalUnitNameInput(this.value)"
value="{{ old('transporter_type') === 'external' ? old('transporter_unit_name') : '' }}"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik jenis kendaraan, nomor plat polisi, atau identitas unit rekanan luar.</p>
</div>
</div>
</div> </div>
<!-- Field Hidden Final yang Dikirim ke Server -->
<input type="hidden" name="transporter_origin_location" id="final_transporter_origin_location" value="{{ old('transporter_origin_location') }}">
<input type="hidden" name="transporter_unit_name" id="final_transporter_unit_name" value="{{ old('transporter_unit_name') }}">
<!-- Grid 2 Kolom: Supir Pengangkut & Catatan Angkutan --> <!-- Grid 2 Kolom: Supir Pengangkut & Catatan Angkutan -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-1">
<!-- Supir Pengangkut --> <!-- Supir Pengangkut -->
<div> <div>
<label for="transporter_driver_name" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between"> <label for="transporter_driver_name" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
@@ -482,8 +590,20 @@
</div> </div>
<script> <script>
// Inisialisasi daftar semua unit alat berat dari options // Inisialisasi daftar semua unit alat berat & armada pengangkut
let allHeavyUnits = []; let allHeavyUnits = [];
let allTransporterUnits = [
@foreach($transporterUnits as $tu)
{
id: {{ $tu->id }},
code: @json($tu->code),
name: @json($tu->code . ' - ' . $tu->brand_type . ($tu->license_plate ? ' (' . $tu->license_plate . ')' : '')),
location: @json($tu->location ?: 'Site Kerinci'),
category: @json($tu->unit_category ?? 'Truk'),
text: @json($tu->code . ' - ' . $tu->brand_type . ($tu->license_plate ? ' (' . $tu->license_plate . ')' : '') . ' [Posisi: ' . ($tu->location ?: 'Site Kerinci') . ']')
},
@endforeach
];
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const unitSelect = document.getElementById('vehicle_id'); const unitSelect = document.getElementById('vehicle_id');
@@ -504,17 +624,193 @@
}); });
} }
// Cek jika sudah ada lokasi awal (dari old value atau selectedOriginLocation) // Cek jika sudah ada lokasi awal alat berat (dari old value atau selectedOriginLocation)
const originSelect = document.getElementById('origin_location'); const originSelect = document.getElementById('origin_location');
if (originSelect && originSelect.value) { if (originSelect && originSelect.value) {
onOriginLocationChanged(originSelect.value, "{{ old('vehicle_id', $selectedVehicleId ?? '') }}"); onOriginLocationChanged(originSelect.value, "{{ old('vehicle_id', $selectedVehicleId ?? '') }}");
} }
// Inisialisasi tampilan jenis pengangkut (internal vs external)
const currentTransporterType = document.querySelector('input[name="transporter_type"]:checked')?.value || 'internal';
onTransporterTypeChanged(currentTransporterType);
// Inisialisasi datalist saran truk internal
const oldTransporterOrigin = "{{ old('transporter_origin_location') }}";
const oldTransporterId = "{{ old('transporter_vehicle_id') }}";
if (currentTransporterType === 'internal') {
if (oldTransporterOrigin) {
const tLocSelect = document.getElementById('transporter_origin_location_select');
if (tLocSelect) tLocSelect.value = oldTransporterOrigin;
onTransporterOriginChanged(oldTransporterOrigin, oldTransporterId);
} else if (oldTransporterId) {
const matched = allTransporterUnits.find(u => String(u.id) === String(oldTransporterId));
if (matched) {
const tLocSelect = document.getElementById('transporter_origin_location_select');
if (tLocSelect) tLocSelect.value = matched.location;
onTransporterOriginChanged(matched.location, oldTransporterId);
} else {
onTransporterOriginChanged('');
}
} else {
onTransporterOriginChanged('');
}
}
// Inisialisasi tampilan BAST berdasarkan status site awal // Inisialisasi tampilan BAST berdasarkan status site awal
const currentSiteStatus = document.querySelector('input[name="to_site_status"]:checked')?.value || 'inside_site'; const currentSiteStatus = document.querySelector('input[name="to_site_status"]:checked')?.value || 'inside_site';
onSiteStatusChanged(currentSiteStatus); onSiteStatusChanged(currentSiteStatus);
}); });
/**
* Handler untuk Jenis Pengangkut (Dari Dalam KMH vs Dari Luar KMH)
*/
function onTransporterTypeChanged(type) {
const cardInternal = document.getElementById('card_transporter_internal');
const cardExternal = document.getElementById('card_transporter_external');
const containerInternal = document.getElementById('transporterInternalContainer');
const containerExternal = document.getElementById('transporterExternalContainer');
const updateCheckboxWrapper = document.getElementById('transporterUpdateCheckboxWrapper');
const updateCheckbox = document.getElementById('update_transporter_location');
if (type === 'external') {
// Style Card External Aktif
cardExternal.className = 'flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs';
cardInternal.className = 'flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer';
containerInternal.classList.add('hidden');
containerExternal.classList.remove('hidden');
if (updateCheckboxWrapper) updateCheckboxWrapper.classList.add('hidden');
if (updateCheckbox) updateCheckbox.checked = false;
// Kosongkan seleksi unit internal
const vId = document.getElementById('transporter_vehicle_id');
if (vId) vId.value = '';
// Sinkronkan data dari input teks external
const extOrigin = document.getElementById('transporter_origin_location_input')?.value.trim() || '';
const extName = document.getElementById('transporter_unit_name_input')?.value.trim() || '';
document.getElementById('final_transporter_origin_location').value = extOrigin;
document.getElementById('final_transporter_unit_name').value = extName;
} else {
// Style Card Internal Aktif
cardInternal.className = 'flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs';
cardExternal.className = 'flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer';
containerInternal.classList.remove('hidden');
containerExternal.classList.add('hidden');
if (updateCheckboxWrapper) updateCheckboxWrapper.classList.remove('hidden');
if (updateCheckbox) updateCheckbox.checked = true;
// Sinkronkan data dari input pencarian internal
const searchInput = document.getElementById('internal_transporter_search');
if (searchInput) onInternalTransporterInput(searchInput.value);
}
updateRouteBanner();
}
/**
* Handler ketika Lokasi Asal Armada Pengangkut Internal Berubah
*/
function onTransporterOriginChanged(selectedLocation, preselectId = null) {
const datalist = document.getElementById('internalTransporterSuggestionList');
const badge = document.getElementById('transporterCounterBadge');
const searchInput = document.getElementById('internal_transporter_search');
if (!datalist) return;
datalist.innerHTML = '';
const filtered = (!selectedLocation || selectedLocation === 'ALL')
? allTransporterUnits
: allTransporterUnits.filter(u => u.location === selectedLocation);
if (badge) {
badge.classList.remove('hidden');
badge.textContent = `${filtered.length} Truk Tersedia`;
}
if (searchInput) {
if (selectedLocation && selectedLocation !== 'ALL') {
searchInput.placeholder = `Ketik kode truk di ${selectedLocation} (${filtered.length} truk)...`;
} else {
searchInput.placeholder = `Ketik kode/tipe truk (${filtered.length} truk tersedia)...`;
}
}
filtered.forEach(u => {
const opt = document.createElement('option');
opt.value = u.text;
opt.setAttribute('data-id', u.id);
datalist.appendChild(opt);
});
if (preselectId) {
const matched = allTransporterUnits.find(u => String(u.id) === String(preselectId));
if (matched && searchInput) {
searchInput.value = matched.text;
onInternalTransporterInput(matched.text);
}
}
}
/**
* Handler ketika input ketikan truk internal berubah (Autocomplete / Pencarian)
*/
function onInternalTransporterInput(val) {
val = (val || '').trim();
const finalOrigin = document.getElementById('final_transporter_origin_location');
const finalName = document.getElementById('final_transporter_unit_name');
const vehicleIdInput = document.getElementById('transporter_vehicle_id');
if (!val) {
if (vehicleIdInput) vehicleIdInput.value = '';
if (finalName) finalName.value = '';
if (finalOrigin) finalOrigin.value = '';
updateRouteBanner();
return;
}
// Cari unit yang cocok di allTransporterUnits berdasarkan kode atau nama lengkap
const valUpper = val.toUpperCase();
const matched = allTransporterUnits.find(u =>
valUpper === u.code.toUpperCase() ||
valUpper === u.text.toUpperCase() ||
valUpper === u.name.toUpperCase() ||
valUpper.startsWith(u.code.toUpperCase() + ' ') ||
valUpper.startsWith(u.code.toUpperCase() + '-')
);
if (matched) {
if (vehicleIdInput) vehicleIdInput.value = matched.id;
if (finalName) finalName.value = matched.name;
if (finalOrigin) finalOrigin.value = matched.location;
} else {
// Teks ketikan bebas
if (vehicleIdInput) vehicleIdInput.value = '';
if (finalName) finalName.value = val;
}
updateRouteBanner();
}
/**
* Handler input Asal Kendaraan Luar
*/
function onExternalOriginInput(val) {
const finalOrigin = document.getElementById('final_transporter_origin_location');
if (finalOrigin) finalOrigin.value = (val || '').trim();
updateRouteBanner();
}
/**
* Handler input Nama / Identitas Kendaraan Luar
*/
function onExternalUnitNameInput(val) {
const finalName = document.getElementById('final_transporter_unit_name');
if (finalName) finalName.value = (val || '').trim();
updateRouteBanner();
}
/** /**
* Handler untuk Area Tujuan (Di Dalam Site vs Di Luar Site) * Handler untuk Area Tujuan (Di Dalam Site vs Di Luar Site)
* Nomor BAST dan Dokumen hanya muncul saat transfer ke LUAR site. * Nomor BAST dan Dokumen hanya muncul saat transfer ke LUAR site.
@@ -679,46 +975,49 @@
} }
/** /**
* Handler saat Armada Pengangkut Terpilih * Update Banner Logistik Rute Perjalanan (Mendukung Internal & Eksternal)
*/
function onTransporterSelected(selectElement) {
const option = selectElement.options[selectElement.selectedIndex];
const nameInput = document.getElementById('transporter_unit_name');
if (option && option.value) {
const dataName = option.getAttribute('data-name');
if (dataName) {
nameInput.value = dataName;
}
}
updateRouteBanner();
}
/**
* Update Banner Logistik Rute Perjalanan
*/ */
function updateRouteBanner() { function updateRouteBanner() {
const banner = document.getElementById('routeLogisticsBanner'); const banner = document.getElementById('routeLogisticsBanner');
const text = document.getElementById('routeLogisticsText'); const text = document.getElementById('routeLogisticsText');
const transporterSelect = document.getElementById('transporter_vehicle_id');
const originSelect = document.getElementById('origin_location'); const originSelect = document.getElementById('origin_location');
const destinationInput = document.getElementById('to_location'); const destinationInput = document.getElementById('to_location');
const transporterType = document.querySelector('input[name="transporter_type"]:checked')?.value || 'internal';
const optTransporter = transporterSelect.options[transporterSelect.selectedIndex]; if (!banner || !text) return;
if (!optTransporter || !optTransporter.value) {
banner.classList.add('hidden');
return;
}
const transporterCode = optTransporter.getAttribute('data-code'); const originLoc = originSelect && originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
const transporterLoc = optTransporter.getAttribute('data-location') || 'Pool Workshop'; const destLoc = destinationInput && destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
const originLoc = originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
const destLoc = destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
banner.classList.remove('hidden'); if (transporterType === 'internal') {
if (transporterLoc === originLoc) { const truckName = document.getElementById('final_transporter_unit_name')?.value || document.getElementById('internal_transporter_search')?.value.trim();
text.innerHTML = `Truk <strong>${transporterCode}</strong> saat ini standby di <strong>${transporterLoc}</strong> (sama dengan lokasi alat berat) &rarr; Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`; const truckLoc = document.getElementById('final_transporter_origin_location')?.value || 'Site Kerinci';
if (!truckName) {
banner.classList.add('hidden');
return;
}
banner.classList.remove('hidden');
if (truckLoc === originLoc) {
text.innerHTML = `Truk <strong>${truckName}</strong> saat ini standby di <strong>${truckLoc}</strong> (sama dengan lokasi alat berat) &rarr; Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`;
} else {
text.innerHTML = `Truk <strong>${truckName}</strong> diberangkatkan dari <strong>${truckLoc}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
}
} else { } else {
text.innerHTML = `Truk <strong>${transporterCode}</strong> diberangkatkan dari <strong>${transporterLoc}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`; const extOrigin = document.getElementById('transporter_origin_location_input')?.value.trim();
const extName = document.getElementById('transporter_unit_name_input')?.value.trim();
if (!extName && !extOrigin) {
banner.classList.add('hidden');
return;
}
const displayOrigin = extOrigin ? extOrigin : 'Luar Proyek';
const displayName = extName ? extName : 'Armada Eksternal';
banner.classList.remove('hidden');
text.innerHTML = `Armada luar (<strong>${displayName}</strong>) diberangkatkan dari <strong>${displayOrigin}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
} }
} }
</script> </script>
+170 -171
View File
@@ -3,12 +3,12 @@
@section('title', 'Transfer Unit Alat Berat - Admin QMA | PT Kerinci Merangin Hidro') @section('title', 'Transfer Unit Alat Berat - Admin QMA | PT Kerinci Merangin Hidro')
@section('content') @section('content')
<div class="w-full space-y-6"> <div class="w-full space-y-4 sm:space-y-5">
<!-- Header Judul & Tombol Aksi (Persis Format Standar HSE Employees) --> <!-- Header Judul & Tombol Aksi -->
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4"> <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
<div> <div>
<div class="flex items-center space-x-1.5 mb-1"> <div class="flex items-center space-x-1.5 mb-0.5">
<span class="text-xs font-bold uppercase tracking-wider text-[#1b5e20]"> <span class="text-xs font-bold uppercase tracking-wider text-[#1b5e20]">
MANAJEMEN SISTEM MANAJEMEN SISTEM
</span> </span>
@@ -19,22 +19,22 @@
<i class="fa-solid fa-info"></i> <i class="fa-solid fa-info"></i>
</button> </button>
</div> </div>
<h2 class="text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight"> <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
Transfer Unit Alat Berat Transfer Unit Alat Berat
</h2> </h2>
</div> </div>
<!-- Tombol Aksi Kanan --> <!-- Tombol Aksi Kanan -->
<div class="flex items-center gap-2.5 sm:gap-3 w-full sm:w-auto"> <div class="flex items-center gap-2 sm:gap-2.5 w-full sm:w-auto">
<!-- Dropdown Menu Ekspor Format it.allrole.web.id --> <!-- Dropdown Menu Ekspor Format it.allrole.web.id -->
<div class="relative inline-block w-full sm:w-auto flex-1 sm:flex-none" id="exportDropdownContainer"> <div class="relative inline-block w-full sm:w-auto flex-1 sm:flex-none" id="exportDropdownContainer">
<button type="button" <button type="button"
onclick="toggleExportMenu(event)" onclick="toggleExportMenu(event)"
id="btnExportTrigger" id="btnExportTrigger"
class="w-full sm:w-auto border border-emerald-600/30 text-emerald-900 bg-white hover:bg-emerald-50/50 px-3 sm:px-4 py-2.5 rounded-xl text-xs font-bold flex items-center justify-center space-x-2 transition shadow-sm cursor-pointer"> class="w-full sm:w-auto border border-emerald-600/30 text-emerald-900 bg-white hover:bg-emerald-50/50 px-3 sm:px-3.5 py-2 rounded-xl text-xs font-bold flex items-center justify-center space-x-1.5 transition shadow-2xs cursor-pointer">
<i class="fa-regular fa-file-excel text-emerald-700 text-sm"></i> <i class="fa-regular fa-file-excel text-emerald-700 text-sm"></i>
<span class="truncate">Ekspor Data</span> <span class="truncate">Ekspor Data</span>
<i class="fa-solid fa-chevron-down text-[9px] text-slate-400 ml-0.5 sm:ml-1"></i> <i class="fa-solid fa-chevron-down text-[9px] text-slate-400 ml-0.5"></i>
</button> </button>
<div id="exportMenu" style="display: none;" class="absolute right-0 mt-2 w-52 bg-white rounded-xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-slate-100 z-50 overflow-hidden"> <div id="exportMenu" style="display: none;" class="absolute right-0 mt-2 w-52 bg-white rounded-xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-slate-100 z-50 overflow-hidden">
<a href="{{ route('qma.unit_transfers.export_pdf', request()->query()) }}" target="_blank" class="flex items-center px-4 py-3 text-xs text-slate-700 hover:bg-slate-50 hover:text-[#1b5e20] font-bold transition"> <a href="{{ route('qma.unit_transfers.export_pdf', request()->query()) }}" target="_blank" class="flex items-center px-4 py-3 text-xs text-slate-700 hover:bg-slate-50 hover:text-[#1b5e20] font-bold transition">
@@ -51,21 +51,9 @@
@canany(['qma.vehicles.create', 'qma.vehicles.edit']) @canany(['qma.vehicles.create', 'qma.vehicles.edit'])
<a href="{{ route('qma.unit_transfers.create') }}" <a href="{{ route('qma.unit_transfers.create') }}"
class="flex items-center justify-center space-x-2 bg-[#1b5e20] hover:bg-[#144919] text-white px-3 sm:px-4 py-2.5 rounded-xl text-xs font-bold transition shadow-sm cursor-pointer whitespace-nowrap"> class="flex-1 sm:flex-none flex items-center justify-center space-x-1.5 bg-[#1b5e20] hover:bg-[#144919] text-white px-3.5 py-2 rounded-xl text-xs font-bold transition shadow-2xs cursor-pointer whitespace-nowrap">
<i class="fa-solid fa-truck-moving text-sm"></i> <i class="fa-solid fa-truck-moving text-xs"></i>
<span class="hidden sm:inline">Transfer Unit Baru</span> <span>Transfer Unit Baru</span>
<span class="sm:hidden">Transfer Baru</span>
</a>
@endcanany
</div>
</div>
<!-- Tombol Buat Transfer Unit Baru -->
@canany(['qma.vehicles.create', 'qma.vehicles.edit'])
<a href="{{ route('qma.unit_transfers.create') }}"
class="inline-flex items-center justify-center space-x-2 bg-[#1b5e20] hover:bg-[#144919] text-white px-4 py-2.5 rounded-xl text-xs font-bold transition shadow-sm cursor-pointer whitespace-nowrap">
<i class="fa-solid fa-plus text-xs"></i>
<span>Buat Transfer Unit</span>
</a> </a>
@endcanany @endcanany
</div> </div>
@@ -73,8 +61,8 @@
<!-- Alert Notifikasi Flash --> <!-- Alert Notifikasi Flash -->
@if(session('success')) @if(session('success'))
<div class="flex items-center space-x-3 p-4 bg-emerald-50/90 border border-emerald-200 rounded-2xl text-emerald-800 text-xs sm:text-sm font-semibold shadow-2xs"> <div class="flex items-center space-x-3 p-3.5 bg-emerald-50/90 border border-emerald-200 rounded-xl text-emerald-800 text-xs font-semibold shadow-2xs">
<div class="w-7 h-7 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0"> <div class="w-6 h-6 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0 text-xs">
<i class="fa-solid fa-check"></i> <i class="fa-solid fa-check"></i>
</div> </div>
<div class="flex-1"> <div class="flex-1">
@@ -84,8 +72,8 @@
@endif @endif
@if(session('error')) @if(session('error'))
<div class="flex items-center space-x-3 p-4 bg-rose-50/90 border border-rose-200 rounded-2xl text-rose-800 text-xs sm:text-sm font-semibold shadow-2xs"> <div class="flex items-center space-x-3 p-3.5 bg-rose-50/90 border border-rose-200 rounded-xl text-rose-800 text-xs font-semibold shadow-2xs">
<div class="w-7 h-7 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center shrink-0"> <div class="w-6 h-6 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center shrink-0 text-xs">
<i class="fa-solid fa-triangle-exclamation"></i> <i class="fa-solid fa-triangle-exclamation"></i>
</div> </div>
<div class="flex-1"> <div class="flex-1">
@@ -94,178 +82,184 @@
</div> </div>
@endif @endif
<!-- KPI Ringkasan Pemindahan Unit --> <!-- KPI Ringkasan Pemindahan Unit (Ramping & Sleek) -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3.5"> <div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3">
<!-- 1. Total Transfer --> <!-- 1. Total Transfer -->
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs"> <div class="bg-white p-3 sm:p-3.5 rounded-xl border border-slate-200/80 shadow-2xs flex items-center justify-between">
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Pemindahan</p> <div>
<h3 class="text-2xl font-black text-slate-800 mt-1">{{ number_format($totalTransfers, 0, ',', '.') }}</h3> <p class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Total BAST</p>
<span class="text-[10px] text-slate-400 font-medium block mt-1">Semua Dokumen BAST</span> <h3 class="text-lg sm:text-xl font-black text-slate-800 mt-0.5">{{ number_format($totalTransfers, 0, ',', '.') }}</h3>
<span class="text-[10px] text-slate-400 font-medium">Semua Dokumen</span>
</div>
<div class="w-8 h-8 rounded-lg bg-slate-100 text-slate-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-file-contract"></i>
</div>
</div> </div>
<!-- 2. Pemindahan Bulan Ini --> <!-- 2. Pemindahan Bulan Ini -->
<div class="bg-white p-4 rounded-2xl border border-blue-200/80 shadow-xs bg-gradient-to-br from-white to-blue-50/30"> <div class="bg-white p-3 sm:p-3.5 rounded-xl border border-blue-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-blue-50/20">
<p class="text-[11px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p> <div>
<h3 class="text-2xl font-black text-blue-800 mt-1">{{ number_format($thisMonthCount, 0, ',', '.') }}</h3> <p class="text-[10px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p>
<span class="text-[10px] text-blue-600 font-semibold block mt-1">{{ \Carbon\Carbon::now()->translatedFormat('F Y') }}</span> <h3 class="text-lg sm:text-xl font-black text-blue-800 mt-0.5">{{ number_format($thisMonthCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-blue-600 font-semibold">{{ \Carbon\Carbon::now()->translatedFormat('M Y') }}</span>
</div>
<div class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-calendar-check"></i>
</div>
</div> </div>
<!-- 3. Di Dalam Site --> <!-- 3. Di Dalam Site -->
<div class="bg-white p-4 rounded-2xl border border-emerald-200/80 shadow-xs bg-gradient-to-br from-white to-emerald-50/30"> <div class="bg-white p-3 sm:p-3.5 rounded-xl border border-emerald-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-emerald-50/20">
<p class="text-[11px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p> <div>
<h3 class="text-2xl font-black text-emerald-800 mt-1">{{ number_format($insideCount, 0, ',', '.') }}</h3> <p class="text-[10px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p>
<span class="text-[10px] text-emerald-600 font-semibold block mt-1">Area Proyek KMH</span> <h3 class="text-lg sm:text-xl font-black text-emerald-800 mt-0.5">{{ number_format($insideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-emerald-600 font-semibold">Area Proyek</span>
</div>
<div class="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-location-dot"></i>
</div>
</div> </div>
<!-- 4. Di Luar Site --> <!-- 4. Di Luar Site -->
<div class="bg-white p-4 rounded-2xl border border-amber-200/80 shadow-xs bg-gradient-to-br from-white to-amber-50/30"> <div class="bg-white p-3 sm:p-3.5 rounded-xl border border-amber-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-amber-50/20">
<p class="text-[11px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p> <div>
<h3 class="text-2xl font-black text-amber-800 mt-1">{{ number_format($outsideCount, 0, ',', '.') }}</h3> <p class="text-[10px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p>
<span class="text-[10px] text-amber-600 font-semibold block mt-1">Workshop/Luar Proyek</span> <h3 class="text-lg sm:text-xl font-black text-amber-800 mt-0.5">{{ number_format($outsideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-amber-600 font-semibold">Workshop/Luar</span>
</div>
<div class="w-8 h-8 rounded-lg bg-amber-50 text-amber-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-arrow-up-right-from-square"></i>
</div>
</div> </div>
</div> </div>
<!-- Filter Card --> <!-- Kotak Pencarian & Filter Ramping (Inline Format Referensi HSE) -->
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs"> <form method="GET" action="{{ route('qma.unit_transfers.index') }}" id="transferFilterForm" class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2.5 sm:gap-3">
<form method="GET" action="{{ route('qma.unit_transfers.index') }}" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-5 gap-3 items-center"> <!-- Search Text (Kiri) -->
<!-- Search Text --> <div class="relative w-full sm:max-w-md">
<div class="relative md:col-span-2"> <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i> <i class="fa-solid fa-magnifying-glass text-xs"></i>
<input type="text" </span>
name="search" <input type="text"
value="{{ request('search') }}" name="search"
placeholder="Cari No BAST, Unit, Lokasi, Driver, Pelapor..." id="transferSearchInput"
class="w-full pl-9 pr-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition"> value="{{ request('search') }}"
</div> placeholder="Cari No BAST, unit, lokasi, pengangkut, pelapor..."
class="w-full text-xs pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition">
</div>
<!-- Filter Dropdown (Kanan) -->
<div class="flex flex-wrap items-center gap-2 sm:gap-2.5 w-full sm:w-auto">
<!-- Filter Alat Berat --> <!-- Filter Alat Berat -->
<div> <select name="vehicle_id" onchange="this.form.submit()" class="text-xs rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] shadow-sm transition max-w-[200px] truncate">
<select name="vehicle_id" class="w-full px-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-700"> <option value="all">Semua Alat Berat</option>
<option value="all">Semua Alat Berat</option> @foreach($heavyUnits as $hu)
@foreach($heavyUnits as $hu) <option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}>
<option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}> {{ $hu->code }} - {{ $hu->brand_type }}
{{ $hu->code }} - {{ $hu->brand_type }} </option>
</option> @endforeach
@endforeach </select>
</select>
</div>
<!-- Filter Status Area Tujuan --> <!-- Filter Status Area Tujuan -->
<div> <select name="to_site_status" onchange="this.form.submit()" class="text-xs rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] shadow-sm transition">
<select name="to_site_status" class="w-full px-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-700"> <option value="all" {{ request('to_site_status') === 'all' ? 'selected' : '' }}>Semua Area Tujuan</option>
<option value="all" {{ request('to_site_status') === 'all' ? 'selected' : '' }}>Semua Area Tujuan</option> <option value="inside_site" {{ request('to_site_status') === 'inside_site' ? 'selected' : '' }}>Di Dalam Site</option>
<option value="inside_site" {{ request('to_site_status') === 'inside_site' ? 'selected' : '' }}>Di Dalam Site</option> <option value="outside_site" {{ request('to_site_status') === 'outside_site' ? 'selected' : '' }}>Di Luar Site</option>
<option value="outside_site" {{ request('to_site_status') === 'outside_site' ? 'selected' : '' }}>Di Luar Site</option> </select>
</select>
</div>
<!-- Tombol Filter & Reset --> @if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date']))
<div class="flex items-center space-x-2"> <a href="{{ route('qma.unit_transfers.index') }}" class="px-2.5 py-2 rounded-xl text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 hover:bg-rose-100 transition whitespace-nowrap" title="Reset Filter">
<button type="submit" class="flex-1 px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition shadow-sm cursor-pointer text-center"> <i class="fa-solid fa-rotate-left mr-1"></i>Reset
Filter </a>
</button> @endif
@if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date'])) </div>
<a href="{{ route('qma.unit_transfers.index') }}" class="px-3 py-2 rounded-xl text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 hover:bg-rose-100 transition whitespace-nowrap" title="Reset Filter"> </form>
<i class="fa-solid fa-rotate-left"></i>
</a>
@endif
</div>
</form>
</div>
<!-- Tabel Riwayat Transfer Unit dengan Header Biru Tua Navy (Pada Mobile: Format Kotak Tanpa Border Radius) --> <!-- Tabel Riwayat Transfer Unit -->
<div class="bg-white rounded-none sm:rounded-2xl border border-slate-200 shadow-sm overflow-hidden"> <div class="bg-white rounded-none sm:rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="min-w-full text-xs text-left border-collapse"> <table class="min-w-full text-xs text-left border-collapse">
<!-- Header Tabel Navy Gelap Solid #06213f --> <!-- Header Tabel Navy Gelap Solid #06213f -->
<thead class="bg-[#06213f] text-white font-bold text-[11px] uppercase tracking-wider"> <thead class="bg-[#06213f] text-white font-bold text-[11px] uppercase tracking-wider">
<tr> <tr>
<th class="py-3.5 px-4 text-center w-12">NO</th> <th class="py-3 px-3.5 text-center w-10">NO</th>
<th class="py-3.5 px-4 whitespace-nowrap">TANGGAL & NO TRANSFER</th> <th class="py-3 px-3.5 whitespace-nowrap">DOKUMEN & TANGGAL</th>
<th class="py-3.5 px-4 whitespace-nowrap">BERITA ACARA (BAST)</th> <th class="py-3 px-3.5 whitespace-nowrap">UNIT ALAT BERAT</th>
<th class="py-3.5 px-4 whitespace-nowrap min-w-[180px]">UNIT ALAT BERAT</th> <th class="py-3 px-3.5 whitespace-nowrap">RUTE PEMINDAHAN</th>
<th class="py-3.5 px-4 whitespace-nowrap min-w-[200px]">PERPINDAHAN LOKASI</th> <th class="py-3 px-3.5 whitespace-nowrap">PENGANGKUT & SUPIR</th>
<th class="py-3.5 px-4 whitespace-nowrap">ARMADA & SUPIR</th> <th class="py-3 px-3.5 whitespace-nowrap">PELAPOR</th>
<th class="py-3.5 px-4 whitespace-nowrap">PELAPOR</th> <th class="py-3 px-3.5 text-center whitespace-nowrap w-24">AKSI</th>
<th class="py-3.5 px-4 text-center whitespace-nowrap w-28">AKSI</th>
</tr> </tr>
</thead> </thead>
<tbody class="divide-y divide-slate-100 text-slate-700 bg-white"> <tbody class="divide-y divide-slate-100 text-slate-700 bg-white">
@forelse($transfers as $index => $t) @forelse($transfers as $index => $t)
<tr class="hover:bg-slate-50/80 transition"> <tr class="hover:bg-slate-50/80 transition">
<!-- 1. No --> <!-- 1. No -->
<td class="py-3.5 px-3.5 text-center text-slate-400 font-medium"> <td class="py-2.5 px-3.5 text-center text-slate-400 font-medium">
{{ $transfers->firstItem() + $index }} {{ $transfers->firstItem() + $index }}
</td> </td>
<!-- 2. Tanggal & No Transfer --> <!-- 2. Dokumen BAST & Tanggal Transfer -->
<td class="py-3.5 px-3.5 whitespace-nowrap"> <td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="font-bold text-slate-900"> <div class="flex items-center space-x-1.5">
{{ $t->transfer_date ? $t->transfer_date->translatedFormat('d M Y') : '-' }} @if($t->document_number)
</div> <span class="font-bold text-slate-900 font-mono text-xs">
<span class="inline-block mt-0.5 font-mono text-[10px] text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded"> {{ $t->document_number }}
{{ $t->transfer_no }} </span>
</span> @if($t->document_file_path)
</td> <a href="{{ $t->document_file_url }}" target="_blank" class="text-emerald-700 hover:text-emerald-900 text-xs" title="Lihat Lampiran Berkas">
<i class="fa-solid fa-paperclip"></i>
<!-- 3. Berita Acara --> </a>
<td class="py-3.5 px-3.5 min-w-[200px]"> @endif
@if($t->document_number)
<div class="font-bold text-slate-900 leading-tight font-mono text-xs">
{{ $t->document_number }}
</div>
<div class="text-[11px] text-slate-500 mt-0.5 line-clamp-1" title="{{ $t->document_title }}">
{{ $t->document_title }}
</div>
@if($t->document_file_path)
<a href="{{ $t->document_file_url }}" target="_blank" class="inline-flex items-center space-x-1 text-[10px] font-bold text-emerald-700 hover:text-emerald-900 mt-1">
<i class="fa-solid fa-paperclip"></i>
<span>Lihat Lampiran</span>
</a>
@endif
@else
<span class="inline-flex items-center space-x-1 px-2 py-0.5 rounded text-[11px] font-medium text-slate-500 bg-slate-100 border border-slate-200">
<span>Tanpa BAST (Internal Site)</span>
</span>
@endif
</td>
<!-- 4. Unit Alat Berat -->
<td class="py-3.5 px-3.5 whitespace-nowrap">
<div class="flex items-center space-x-2.5">
@if($t->vehicle && $t->vehicle->photo_url)
<img src="{{ $t->vehicle->photo_url }}" alt="{{ $t->vehicle->code }}" class="w-9 h-9 rounded-xl object-cover border border-slate-200 shrink-0">
@else @else
<div class="w-9 h-9 rounded-xl bg-slate-100 text-slate-400 flex items-center justify-center shrink-0 border border-slate-200"> <span class="px-1.5 py-0.5 rounded text-[10px] font-bold text-slate-600 bg-slate-100 border border-slate-200">
<i class="fa-solid fa-truck-monster text-sm"></i> Internal Site
</span>
@endif
</div>
<div class="text-[11px] text-slate-500 mt-0.5 flex items-center gap-1.5 font-medium">
<span>{{ $t->transfer_date ? $t->transfer_date->translatedFormat('d M Y') : '-' }}</span>
<span class="text-slate-300">&bull;</span>
<span class="font-mono text-[10px] text-slate-400">{{ $t->transfer_no }}</span>
</div>
</td>
<!-- 3. Unit Alat Berat -->
<td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="flex items-center space-x-2">
@if($t->vehicle && $t->vehicle->photo_url)
<img src="{{ $t->vehicle->photo_url }}" alt="{{ $t->vehicle->code }}" class="w-8 h-8 rounded-lg object-cover border border-slate-200 shrink-0">
@else
<div class="w-8 h-8 rounded-lg bg-slate-100 text-slate-400 flex items-center justify-center shrink-0 border border-slate-200 text-xs">
<i class="fa-solid fa-truck-monster"></i>
</div> </div>
@endif @endif
<div> <div>
<div class="font-black text-slate-900 tracking-tight"> <div class="font-black text-slate-900 tracking-tight text-xs">
{{ $t->vehicle?->code ?? '-' }} {{ $t->vehicle?->code ?? '-' }}
</div> </div>
<div class="text-[11px] text-slate-500"> <div class="text-[10px] text-slate-500 max-w-[150px] truncate" title="{{ $t->vehicle?->brand_type ?? '-' }}">
{{ $t->vehicle?->brand_type ?? '-' }} {{ $t->vehicle?->brand_type ?? '-' }}
</div> </div>
</div> </div>
</div> </div>
</td> </td>
<!-- 5. Lokasi Asal -> Lokasi Tujuan --> <!-- 4. Rute Pemindahan -->
<td class="py-3.5 px-3.5"> <td class="py-2.5 px-3.5">
<div class="flex items-center space-x-1.5 text-xs"> <div class="flex items-center space-x-1.5 text-xs whitespace-nowrap">
<span class="text-slate-600 font-medium">{{ $t->from_location }}</span> <span class="text-slate-600 font-medium">{{ $t->from_location }}</span>
<i class="fa-solid fa-arrow-right text-[10px] text-emerald-600"></i> <i class="fa-solid fa-arrow-right text-[10px] text-slate-400"></i>
<span class="font-extrabold text-[#1b5e20]">{{ $t->to_location }}</span> <span class="font-bold text-[#1b5e20]">{{ $t->to_location }}</span>
</div> </div>
<div class="mt-1"> <div class="mt-0.5">
@if($t->isToInsideSite()) @if($t->isToInsideSite())
<span class="inline-flex items-center space-x-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200"> <span class="inline-flex items-center gap-1 text-[10px] font-semibold text-emerald-700">
<span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
<span>Di Dalam Site</span> <span>Di Dalam Site</span>
</span> </span>
@else @else
<span class="inline-flex items-center space-x-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-50 text-amber-700 border border-amber-200"> <span class="inline-flex items-center gap-1 text-[10px] font-semibold text-amber-700">
<span class="w-1.5 h-1.5 rounded-full bg-amber-500"></span> <span class="w-1.5 h-1.5 rounded-full bg-amber-500"></span>
<span>Di Luar Site</span> <span>Di Luar Site</span>
</span> </span>
@@ -273,34 +267,39 @@
</div> </div>
</td> </td>
<!-- 6. Armada & Supir Pengangkut --> <!-- 5. Armada & Supir Pengangkut -->
<td class="py-3.5 px-3.5 whitespace-nowrap"> <td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="font-semibold text-slate-800"> <div class="font-semibold text-slate-800 text-xs flex items-center gap-1.5">
<i class="fa-solid fa-truck-moving text-slate-400 mr-1 text-[11px]"></i> <i class="fa-solid fa-truck-moving text-slate-400 text-[10px]"></i>
{{ $t->transporter_unit_name ?: ($t->transporterVehicle?->code ?? 'Tanpa Pengangkut') }} <span>{{ $t->transporter_unit_name ?: ($t->transporterVehicle?->code ?? 'Tanpa Pengangkut') }}</span>
@if($t->transporter_type === 'external' || (!$t->transporter_vehicle_id && $t->transporter_unit_name))
<span class="text-[9px] px-1.5 py-0.2 rounded font-bold bg-amber-50 text-amber-700 border border-amber-200">Luar</span>
@endif
</div> </div>
<div class="text-[11px] text-slate-500 mt-0.5"> <div class="text-[11px] text-slate-500 mt-0.5 flex items-center gap-1.5">
<i class="fa-solid fa-id-badge text-slate-400 mr-1 text-[11px]"></i> <span>{{ $t->transporter_driver_name ?: ($t->transporterDriver?->name ?? '-') }}</span>
{{ $t->transporter_driver_name ?: ($t->transporterDriver?->name ?? '-') }} @if($t->transporter_origin_location)
<span class="text-[10px] text-slate-400">| Asal: {{ $t->transporter_origin_location }}</span>
@endif
</div> </div>
</td> </td>
<!-- 7. Pelapor --> <!-- 6. Pelapor -->
<td class="py-3.5 px-3.5 whitespace-nowrap"> <td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="font-bold text-slate-800"> <div class="font-bold text-slate-800 text-xs">
{{ $t->reported_by }} {{ $t->reported_by }}
</div> </div>
<div class="text-[10px] text-slate-400"> <div class="text-[10px] text-slate-400">
Petugas QMA QMA
</div> </div>
</td> </td>
<!-- 8. Aksi --> <!-- 7. Aksi -->
<td class="py-3.5 px-3.5 text-center whitespace-nowrap"> <td class="py-2.5 px-3.5 text-center whitespace-nowrap">
<div class="inline-flex items-center space-x-1.5"> <div class="inline-flex items-center space-x-1">
<!-- Tombol Lihat Detail BAST --> <!-- Tombol Lihat Detail BAST -->
<a href="{{ route('qma.unit_transfers.show', $t->id) }}" <a href="{{ route('qma.unit_transfers.show', $t->id) }}"
class="p-2 rounded-xl text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200/80 transition shadow-2xs" class="p-1.5 rounded-lg text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200/80 transition"
title="Lihat Berita Acara & Detail"> title="Lihat Berita Acara & Detail">
<i class="fa-solid fa-file-invoice text-xs"></i> <i class="fa-solid fa-file-invoice text-xs"></i>
</a> </a>
@@ -309,7 +308,7 @@
@can('qma.vehicles.delete') @can('qma.vehicles.delete')
<button type="button" <button type="button"
onclick="openDeleteModal('{{ $t->id }}', '{{ e($t->document_number) }}', '{{ e($t->vehicle?->code ?? 'Unit') }}')" onclick="openDeleteModal('{{ $t->id }}', '{{ e($t->document_number) }}', '{{ e($t->vehicle?->code ?? 'Unit') }}')"
class="p-2 rounded-xl text-rose-600 bg-rose-50 hover:bg-rose-100 border border-rose-200/80 transition shadow-2xs cursor-pointer" class="p-1.5 rounded-lg text-rose-600 bg-rose-50 hover:bg-rose-100 border border-rose-200/80 transition cursor-pointer"
title="Hapus Data Transfer"> title="Hapus Data Transfer">
<i class="fa-solid fa-trash text-xs"></i> <i class="fa-solid fa-trash text-xs"></i>
</button> </button>
@@ -319,18 +318,18 @@
</tr> </tr>
@empty @empty
<tr> <tr>
<td colspan="8" class="py-12 text-center text-slate-400"> <td colspan="7" class="py-8 sm:py-10 text-center text-slate-400">
<div class="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mx-auto mb-3 text-slate-400 text-2xl"> <div class="w-11 h-11 rounded-full bg-slate-100 flex items-center justify-center mx-auto mb-2 text-slate-400 text-lg">
<i class="fa-solid fa-truck-ramp-box"></i> <i class="fa-solid fa-truck-ramp-box"></i>
</div> </div>
<p class="text-sm font-bold text-slate-700">Belum Ada Data Pemindahan Unit</p> <p class="text-xs font-bold text-slate-700">Belum Ada Data Pemindahan Unit</p>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto"> <p class="text-[11px] text-slate-400 mt-0.5 max-w-sm mx-auto">
Belum ada transaksi pemindahan alat berat yang tercatat. Silakan klik tombol "Buat Transfer Unit" untuk membuat Berita Acara baru. Belum ada transaksi pemindahan alat berat yang tercatat. Silakan klik tombol di bawah untuk membuat Berita Acara baru.
</p> </p>
@canany(['qma.vehicles.create', 'qma.vehicles.edit']) @canany(['qma.vehicles.create', 'qma.vehicles.edit'])
<div class="mt-4"> <div class="mt-3">
<a href="{{ route('qma.unit_transfers.create') }}" class="inline-flex items-center space-x-1.5 px-4 py-2 bg-[#1b5e20] hover:bg-[#144919] text-white rounded-xl text-xs font-bold transition shadow-sm"> <a href="{{ route('qma.unit_transfers.create') }}" class="inline-flex items-center space-x-1.5 px-3.5 py-1.5 bg-[#1b5e20] hover:bg-[#144919] text-white rounded-xl text-xs font-bold transition shadow-2xs">
<i class="fa-solid fa-plus"></i> <i class="fa-solid fa-plus text-xs"></i>
<span>Buat Transfer Unit Baru</span> <span>Buat Transfer Unit Baru</span>
</a> </a>
</div> </div>
@@ -190,8 +190,21 @@
<td class="py-2.5 px-4 font-bold text-slate-600 w-1/3">Kendaraan Pengangkut</td> <td class="py-2.5 px-4 font-bold text-slate-600 w-1/3">Kendaraan Pengangkut</td>
<td class="py-2.5 px-4 font-bold text-slate-900"> <td class="py-2.5 px-4 font-bold text-slate-900">
{{ $transfer->transporter_unit_name ?: ($transfer->transporterVehicle?->code ?? 'Tanpa Truk Pengangkut (Mobilisasi Mandiri)') }} {{ $transfer->transporter_unit_name ?: ($transfer->transporterVehicle?->code ?? 'Tanpa Truk Pengangkut (Mobilisasi Mandiri)') }}
@if($transfer->transporter_type === 'external' || (!$transfer->transporter_vehicle_id && $transfer->transporter_unit_name))
<span class="ml-2 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800 border border-amber-200">Armada Luar / Rekanan</span>
@elseif($transfer->transporter_vehicle_id)
<span class="ml-2 px-2 py-0.5 rounded-full text-[10px] font-bold bg-blue-100 text-blue-800 border border-blue-200">Armada Internal KMH</span>
@endif
</td> </td>
</tr> </tr>
@if($transfer->transporter_origin_location)
<tr>
<td class="py-2.5 px-4 font-bold text-slate-600">Asal Kendaraan Pengangkut</td>
<td class="py-2.5 px-4 font-semibold text-slate-800">
<i class="fa-solid fa-map-pin text-emerald-600 mr-1.5"></i>{{ $transfer->transporter_origin_location }}
</td>
</tr>
@endif
<tr> <tr>
<td class="py-2.5 px-4 font-bold text-slate-600">Nama Pengemudi / Driver</td> <td class="py-2.5 px-4 font-bold text-slate-600">Nama Pengemudi / Driver</td>
<td class="py-2.5 px-4 font-semibold text-slate-800"> <td class="py-2.5 px-4 font-semibold text-slate-800">
@@ -233,62 +246,34 @@
Demikian Berita Acara ini dibuat dengan sebenarnya dalam rangkap yang sah untuk dipergunakan sebagaimana mestinya dalam tertib administrasi aset dan operasional alat berat proyek Kerinci Merangin Hidro. Demikian Berita Acara ini dibuat dengan sebenarnya dalam rangkap yang sah untuk dipergunakan sebagaimana mestinya dalam tertib administrasi aset dan operasional alat berat proyek Kerinci Merangin Hidro.
</p> </p>
<!-- KOLOM TANDA TANGAN (4 PIHAK) --> <!-- KOLOM TANDA TANGAN (2 PIHAK) -->
<div class="pt-6"> <div class="pt-6">
<div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center text-xs"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-8 text-center text-xs max-w-2xl mx-auto">
<!-- 1. Yang Menyerahkan (Driver / Pengangkut) --> <!-- 1. Yang Melakukan / Mencatat Pemindahan -->
<div class="flex flex-col justify-between min-h-[140px] p-2 border border-slate-200 rounded-xl bg-slate-50/40"> <div class="flex flex-col justify-between min-h-[150px] p-4 border border-slate-200 rounded-xl bg-slate-50/40 shadow-sm">
<p class="font-bold text-slate-600 text-[11px]">Yang Menyerahkan / Pengangkut,</p> <p class="font-bold text-slate-700 text-xs uppercase tracking-wider">Yang Mencatat Pemindahan,</p>
<div class="py-6"> <div class="py-8">
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span> <span class="text-[11px] text-slate-400 italic">( Tanda Tangan )</span>
</div> </div>
<div> <div>
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1"> <p class="font-bold text-slate-900 border-t border-slate-300 pt-2 text-sm">
{{ $transfer->transporter_driver_name ?: 'Driver Pengangkut' }} {{ $transfer->user?->name ?? $transfer->reported_by }}
</p> </p>
<p class="text-[10px] text-slate-400">Pengemudi / Operator</p> <p class="text-[11px] text-slate-500 font-medium">Petugas Pemindahan / Pelapor</p>
</div> </div>
</div> </div>
<!-- 2. Yang Melaporkan (Petugas QMA) --> <!-- 2. Admin QMA (Mengetahui / Menyetujui) -->
<div class="flex flex-col justify-between min-h-[140px] p-2 border border-slate-200 rounded-xl bg-slate-50/40"> <div class="flex flex-col justify-between min-h-[150px] p-4 border border-slate-200 rounded-xl bg-slate-50/40 shadow-sm">
<p class="font-bold text-slate-600 text-[11px]">Yang Melaporkan,</p> <p class="font-bold text-slate-700 text-xs uppercase tracking-wider">Mengetahui / Menyetujui,</p>
<div class="py-6"> <div class="py-8">
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span> <span class="text-[11px] text-slate-400 italic">( Tanda Tangan )</span>
</div> </div>
<div> <div>
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1"> <p class="font-bold text-slate-900 border-t border-slate-300 pt-2 text-sm">
{{ $transfer->reported_by }}
</p>
<p class="text-[10px] text-slate-400">Petugas QMA Field</p>
</div>
</div>
<!-- 3. Yang Menerima (Penanggung Jawab Lokasi Baru) -->
<div class="flex flex-col justify-between min-h-[140px] p-2 border border-slate-200 rounded-xl bg-slate-50/40">
<p class="font-bold text-slate-600 text-[11px]">Yang Menerima,</p>
<div class="py-6">
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span>
</div>
<div>
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1">
( .................................... ) ( .................................... )
</p> </p>
<p class="text-[10px] text-slate-400">PIC {{ $transfer->to_location }}</p> <p class="text-[11px] text-slate-500 font-medium">Admin QMA</p>
</div>
</div>
<!-- 4. Mengetahui (Superintendent / Site Manager) -->
<div class="flex flex-col justify-between min-h-[140px] p-2 border border-slate-200 rounded-xl bg-slate-50/40">
<p class="font-bold text-slate-600 text-[11px]">Mengetahui,</p>
<div class="py-6">
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span>
</div>
<div>
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1">
( .................................... )
</p>
<p class="text-[10px] text-slate-400">Superintendent QMA</p>
</div> </div>
</div> </div>
</div> </div>
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -218,9 +218,9 @@ Route::middleware('auth')->group(function () {
// Backup & Restore Sistem (Database & Media) // Backup & Restore Sistem (Database & Media)
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index'); Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store'); Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
Route::post('/backups/inspect-file', [BackupController::class, 'inspectUpload'])->name('backups.inspect_upload');
Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1'); Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1');
Route::get('/backups/{filename}/inspect', [BackupController::class, 'inspect'])->name('backups.inspect'); Route::post('/backups/converter/inspect', [BackupController::class, 'converterInspect'])->name('backups.converter.inspect');
Route::post('/backups/converter/execute', [BackupController::class, 'converterExecute'])->name('backups.converter.execute');
Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download'); Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download');
Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload'); Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload');
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1'); Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1');
-56
View File
@@ -310,60 +310,4 @@ class BackupAndRestoreTest extends TestCase
'target_name' => 'backup_dari_pc.kmh', 'target_name' => 'backup_dari_pc.kmh',
]); ]);
} }
public function test_super_admin_can_inspect_server_kmh_backup(): void
{
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_inspect_server.kmh');
$response = $this->actingAs($this->superAdmin)
->getJson(route('admin.backups.inspect', $filename));
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'data' => [
'filename' => $filename,
'is_valid' => true,
'encryption_cipher' => 'AES-256-CBC',
],
]);
$this->assertContains('users', $response->json('data.tables'));
}
public function test_super_admin_can_inspect_uploaded_kmh_backup_with_zero_disk_retention(): void
{
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_inspect_upload.kmh');
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$kmhContent = file_get_contents($fullPath);
$uploadedFile = UploadedFile::fake()->createWithContent('arsip_lama_2bulan_lalu.kmh', $kmhContent);
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.inspect_upload'), [
'backup_file' => $uploadedFile,
]);
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'data' => [
'filename' => 'arsip_lama_2bulan_lalu.kmh',
'is_valid' => true,
'encryption_cipher' => 'AES-256-CBC',
],
]);
$this->assertContains('users', $response->json('data.tables'));
}
public function test_inspect_kmh_command_outputs_metadata(): void
{
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_cli_inspect.kmh');
$this->artisan('kmh:inspect', ['file' => $filename])
->expectsOutputToContain('HASIL INSPEKSI ARSIP KMH')
->expectsOutputToContain('AES-256-CBC')
->assertExitCode(0);
}
} }
+254
View File
@@ -0,0 +1,254 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\DatabaseBackupService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class BackupConverterTest extends TestCase
{
use RefreshDatabase;
private User $superAdmin;
private DatabaseBackupService $backupService;
protected function setUp(): void
{
parent::setUp();
$role = Role::firstOrCreate(['name' => 'super_admin']);
$this->superAdmin = User::factory()->create([
'username' => 'superadmin_conv_test',
'role' => 'super_admin',
'password' => bcrypt('password123'),
]);
$this->superAdmin->assignRole($role);
$this->backupService = new DatabaseBackupService();
}
protected function tearDown(): void
{
$dir = $this->backupService->getBackupDirectory();
if (File::isDirectory($dir)) {
foreach (File::files($dir) as $f) {
if (str_starts_with($f->getFilename(), 'test_conv_')) {
@unlink($f->getPathname());
}
}
}
parent::tearDown();
}
protected function createSampleKmhFile(string $name = 'test_conv_sample.kmh'): UploadedFile
{
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, $name);
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$content = file_get_contents($fullPath);
@unlink($fullPath);
return UploadedFile::fake()->createWithContent($name, $content);
}
public function test_super_admin_can_inspect_uploaded_kmh_backup(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_inspect.kmh');
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $uploadedFile,
]);
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'data' => [
'filename' => 'test_conv_inspect.kmh',
],
]);
$this->assertContains('users', $response->json('data.tables'));
$this->assertContains('roles', $response->json('data.tables'));
}
public function test_inspect_rejects_non_kmh_file(): void
{
$fakeFile = UploadedFile::fake()->create('document.pdf', 100);
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $fakeFile,
]);
$response->assertStatus(422);
$response->assertJson([
'success' => false,
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
]);
}
public function test_inspect_rejects_corrupted_kmh_content(): void
{
$corruptFile = UploadedFile::fake()->createWithContent('corrupted.kmh', "KMH_ENCRYPTED_BACKUP_V1\nCorruptedHMACandPayload12345");
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $corruptFile,
]);
$response->assertStatus(422);
$response->assertJson([
'success' => false,
]);
}
public function test_super_admin_can_convert_single_table_to_xlsx(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_single.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Tabel_users_', $disposition);
$this->assertStringEndsWith('.xlsx', $disposition);
}
public function test_super_admin_can_convert_multiple_tables_to_xlsx_zip(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_multi_xlsx.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users', 'roles'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/zip');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_Excel_', $disposition);
$this->assertStringEndsWith('.zip', $disposition);
}
public function test_super_admin_can_convert_tables_to_csv_zip(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_csv.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users', 'roles'],
'format' => 'csv',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/zip');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_CSV_', $disposition);
$this->assertStringEndsWith('.zip', $disposition);
}
public function test_super_admin_can_convert_tables_to_sql(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_sql.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'sql',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/sql');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_SQL_', $disposition);
$this->assertStringEndsWith('.sql', $disposition);
}
public function test_convert_validates_required_fields(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_val.kmh');
// Tanpa tabel
$response1 = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => [],
'format' => 'xlsx',
]);
$response1->assertStatus(422);
// Format tidak valid
$response2 = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'invalid_format',
]);
$response2->assertStatus(422);
}
public function test_active_database_remains_unaffected_after_conversion(): void
{
$initialUserCount = User::count();
$this->assertGreaterThan(0, $initialUserCount);
$uploadedFile = $this->createSampleKmhFile('test_conv_safety.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
// Pastikan jumlah user di database aktif tetap sama persis
$this->assertEquals($initialUserCount, User::count());
}
public function test_super_admin_can_convert_using_session_token_without_reuploading(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_token.kmh');
// Step 1: Inspect and receive session token
$inspectResponse = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $uploadedFile,
]);
$inspectResponse->assertStatus(200);
$token = $inspectResponse->json('data.token');
$this->assertNotEmpty($token);
// Step 2: Execute conversion passing ONLY the token (zero re-upload)
$executeResponse = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'token' => $token,
'tables' => ['users'],
'format' => 'xlsx',
]);
$executeResponse->assertStatus(200);
$executeResponse->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$disposition = $executeResponse->headers->get('Content-Disposition');
$this->assertStringContainsString('Tabel_users_', $disposition);
$this->assertStringEndsWith('.xlsx', $disposition);
}
}
+91
View File
@@ -190,4 +190,95 @@ class GateInspectionTest extends TestCase
'gate_id' => null, 'gate_id' => null,
]); ]);
} }
public function test_guard_can_reject_vehicle_activity_with_rejection_note(): void
{
$vehicle = Vehicle::create([
'code' => 'LV-REJECT-01',
'category' => 'light_vehicle',
'brand_type' => 'Mitsubishi Triton',
'current_km' => 2000,
]);
$driver = Employee::create([
'name' => 'Driver Mau Lewat',
'nik' => 'KMH-REJ-01',
]);
$activity = VehicleActivity::create([
'transaction_no' => 'TRX-REJ-001',
'vehicle_id' => $vehicle->id,
'driver_id' => $driver->id,
'gate_id' => $this->gate1->id,
'direction' => 'out',
'previous_km' => 2000,
'current_km' => 2050,
'distance' => 50,
'purpose' => 'Ambil Material Proyek',
'validation_status' => 'pending',
'recorded_at' => now(),
]);
$response = $this->actingAs($this->guardUser)
->post(route('pg.gate.reject', $activity->id), [
'security_guard_id' => $this->guard->id,
'rejection_note' => 'Masa berlaku SIMPER pengemudi telah kedaluwarsa (Expired)',
]);
$response->assertRedirect();
$response->assertSessionHas('success');
$activity->refresh();
$this->assertEquals('rejected', $activity->validation_status);
$this->assertEquals($this->guard->id, $activity->security_guard_id);
$this->assertEquals('Masa berlaku SIMPER pengemudi telah kedaluwarsa (Expired)', $activity->rejection_note);
$this->assertNotNull($activity->validated_at);
// Verifikasi tercatat di AdminActivityLog
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'reject',
'module' => 'pos_gerbang',
'target_type' => 'vehicle_activity',
'target_id' => $activity->id,
]);
}
public function test_cannot_reject_vehicle_activity_without_rejection_note(): void
{
$vehicle = Vehicle::create([
'code' => 'LV-REJECT-02',
'category' => 'light_vehicle',
'brand_type' => 'Toyota Hilux',
'current_km' => 1500,
]);
$driver = Employee::create([
'name' => 'Driver No Note',
'nik' => 'KMH-REJ-02',
]);
$activity = VehicleActivity::create([
'transaction_no' => 'TRX-REJ-002',
'vehicle_id' => $vehicle->id,
'driver_id' => $driver->id,
'gate_id' => $this->gate1->id,
'direction' => 'in',
'previous_km' => 1500,
'current_km' => 1520,
'distance' => 20,
'purpose' => 'Patroli',
'validation_status' => 'pending',
'recorded_at' => now(),
]);
$response = $this->actingAs($this->guardUser)
->post(route('pg.gate.reject', $activity->id), [
'security_guard_id' => $this->guard->id,
'rejection_note' => '',
]);
$response->assertSessionHasErrors('rejection_note');
$activity->refresh();
$this->assertEquals('pending', $activity->validation_status);
}
} }
@@ -430,4 +430,245 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase
'position' => 'Anggota', 'position' => 'Anggota',
]); ]);
} }
public function test_unchecking_and_readding_simper_does_not_trigger_500_unique_constraint_violation(): void
{
$simperLv = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-LV'],
['name' => 'SIMPER Light Vehicle', 'category_scope' => 'light_vehicle', 'is_active' => true]
);
$simperDt = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-DT'],
['name' => 'SIMPER Dump Truck', 'category_scope' => 'unit_support_mobile', 'is_active' => true]
);
$employee = Employee::create([
'nik' => 'KMH-MULTI-SIMPER',
'name' => 'Driver Multi Izin',
'employee_type' => 'Karyawan',
'unit_kerja' => 'Umum',
'division' => 'Operasi',
'position' => 'Driver Tambang',
'is_operator' => true,
'simper_expired_at' => '2026-12-31',
]);
// 1. Tambah 2 SIMPER awal
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperLv->id,
'simper_number' => 'SMP-001-LV',
'expired_at' => '2026-12-31',
'status' => 'active',
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'simper_number' => 'SMP-001-DT',
'expired_at' => '2026-12-31',
'status' => 'active',
]);
// 2. Edit Karyawan: Hilangkan (uncheck) SIMPER-DT (hanya sisakan SIMPER-LV)
$responseUncheck = $this->actingAs($this->hseAdmin)
->post(route('hse.employees.update', $employee->id), [
'name' => 'Driver Multi Izin',
'is_operator' => '1',
'simper_assignments' => [
$simperLv->id => [
'enabled' => '1',
'simper_number' => 'SMP-001-LV',
'expired_at' => '2026-12-31',
],
$simperDt->id => [
// Unchecked: enabled tidak dikirim
'simper_number' => 'SMP-001-DT',
'expired_at' => '',
],
],
]);
$responseUncheck->assertSessionHasNoErrors();
$responseUncheck->assertRedirect();
// SIMPER-DT harus terhapus
$this->assertDatabaseMissing('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'deleted_at' => null,
]);
// 3. Edit Karyawan LAGI: Centang kembali (re-add) SIMPER-DT
// Ini adalah skenario yang sebelumnya memicu 500 Duplicate entry
$responseReadd = $this->actingAs($this->hseAdmin)
->post(route('hse.employees.update', $employee->id), [
'name' => 'Driver Multi Izin',
'is_operator' => '1',
'simper_assignments' => [
$simperLv->id => [
'enabled' => '1',
'simper_number' => 'SMP-001-LV',
'expired_at' => '2026-12-31',
],
$simperDt->id => [
'enabled' => '1',
'simper_number' => 'SMP-001-DT-RENEWED',
'expired_at' => '2027-06-30',
],
],
]);
$responseReadd->assertSessionHasNoErrors();
$responseReadd->assertRedirect();
// Verifikasi bahwa SIMPER-DT berhasil aktif kembali tanpa error 500
$this->assertDatabaseHas('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'simper_number' => 'SMP-001-DT-RENEWED',
'expired_at' => '2027-06-30 00:00:00',
'status' => 'active',
'deleted_at' => null,
]);
$employee->refresh();
$this->assertEquals('2027-06-30', $employee->simper_expired_at->format('Y-m-d'));
}
public function test_hse_can_renew_specific_simper_with_dropdown_selection(): void
{
$simperLv = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-LV'],
['name' => 'SIMPER Light Vehicle', 'category_scope' => 'light_vehicle', 'is_active' => true]
);
$simperDt = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-DT'],
['name' => 'SIMPER Dump Truck', 'category_scope' => 'unit_support_mobile', 'is_active' => true]
);
$employee = Employee::create([
'nik' => 'KMH-RENEW-TEST',
'name' => 'Operator Perpanjang',
'employee_type' => 'Karyawan',
'unit_kerja' => 'Operasi',
'division' => 'Operasi',
'position' => 'Driver',
'is_operator' => true,
'simper_expired_at' => '2026-10-01',
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperLv->id,
'simper_number' => 'SMP-LV-01',
'expired_at' => '2026-10-01',
'status' => 'active',
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'simper_number' => 'SMP-DT-01',
'expired_at' => '2026-09-01',
'status' => 'active',
]);
// Perpanjang HANYA SIMPER-DT via modal dropdown (renew_simper_type_id = DT)
$response = $this->actingAs($this->hseAdmin)
->post(route('hse.employees.update', $employee->id), [
'is_operator' => '1',
'renew_simper_type_id' => (string) $simperDt->id,
'simper_expired_at' => '2027-12-31',
]);
$response->assertSessionHasNoErrors();
$response->assertRedirect();
// SIMPER-DT harus diperpanjang ke 2027-12-31
$this->assertDatabaseHas('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'expired_at' => '2027-12-31 00:00:00',
]);
// SIMPER-LV harus tetap 2026-10-01 (tidak berubah)
$this->assertDatabaseHas('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperLv->id,
'expired_at' => '2026-10-01 00:00:00',
]);
// Max expired_at master employee harus ikut naik ke 2027-12-31
$employee->refresh();
$this->assertEquals('2027-12-31', $employee->simper_expired_at->format('Y-m-d'));
}
public function test_hse_can_renew_all_simpers_simultaneously(): void
{
$simperLv = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-LV'],
['name' => 'SIMPER Light Vehicle', 'category_scope' => 'light_vehicle', 'is_active' => true]
);
$simperDt = \App\Models\SimperType::firstOrCreate(
['code' => 'SIMPER-DT'],
['name' => 'SIMPER Dump Truck', 'category_scope' => 'unit_support_mobile', 'is_active' => true]
);
$employee = Employee::create([
'nik' => 'KMH-RENEW-ALL',
'name' => 'Operator All Renew',
'employee_type' => 'Karyawan',
'unit_kerja' => 'Operasi',
'division' => 'Operasi',
'position' => 'Driver',
'is_operator' => true,
'simper_expired_at' => '2026-05-01',
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperLv->id,
'simper_number' => 'SMP-LV-02',
'expired_at' => '2026-05-01',
'status' => 'active',
]);
\App\Models\EmployeeSimper::create([
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'simper_number' => 'SMP-DT-02',
'expired_at' => '2026-06-01',
'status' => 'active',
]);
// Perpanjang SEMUA SIMPER sekaligus (renew_simper_type_id = all)
$response = $this->actingAs($this->hseAdmin)
->post(route('hse.employees.update', $employee->id), [
'is_operator' => '1',
'renew_simper_type_id' => 'all',
'simper_expired_at' => '2028-01-01',
]);
$response->assertSessionHasNoErrors();
$response->assertRedirect();
// Keduanya harus naik ke 2028-01-01
$this->assertDatabaseHas('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperLv->id,
'expired_at' => '2028-01-01 00:00:00',
]);
$this->assertDatabaseHas('employee_simpers', [
'employee_id' => $employee->id,
'simper_type_id' => $simperDt->id,
'expired_at' => '2028-01-01 00:00:00',
]);
$employee->refresh();
$this->assertEquals('2028-01-01', $employee->simper_expired_at->format('Y-m-d'));
}
} }
@@ -0,0 +1,187 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Models\Vehicle;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class QmaHeavyEquipmentThreeLevelNavigationTest extends TestCase
{
use RefreshDatabase;
private User $qmaAdmin;
protected function setUp(): void
{
parent::setUp();
$this->seed(RolePermissionSeeder::class);
$this->qmaAdmin = User::factory()->create([
'name' => 'Admin QMA Test',
'username' => 'qma_test_3level',
'role' => 'qma_admin',
]);
$this->qmaAdmin->assignRole('qma_admin');
// 1. Hauling Units (Dump Truck & Mixer Truck)
Vehicle::create([
'code' => 'DT-01',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Dump Truck',
'unit_type' => 'DUMP TRUCK',
'brand' => 'HOWO',
'brand_type' => 'HOWO SINOTRUK 336',
'model_number' => 'ZZ3257N3847',
'serial_number' => 'HW123456',
'location' => 'Main Dam',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
Vehicle::create([
'code' => 'DT-02',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Dump Truck',
'unit_type' => 'DUMP TRUCK',
'brand' => 'HOWO',
'brand_type' => 'HOWO SINOTRUK 336',
'location' => 'Adit 3',
'site_status' => 'inside_site',
'status' => 'Standby',
]);
Vehicle::create([
'code' => 'MT-01',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Truk Mixer',
'unit_type' => 'MIXER TRUCK',
'brand' => 'YUCHAI',
'brand_type' => 'YUCHAI DIECI',
'location' => 'Batching Plant',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
// 2. Loader Units (Excavator)
Vehicle::create([
'code' => 'EX-01',
'category' => 'unit_support',
'operational_group' => 'LOADER',
'unit_category' => 'Excavator',
'unit_type' => 'EXCAVATOR',
'brand' => 'KOMATSU',
'brand_type' => 'KOMATSU PC200-8',
'location' => 'Power House',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
// 3. Support Units (Compressor)
Vehicle::create([
'code' => 'CP-01',
'category' => 'unit_support',
'operational_group' => 'SUPPORT',
'unit_category' => 'Engine Compressor',
'unit_type' => 'COMPRESSOR',
'brand' => 'AIRMAN',
'brand_type' => 'AIRMAN PDS655S',
'location' => 'Adit 2',
'site_status' => 'inside_site',
'status' => 'Breakdown',
]);
}
/**
* Level 1: Halaman utama menampilkan daftar Kelompok Operasional (HAULING, LOADER, SUPPORT, dll).
*/
public function test_level_1_shows_operational_groups(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'groups');
$response->assertViewHas('groups');
// Memastikan nama-nama kelompok operasional tampil di tabel Level 1
$response->assertSee('HAULING');
$response->assertSee('LOADER');
$response->assertSee('SUPPORT');
$response->assertSee('Lihat Kategori');
}
/**
* Level 2: Memilih salah satu Kelompok Operasional menampilkan daftar tipe alat di dalamnya.
*/
public function test_level_2_shows_types_in_selected_group(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?group=HAULING');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'types');
$response->assertViewHas('selectedGroup', 'HAULING');
// Tipe dalam kelompok HAULING
$response->assertSee('DUMP TRUCK');
$response->assertSee('MIXER TRUCK');
$typesInView = collect($response->viewData('types')->items())->pluck('unit_type')->all();
$this->assertContains('DUMP TRUCK', $typesInView);
$this->assertContains('MIXER TRUCK', $typesInView);
$this->assertNotContains('EXCAVATOR', $typesInView);
$this->assertNotContains('COMPRESSOR', $typesInView);
// Breadcrumb & tombol kembali
$response->assertSee('Semua Kelompok');
$response->assertSee('Buka Unit');
}
/**
* Level 3: Memilih tipe alat menampilkan daftar unit fisik individual.
*/
public function test_level_3_shows_physical_units(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?group=HAULING&type=DUMP+TRUCK');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'units');
$response->assertViewHas('selectedGroup', 'HAULING');
$response->assertViewHas('selectedType', 'DUMP TRUCK');
// Unit fisik Dump Truck
$response->assertSee('DT-01');
$response->assertSee('DT-02');
$response->assertSee('HOWO SINOTRUK 336');
$response->assertSee('Main Dam');
$codesInView = collect($response->viewData('typeUnits')->items())->pluck('code')->all();
$this->assertContains('DT-01', $codesInView);
$this->assertContains('DT-02', $codesInView);
$this->assertNotContains('MT-01', $codesInView);
$this->assertNotContains('EX-01', $codesInView);
}
/**
* Auto-detect group jika user hanya memasukkan query parameter `type`.
*/
public function test_level_3_auto_detects_group_when_only_type_passed(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?type=EXCAVATOR');
$response->assertStatus(200);
$response->assertViewHas('level', 'units');
$response->assertViewHas('selectedGroup', 'LOADER');
$response->assertViewHas('selectedType', 'EXCAVATOR');
$response->assertSee('EX-01');
$response->assertSee('Power House');
}
}
+57
View File
@@ -675,4 +675,61 @@ class QmaSupportTimesheetTest extends TestCase
'operator_id' => $opDt->id, 'operator_id' => $opDt->id,
]); ]);
} }
/**
* Uji perhitungan otomatis finish HM dan durasi operasional (1 HM = 1 Jam):
* Ketika Budi mengisi 1010 dan berikutnya Joko mengisi 1012, Budi otomatis tercatat selesai di 1012 (2 jam kerja).
*/
public function test_sequential_timesheets_auto_calculate_finish_hm_and_operating_hours(): void
{
$today = Carbon::today()->toDateString();
// 1. Budi mengisi timesheet dengan start_meter 1010 (tanpa end_meter)
$budiData = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => $today,
'start_time' => '08:00',
'meter_type' => 'HM',
'start_meter' => 1010.00,
'location' => 'Adit 3',
'activity_type' => 'Galian Material',
'status' => 'Operation',
];
$res1 = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $budiData);
$res1->assertSessionHas('success');
$budiTs = UnitSupportTimesheet::where('vehicle_id', $this->supportUnit->id)->latest('id')->first();
$this->assertNotNull($budiTs);
$this->assertEquals(1010.00, (float) $budiTs->start_meter);
// 2. Joko mengisi timesheet berikutnya untuk unit yang sama dengan start_meter 1012
$jokoData = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => $today,
'start_time' => '11:00',
'meter_type' => 'HM',
'start_meter' => 1012.00,
'location' => 'Power House',
'activity_type' => 'Loading Material',
'status' => 'Operation',
];
$res2 = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $jokoData);
$res2->assertSessionHas('success');
// Budi's timesheet harus otomatis terupdate end_meter = 1012 dan operating_hours = 2.00
$budiTs->refresh();
$this->assertEquals(1012.00, (float) $budiTs->end_meter);
$this->assertEquals(2.00, (float) $budiTs->operating_hours);
// 3. Uji pada ekspor Excel: Budi's row harus memiliki finish HM 1.012,00 dan jam operasi 2,00 (tidak 0)
$excelRes = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.export_excel'));
$excelRes->assertStatus(200);
}
} }
+33
View File
@@ -379,4 +379,37 @@ class QmaUnitTransferTest extends TestCase
$this->assertEquals('Adit 2 Intake', $transporterHistory->location); $this->assertEquals('Adit 2 Intake', $transporterHistory->location);
$this->assertStringContainsString('Mengantar EXCA-01', $transporterHistory->note); $this->assertStringContainsString('Mengantar EXCA-01', $transporterHistory->note);
} }
/**
* Test transfer unit dengan armada pengangkut eksternal (rental/luar)
* dengan asal kendaraan manual dan nama unit manual.
*/
public function test_store_transfer_with_external_transporter(): void
{
Storage::fake('public');
$payload = [
'vehicle_id' => $this->heavyEquipment->id,
'from_location' => 'Main Dam',
'transfer_date' => Carbon::now()->format('Y-m-d'),
'to_location' => 'Adit 2 Intake',
'to_site_status' => 'inside_site',
'reported_by' => 'Staff QMA Logistik',
'transporter_type' => 'external',
'transporter_origin_location' => 'Pool Jambi',
'transporter_unit_name' => 'Truk Tronton BA 1234 XY (Vendor Subkon)',
'transporter_driver_name' => 'Budi Supir Rental',
'transporter_description' => 'Lashing rantai 4 titik aman',
];
$response = $this->actingAs($this->qmaAdmin)->post(route('qma.unit_transfers.store'), $payload);
$response->assertSessionHas('success');
$transfer = UnitTransfer::latest('id')->first();
$this->assertEquals('external', $transfer->transporter_type);
$this->assertNull($transfer->transporter_vehicle_id);
$this->assertEquals('Pool Jambi', $transfer->transporter_origin_location);
$this->assertEquals('Truk Tronton BA 1234 XY (Vendor Subkon)', $transfer->transporter_unit_name);
$this->assertEquals('Budi Supir Rental', $transfer->transporter_driver_name);
}
} }