Compare commits
26
Commits
433f07b505
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f655c3af1e | ||
|
|
29f878e0e7 | ||
|
|
dc069fe0ec | ||
|
|
a55ead4c5b | ||
|
|
61332f948b | ||
|
|
c1be96c2ba | ||
|
|
6e5c6eeeb8 | ||
|
|
ff3ab616e0 | ||
|
|
5a4969b467 | ||
|
|
2fe265da37 | ||
|
|
008e5f6b9d | ||
|
|
23377631b3 | ||
|
|
b8fa1771b9 | ||
|
|
8a94e98ed9 | ||
|
|
6e84e6106f | ||
|
|
bc2215d98e | ||
|
|
a09071f5ed | ||
|
|
e2054dcb8a | ||
|
|
aec6c36344 | ||
|
|
96178971fd | ||
|
|
b83a8fa843 | ||
|
|
bc6213d864 | ||
|
|
14298cfff3 | ||
|
|
a32e996780 | ||
|
|
721abb56c2 | ||
|
|
93baeac001 |
+2
-1
@@ -21,4 +21,5 @@
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
Thumbs.db
|
||||
/Berkas/
|
||||
/Berkas/*
|
||||
!/Berkas/DATA LOKASI TERBARU RKM KMH.xlsx
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\UnitSupportTimesheet;
|
||||
use App\Models\UnitTransfer;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use App\Models\VehicleLocationHistory;
|
||||
use App\Services\TrashService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class CleanTestLogsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'kmh:clean-test-logs
|
||||
{--force : Jalankan pembersihan tanpa konfirmasi interaktif}
|
||||
{--include-he : Sertakan juga pembersihan timesheet alat berat & transfer unit}
|
||||
{--empty-trash : Kosongkan seluruh item di Tong Sampah}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Bersihkan seluruh riwayat transaksi uji coba (Timesheet LV, Riwayat Pos Gerbang, Log Aktivitas Admin) menjelang launching.';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(TrashService $trashService): int
|
||||
{
|
||||
$this->info('===============================================================');
|
||||
$this->info(' PEMBERSIHAN DATA UJI COBA (PRE-LAUNCH CLEAN SLATE) - RKM-KMH ');
|
||||
$this->info('===============================================================');
|
||||
$this->warn('Perintah ini akan membersihkan data riwayat pengujian:');
|
||||
$this->line(' - Riwayat Perjalanan LV / Perlintasan Gerbang (vehicle_activities)');
|
||||
$this->line(' - Riwayat Mutasi Lokasi Kendaraan (vehicle_location_histories)');
|
||||
$this->line(' - Log Riwayat Aktivitas Admin (admin_activity_logs)');
|
||||
|
||||
if ($this->option('include-he')) {
|
||||
$this->line(' - Timesheet Kendaraan Berat / HE (unit_support_timesheets)');
|
||||
$this->line(' - Riwayat Mobilisasi / Transfer Unit (unit_transfers)');
|
||||
}
|
||||
|
||||
if ($this->option('empty-trash')) {
|
||||
$this->line(' - Seluruh data di Tong Sampah (Recycle Bin)');
|
||||
}
|
||||
|
||||
$this->info("\nMaster Kendaraan, Data Karyawan, SIMPER, Pos Gerbang & Akun Pengguna TETAP 100% UTUH.");
|
||||
|
||||
if (!$this->option('force')) {
|
||||
if (!$this->confirm('Apakah Anda yakin ingin melanjutkan pembersihan riwayat uji coba ini?', false)) {
|
||||
$this->warn('Operasi pembersihan dibatalkan.');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
$this->output->write('Sedang membersihkan log riwayat uji coba... ');
|
||||
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
try {
|
||||
// 1. Bersihkan Catatan Perjalanan LV & Perlintasan Gerbang
|
||||
$activityCount = DB::table('vehicle_activities')->count();
|
||||
DB::table('vehicle_activities')->truncate();
|
||||
|
||||
// 2. Bersihkan Riwayat Lokasi Kendaraan
|
||||
$locationHistoryCount = DB::table('vehicle_location_histories')->count();
|
||||
DB::table('vehicle_location_histories')->truncate();
|
||||
|
||||
// 3. Bersihkan Log Aktivitas Admin
|
||||
$adminLogCount = DB::table('admin_activity_logs')->count();
|
||||
DB::table('admin_activity_logs')->truncate();
|
||||
|
||||
// 4. Bersihkan Timesheet HE & Transfer jika dipilih
|
||||
$heCount = 0;
|
||||
$transferCount = 0;
|
||||
if ($this->option('include-he')) {
|
||||
$heCount = DB::table('unit_support_timesheets')->count();
|
||||
DB::table('unit_support_timesheets')->truncate();
|
||||
|
||||
$transferCount = DB::table('unit_transfers')->count();
|
||||
DB::table('unit_transfers')->truncate();
|
||||
}
|
||||
|
||||
// 5. Reset status site kendaraan kembali ke default ('inside_site')
|
||||
DB::table('vehicles')->update([
|
||||
'site_status' => 'inside_site',
|
||||
'location_updated_at' => null,
|
||||
'location_updated_by' => null,
|
||||
'location_note' => null,
|
||||
]);
|
||||
|
||||
// 6. Kosongkan Tong Sampah jika diminta
|
||||
$trashCount = 0;
|
||||
if ($this->option('empty-trash')) {
|
||||
$trashCount = $trashService->emptyTrash();
|
||||
}
|
||||
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
$this->info("SELESAI!\n");
|
||||
$this->table(['Kategori Log Dibersihkan', 'Jumlah Data Terhapus'], [
|
||||
['Riwayat Perjalanan LV (vehicle_activities)', number_format($activityCount)],
|
||||
['Riwayat Mutasi Lokasi (vehicle_location_histories)', number_format($locationHistoryCount)],
|
||||
['Log Riwayat Aktivitas Admin (admin_activity_logs)', number_format($adminLogCount)],
|
||||
['Timesheet Alat Berat / HE', $this->option('include-he') ? number_format($heCount) : 'Dilewati'],
|
||||
['Riwayat Transfer Unit', $this->option('include-he') ? number_format($transferCount) : 'Dilewati'],
|
||||
['Tong Sampah (Recycle Bin)', $this->option('empty-trash') ? number_format($trashCount) : 'Dilewati'],
|
||||
]);
|
||||
|
||||
$this->info("\nSistem sekarang bersih dan siap digunakan untuk peluncuran resmi (Launching)! 🎉");
|
||||
return Command::SUCCESS;
|
||||
} catch (\Throwable $e) {
|
||||
Schema::enableForeignKeyConstraints();
|
||||
$this->error("\nTerjadi kesalahan: " . $e->getMessage());
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\User;
|
||||
@@ -105,6 +106,20 @@ class ImportSecurityGuardsCommand extends Command
|
||||
$updatedGuards++;
|
||||
}
|
||||
|
||||
// 3. Sinkronisasi Profil Master Personil / Karyawan (Data SIMPER)
|
||||
Employee::updateOrCreate(
|
||||
['nik' => $username],
|
||||
[
|
||||
'user_id' => $user->id,
|
||||
'name' => $p['name'],
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
'is_operator' => false,
|
||||
]
|
||||
);
|
||||
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,291 @@
|
||||
<?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'));
|
||||
$rows = [];
|
||||
$hasExcel = false;
|
||||
|
||||
if (file_exists($filePath)) {
|
||||
$this->info("Membaca berkas: {$filePath} ...");
|
||||
try {
|
||||
$rows = SimpleXlsxImporter::parse($filePath);
|
||||
$hasExcel = true;
|
||||
} catch (\Throwable $e) {
|
||||
$this->warn("Gagal membaca berkas Excel: " . $e->getMessage());
|
||||
}
|
||||
} else {
|
||||
$this->warn("Berkas Excel tidak ditemukan di: {$filePath}");
|
||||
$this->warn("Akan melanjutkan pembaruan kelompok operasional unit berdasarkan data master & pemetaan tipe...");
|
||||
}
|
||||
|
||||
$totalRows = count($rows);
|
||||
if ($hasExcel) {
|
||||
$this->info("Total baris terbaca: {$totalRows}");
|
||||
}
|
||||
|
||||
$updatedCount = 0;
|
||||
$createdCount = 0;
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
if ($hasExcel && $totalRows >= 2) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ namespace App\Http\Controllers\Admin;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminActivityLog;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AdminActivityLogController extends Controller
|
||||
@@ -54,4 +56,31 @@ class AdminActivityLogController extends Controller
|
||||
|
||||
return view('admin.activity_logs.index', compact('logs', 'stats'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kosongkan seluruh riwayat log aktivitas admin (Hanya Super Admin).
|
||||
*/
|
||||
public function clear(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
if (!$user || (!$user->hasRole('super_admin') && $user->role !== 'super_admin')) {
|
||||
abort(403, 'Akses ditolak. Hanya Super Admin yang berhak mengosongkan log aktivitas sistem.');
|
||||
}
|
||||
|
||||
$confirmed = false;
|
||||
if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'KOSONGKAN') {
|
||||
$confirmed = true;
|
||||
} elseif ($request->filled('password') && Hash::check($request->input('password'), $user->password)) {
|
||||
$confirmed = true;
|
||||
}
|
||||
|
||||
if (!$confirmed) {
|
||||
return back()->with('error', 'Konfirmasi keamanan tidak sesuai. Silakan ketik kata "KOSONGKAN" atau masukkan password Super Admin Anda.');
|
||||
}
|
||||
|
||||
$count = AdminActivityLog::count();
|
||||
AdminActivityLog::truncate();
|
||||
|
||||
return back()->with('success', "Seluruh rekaman log aktivitas admin berhasil dikosongkan ({$count} catatan log dibersihkan). Sistem siap untuk fase operasional baru.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\BackupLog;
|
||||
use App\Services\DatabaseBackupService;
|
||||
use App\Services\KmhConverterService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -19,7 +20,8 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
class BackupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected DatabaseBackupService $backupService
|
||||
protected DatabaseBackupService $backupService,
|
||||
protected KmhConverterService $converterService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -377,78 +379,23 @@ class BackupController extends Controller
|
||||
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.");
|
||||
} catch (\Throwable $e) {
|
||||
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
if ($request->ajax() || $request->wantsJson()) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,4 +426,128 @@ class BackupController extends Controller
|
||||
|
||||
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' => 'nullable|file',
|
||||
'server_filename' => 'nullable|string',
|
||||
]);
|
||||
|
||||
try {
|
||||
if ($request->filled('server_filename')) {
|
||||
$serverFile = $request->input('server_filename');
|
||||
if (!str_ends_with(strtolower($serverFile), '.kmh')) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
|
||||
], 422);
|
||||
}
|
||||
$metadata = $this->converterService->inspectServerFile($serverFile);
|
||||
} 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);
|
||||
}
|
||||
$metadata = $this->converterService->inspectUploadedFile($file);
|
||||
} else {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Silakan pilih berkas .kmh dari komputer atau server.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,24 +73,28 @@ class TrashController extends Controller
|
||||
*/
|
||||
public function forceDelete(string $category, int $id): RedirectResponse
|
||||
{
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
try {
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
|
||||
if (!$success) {
|
||||
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
|
||||
if (!$success) {
|
||||
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
|
||||
}
|
||||
|
||||
$catDefinitions = TrashService::getCategoryDefinitions();
|
||||
$label = $catDefinitions[$category]['label'] ?? $category;
|
||||
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Tong Sampah',
|
||||
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
|
||||
targetType: $category,
|
||||
targetId: $id
|
||||
);
|
||||
|
||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||
} catch (\Throwable $e) {
|
||||
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$catDefinitions = TrashService::getCategoryDefinitions();
|
||||
$label = $catDefinitions[$category]['label'] ?? $category;
|
||||
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Tong Sampah',
|
||||
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
|
||||
targetType: $category,
|
||||
targetId: $id
|
||||
);
|
||||
|
||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Services\ImageCompressionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
@@ -74,8 +75,8 @@ class UserController extends Controller
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'username' => ['required', 'string', 'max:50', 'unique:users,username'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
|
||||
'username' => ['required', 'string', 'max:50', Rule::unique('users', 'username')->whereNull('deleted_at')],
|
||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->whereNull('deleted_at')],
|
||||
'password' => ['required', 'string', 'min:6'],
|
||||
'role' => ['required', 'string', 'exists:roles,name'],
|
||||
'gate_id' => ['nullable', 'exists:gates,id'],
|
||||
@@ -102,15 +103,38 @@ class UserController extends Controller
|
||||
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
|
||||
}
|
||||
|
||||
$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,
|
||||
]);
|
||||
$user = User::withTrashed()
|
||||
->where('username', $validated['username'])
|
||||
->orWhere('email', $validated['email'])
|
||||
->first();
|
||||
|
||||
if ($user) {
|
||||
if ($user->trashed()) {
|
||||
$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
|
||||
$user->assignRole($validated['role']);
|
||||
@@ -141,7 +165,7 @@ class UserController extends Controller
|
||||
$defaultDivision = ($isGateOfficer || $isPgAdmin) ? 'Private Guard' : '-';
|
||||
$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 = [
|
||||
'user_id' => $user->id,
|
||||
'nik' => $user->username,
|
||||
@@ -154,6 +178,9 @@ class UserController extends Controller
|
||||
'photo_path' => $photoPath ?: $emp?->photo_path,
|
||||
];
|
||||
if ($emp) {
|
||||
if ($emp->trashed()) {
|
||||
$emp->restore();
|
||||
}
|
||||
$emp->update($empData);
|
||||
} else {
|
||||
Employee::create($empData);
|
||||
@@ -393,23 +420,29 @@ class UserController extends Controller
|
||||
$userRole = $user->role ?? '';
|
||||
$userId = $user->id;
|
||||
|
||||
$user->syncRoles([]);
|
||||
$user->delete();
|
||||
try {
|
||||
DB::transaction(function () use ($user) {
|
||||
$user->delete();
|
||||
});
|
||||
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
|
||||
} catch (\Throwable $e) {
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('error', 'Gagal menghapus pengguna: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -47,6 +47,18 @@ class LoginController extends Controller
|
||||
/** @var \App\Models\User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
// Proteksi: Cek apakah akun Petugas Satpam berstatus Nonaktif
|
||||
$guard = $user->securityGuard ?: \App\Models\SecurityGuard::where('user_id', $user->id)->first();
|
||||
if ($guard && ! $guard->is_active && ! $user->isSuperAdmin()) {
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return back()->withErrors([
|
||||
'username' => 'Akun Petugas Satpam Anda berstatus Nonaktif. Silakan hubungi Administrator Pos Gerbang (PG) untuk mengaktifkan kembali.',
|
||||
])->onlyInput('username');
|
||||
}
|
||||
|
||||
if ($request->session()->has('url.intended')) {
|
||||
return redirect()->intended()
|
||||
->with('success', "Selamat datang kembali, {$user->name}!");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers\Hse;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Carbon\Carbon;
|
||||
use App\Models\Employee;
|
||||
use App\Models\EmployeeSimper;
|
||||
use App\Models\SimperType;
|
||||
@@ -17,6 +18,7 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmployeeController extends Controller
|
||||
@@ -42,9 +44,10 @@ class EmployeeController extends Controller
|
||||
->take(5)
|
||||
->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();
|
||||
$simperLogs = Employee::where('is_operator', true)
|
||||
->with(['simpers.simperType'])
|
||||
->orderByRaw("CASE
|
||||
WHEN simper_expired_at IS NULL THEN 1
|
||||
WHEN simper_expired_at < ? THEN 0
|
||||
@@ -209,6 +212,7 @@ class EmployeeController extends Controller
|
||||
'Unit Kerja' => 20,
|
||||
'Divisi' => 20,
|
||||
'Status Driver' => 16,
|
||||
'Jenis Izin SIMPER' => 24,
|
||||
'Masa Berlaku SIMPER' => 22,
|
||||
'Status SIMPER' => 24,
|
||||
];
|
||||
@@ -221,6 +225,13 @@ class EmployeeController extends Controller
|
||||
$isDriver = $emp->is_operator;
|
||||
$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) {
|
||||
$statusText = 'Bukan Driver';
|
||||
} elseif (! $emp->simper_expired_at) {
|
||||
@@ -242,6 +253,7 @@ class EmployeeController extends Controller
|
||||
$emp->unit_kerja ?: '-',
|
||||
$emp->division ?: '-',
|
||||
$isDriver ? 'Driver' : 'Bukan Driver',
|
||||
$simperTypesText,
|
||||
$expDate,
|
||||
$statusText,
|
||||
];
|
||||
@@ -256,6 +268,7 @@ class EmployeeController extends Controller
|
||||
'left', // Unit Kerja
|
||||
'left', // Divisi
|
||||
'center', // Status Driver
|
||||
'center', // Jenis Izin SIMPER
|
||||
'center', // Masa Berlaku
|
||||
'center', // Status SIMPER
|
||||
];
|
||||
@@ -496,48 +509,94 @@ class EmployeeController extends Controller
|
||||
continue;
|
||||
}
|
||||
|
||||
$unitKerja = trim((string) ($colMap['unit_kerja'] !== null ? ($row[$colMap['unit_kerja']] ?? 'Umum') : 'Umum'));
|
||||
$division = trim((string) ($colMap['division'] !== null ? ($row[$colMap['division']] ?? '-') : '-'));
|
||||
$position = trim((string) ($colMap['position'] !== null ? ($row[$colMap['position']] ?? '-') : '-'));
|
||||
$employeeType = trim((string) ($colMap['employee_type'] !== null ? ($row[$colMap['employee_type']] ?? 'Karyawan') : 'Karyawan')) ?: 'Karyawan';
|
||||
$rawUnitKerja = $colMap['unit_kerja'] !== null ? trim((string) ($row[$colMap['unit_kerja']] ?? '')) : '';
|
||||
$rawDivision = $colMap['division'] !== null ? trim((string) ($row[$colMap['division']] ?? '')) : '';
|
||||
$rawPosition = $colMap['position'] !== null ? trim((string) ($row[$colMap['position']] ?? '')) : '';
|
||||
$rawEmployeeType = $colMap['employee_type'] !== null ? trim((string) ($row[$colMap['employee_type']] ?? '')) : '';
|
||||
$rawOperator = $colMap['is_operator'] !== null ? trim((string) ($row[$colMap['is_operator']] ?? '')) : '';
|
||||
$rawSimper = $colMap['simper_expired_at'] !== null ? trim((string) ($row[$colMap['simper_expired_at']] ?? '')) : '';
|
||||
|
||||
$unitKerja = $rawUnitKerja ?: 'Umum';
|
||||
$division = $rawDivision ?: '-';
|
||||
$position = $rawPosition ?: '-';
|
||||
$employeeType = $rawEmployeeType ?: 'Karyawan';
|
||||
|
||||
// Deteksi status driver (jika kolom ada dan berisi ya/driver)
|
||||
$operatorRaw = $colMap['is_operator'] !== null ? strtolower(trim((string) ($row[$colMap['is_operator']] ?? ''))) : '';
|
||||
$operatorRaw = strtolower($rawOperator);
|
||||
$isOperator = in_array($operatorRaw, ['ya', 'yes', '1', 'true', 'driver', 'operator', 'y']);
|
||||
|
||||
// Deteksi tanggal SIMPER
|
||||
$simperRaw = $colMap['simper_expired_at'] !== null ? trim((string) ($row[$colMap['simper_expired_at']] ?? '')) : '';
|
||||
$simperExpiredAt = $isOperator ? SimpleXlsxImporter::normalizeDate($simperRaw) : null;
|
||||
$simperExpiredAt = $isOperator ? SimpleXlsxImporter::normalizeDate($rawSimper) : null;
|
||||
|
||||
// 1. Sinkronisasi Akun User untuk login karyawan
|
||||
// 1. Sinkronisasi Akun User untuk login karyawan (gunakan withTrashed agar tidak bentrok dengan data di Tong Sampah)
|
||||
$cleanEmail = strtolower(str_replace(['-', ' '], '', $nik)) . '@kmh.co.id';
|
||||
$user = User::firstOrCreate(
|
||||
['username' => $nik],
|
||||
[
|
||||
$user = User::withTrashed()->where('username', $nik)->first();
|
||||
if ($user) {
|
||||
if ($user->trashed()) {
|
||||
$user->restore();
|
||||
}
|
||||
$user->update([
|
||||
'name' => $name,
|
||||
'role' => $user->role ?: 'employee',
|
||||
]);
|
||||
} else {
|
||||
if (User::withTrashed()->where('email', $cleanEmail)->exists()) {
|
||||
$cleanEmail = strtolower(str_replace(['-', ' '], '', $nik)) . '.' . uniqid() . '@kmh.co.id';
|
||||
}
|
||||
|
||||
$user = User::create([
|
||||
'username' => $nik,
|
||||
'name' => $name,
|
||||
'email' => $cleanEmail,
|
||||
'password' => Hash::make(config('auth.default_employee_password', '123456')),
|
||||
'role' => 'employee',
|
||||
]
|
||||
);
|
||||
]);
|
||||
}
|
||||
|
||||
if (!$user->hasRole('employee')) {
|
||||
$user->assignRole('employee');
|
||||
}
|
||||
|
||||
// 2. Simpan atau perbarui data master Employee
|
||||
$isExisting = Employee::where('nik', $nik)->first();
|
||||
// 2. Simpan atau perbarui data master Employee (gunakan withTrashed agar tidak duplikat dengan NIK di Tong Sampah)
|
||||
$isExisting = Employee::withTrashed()->where('nik', $nik)->first();
|
||||
if ($isExisting) {
|
||||
$isExisting->update([
|
||||
if ($isExisting->trashed()) {
|
||||
$isExisting->restore();
|
||||
}
|
||||
|
||||
$updateData = [
|
||||
'name' => $name,
|
||||
'employee_type' => $employeeType,
|
||||
'unit_kerja' => $unitKerja ?: 'Umum',
|
||||
'division' => $division ?: '-',
|
||||
'position' => $position ?: '-',
|
||||
'is_operator' => $isOperator,
|
||||
'simper_expired_at' => $simperExpiredAt,
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
];
|
||||
|
||||
// Perbarui kolom secara selektif jika pada berkas Excel terisi data baru
|
||||
if ($rawEmployeeType !== '') {
|
||||
$updateData['employee_type'] = $employeeType;
|
||||
}
|
||||
if ($rawUnitKerja !== '') {
|
||||
$updateData['unit_kerja'] = $unitKerja;
|
||||
} elseif (empty($isExisting->unit_kerja) || $isExisting->unit_kerja === '-') {
|
||||
$updateData['unit_kerja'] = 'Umum';
|
||||
}
|
||||
|
||||
if ($rawDivision !== '') {
|
||||
$updateData['division'] = $division;
|
||||
}
|
||||
|
||||
if ($rawPosition !== '') {
|
||||
$updateData['position'] = $position;
|
||||
}
|
||||
|
||||
if ($rawOperator !== '') {
|
||||
$updateData['is_operator'] = $isOperator;
|
||||
if ($rawSimper !== '' && $isOperator) {
|
||||
$updateData['simper_expired_at'] = $simperExpiredAt;
|
||||
}
|
||||
} elseif ($rawSimper !== '' && $isExisting->is_operator) {
|
||||
$updateData['simper_expired_at'] = SimpleXlsxImporter::normalizeDate($rawSimper);
|
||||
}
|
||||
|
||||
$isExisting->update($updateData);
|
||||
$updatedCount++;
|
||||
} else {
|
||||
Employee::create([
|
||||
@@ -580,7 +639,7 @@ class EmployeeController extends Controller
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$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'],
|
||||
'unit_kerja' => ['required', 'string'],
|
||||
'division' => ['required', 'string'],
|
||||
@@ -588,6 +647,10 @@ class EmployeeController extends Controller
|
||||
'is_operator' => ['required', 'in:1,0'],
|
||||
'simper_expired_at' => ['nullable', 'date'],
|
||||
'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.unique' => 'NIK sudah terdaftar dalam sistem.',
|
||||
@@ -601,6 +664,23 @@ class EmployeeController extends Controller
|
||||
$isOperator = (bool) $validated['is_operator'];
|
||||
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null;
|
||||
|
||||
// Validasi kustom penugasan SIMPER ketika driver aktif
|
||||
if ($isOperator && is_array($request->input('simper_assignments'))) {
|
||||
$today = Carbon::today()->toDateString();
|
||||
foreach ($request->input('simper_assignments') as $typeId => $data) {
|
||||
if (!empty($data['enabled'])) {
|
||||
$st = SimperType::find($typeId);
|
||||
$typeName = $st ? $st->name : "Tipe #{$typeId}";
|
||||
if (empty($data['expired_at'])) {
|
||||
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' wajib diisi ketika dicentang.");
|
||||
}
|
||||
if ($data['expired_at'] < $today) {
|
||||
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' tidak boleh tanggal lampau (minimal hari ini).");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$employeeType = $request->input('employee_type');
|
||||
if ($employeeType === '__CUSTOM__' && $request->filled('custom_employee_type')) {
|
||||
$employeeType = trim($request->input('custom_employee_type'));
|
||||
@@ -609,15 +689,24 @@ class EmployeeController extends Controller
|
||||
$employeeType = 'Karyawan';
|
||||
}
|
||||
|
||||
$user = User::firstOrCreate(
|
||||
['username' => $validated['nik']],
|
||||
[
|
||||
$user = User::withTrashed()->where('username', $validated['nik'])->first();
|
||||
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'],
|
||||
'email' => strtolower(str_replace(['-', ' '], '', $validated['nik'])) . '@kmh.co.id',
|
||||
'password' => Hash::make(config('auth.default_employee_password', '123456')),
|
||||
'role' => 'employee',
|
||||
]
|
||||
);
|
||||
]);
|
||||
}
|
||||
|
||||
if (!$user->hasRole('employee')) {
|
||||
$user->assignRole('employee');
|
||||
@@ -629,18 +718,36 @@ class EmployeeController extends Controller
|
||||
$user->update(['photo_path' => $photoPath]);
|
||||
}
|
||||
|
||||
$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,
|
||||
]);
|
||||
$employee = Employee::withTrashed()->where('nik', $validated['nik'])->first();
|
||||
if ($employee) {
|
||||
if ($employee->trashed()) {
|
||||
$employee->restore();
|
||||
}
|
||||
$employee->update([
|
||||
'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 ?? $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
|
||||
$this->syncEmployeeSimpers($employee, $request, $isOperator, $simperExpiredAt);
|
||||
@@ -696,6 +803,10 @@ class EmployeeController extends Controller
|
||||
'is_operator' => ['required', 'in:1,0'],
|
||||
'simper_expired_at' => ['nullable', 'date'],
|
||||
'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.',
|
||||
'name.required' => 'Nama lengkap wajib diisi.',
|
||||
@@ -705,6 +816,28 @@ class EmployeeController extends Controller
|
||||
$isOperator = (bool) $validated['is_operator'];
|
||||
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? $employee->simper_expired_at) : null;
|
||||
|
||||
// Validasi kustom penugasan SIMPER ketika driver aktif
|
||||
if ($isOperator && is_array($request->input('simper_assignments'))) {
|
||||
$today = Carbon::today()->toDateString();
|
||||
foreach ($request->input('simper_assignments') as $typeId => $data) {
|
||||
if (!empty($data['enabled'])) {
|
||||
$st = SimperType::find($typeId);
|
||||
$typeName = $st ? $st->name : "Tipe #{$typeId}";
|
||||
if (empty($data['expired_at'])) {
|
||||
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' wajib diisi ketika dicentang.");
|
||||
}
|
||||
if ($data['expired_at'] < $today) {
|
||||
// Cek apakah tanggal ini memang tanggal lama yang belum diubah oleh admin
|
||||
$existingSimper = $employee->simpers->firstWhere('simper_type_id', (int) $typeId);
|
||||
$isOldUnchanged = $existingSimper && $existingSimper->expired_at?->format('Y-m-d') === $data['expired_at'];
|
||||
if (!$isOldUnchanged) {
|
||||
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' tidak boleh tanggal lampau (minimal hari ini: {$today}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$employeeType = $request->input('employee_type');
|
||||
if ($employeeType === '__CUSTOM__' && $request->filled('custom_employee_type')) {
|
||||
$employeeType = trim($request->input('custom_employee_type'));
|
||||
@@ -755,26 +888,12 @@ class EmployeeController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus data personil / karyawan beserta izin SIMPER dan akun login terkait.
|
||||
* Hapus data personil / karyawan (Soft Delete masuk ke Tong Sampah).
|
||||
* Seluruh riwayat transaksi (Timesheet, Gate, P2H) tetap aman dan terhubung.
|
||||
*/
|
||||
public function destroy(int $id): RedirectResponse
|
||||
{
|
||||
$employee = Employee::with(['user', 'activities', 'p2hRecords', 'supportTimesheets'])->findOrFail($id);
|
||||
|
||||
// 1. Proteksi integritas relasi: pastikan tidak ada logbook perjalanan kendaraan
|
||||
if ($employee->activities()->exists()) {
|
||||
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah tercatat dalam riwayat logbook operasional kendaraan.");
|
||||
}
|
||||
|
||||
// 2. Proteksi integritas relasi: pastikan tidak ada data inspeksi P2H
|
||||
if ($employee->p2hRecords()->exists()) {
|
||||
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah memiliki formulir riwayat inspeksi P2H.");
|
||||
}
|
||||
|
||||
// 3. Proteksi integritas relasi: pastikan tidak ada data timesheet unit support
|
||||
if ($employee->supportTimesheets()->exists()) {
|
||||
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah tercatat dalam riwayat timesheet unit support.");
|
||||
}
|
||||
$employee = Employee::with(['user'])->findOrFail($id);
|
||||
|
||||
$empName = $employee->name;
|
||||
$empNik = $employee->nik;
|
||||
@@ -786,22 +905,24 @@ class EmployeeController extends Controller
|
||||
// Berkas foto tidak dihapus saat soft delete agar foto tetap ada jika dipulihkan dari tong sampah.
|
||||
// Berkas baru dihapus permanen ketika dilakukan 'Hapus Permanen' (force delete) di TrashService.
|
||||
|
||||
// Hapus data karyawan (relasi employee_simpers otomatis cascade terhapus)
|
||||
// Hapus data karyawan (soft delete - dipindahkan ke Tong Sampah)
|
||||
$employee->delete();
|
||||
|
||||
// Hapus akun login User terkait jika perannya murni hanya karyawan (bukan admin)
|
||||
// Nonaktifkan / soft delete akun login User terkait jika perannya murni hanya karyawan (bukan admin)
|
||||
if ($user && $user->role === 'employee' && ! $user->hasAnyRole(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer'])) {
|
||||
$user->syncRoles([]);
|
||||
$user->delete();
|
||||
}
|
||||
});
|
||||
|
||||
$message = "Data personil '{$empName}' ({$empNik}) berhasil dihapus dan dipindahkan ke Tong Sampah. Seluruh riwayat operasional masa lalu tetap tersimpan utuh.";
|
||||
|
||||
// Jika request berasal dari halaman edit terpisah, arahkan kembali ke index
|
||||
if (url()->previous() === route('hse.employees.edit', $id)) {
|
||||
return redirect()->route('hse.employees.index')->with('success', "Data karyawan '{$empName}' ({$empNik}) berhasil dihapus dari sistem.");
|
||||
return redirect()->route('hse.employees.index')->with('success', $message);
|
||||
}
|
||||
|
||||
return back()->with('success', "Data karyawan '{$empName}' ({$empNik}) berhasil dihapus dari sistem.");
|
||||
return back()->with('success', $message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -810,7 +931,8 @@ class EmployeeController extends Controller
|
||||
private function syncEmployeeSimpers(Employee $employee, Request $request, bool $isOperator, ?string $fallbackDate): void
|
||||
{
|
||||
if (! $isOperator) {
|
||||
$employee->simpers()->delete();
|
||||
$employee->simpers()->forceDelete();
|
||||
$employee->update(['simper_expired_at' => null]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -821,20 +943,30 @@ class EmployeeController extends Controller
|
||||
$maxExpiredAt = null;
|
||||
|
||||
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'])) {
|
||||
$expDate = $data['expired_at'];
|
||||
$simperNum = ! empty($data['simper_number']) ? trim($data['simper_number']) : ('SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT));
|
||||
|
||||
EmployeeSimper::updateOrCreate(
|
||||
['employee_id' => $employee->id, 'simper_type_id' => $typeId],
|
||||
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
|
||||
['employee_id' => $employee->id, 'simper_type_id' => (int) $typeId],
|
||||
[
|
||||
'simper_number' => $simperNum,
|
||||
'expired_at' => $expDate,
|
||||
'status' => 'active',
|
||||
'deleted_at' => null,
|
||||
]
|
||||
);
|
||||
|
||||
if ($simper->trashed()) {
|
||||
$simper->restore();
|
||||
}
|
||||
|
||||
$activeTypeIds[] = (int) $typeId;
|
||||
|
||||
if (! $maxExpiredAt || $expDate > $maxExpiredAt) {
|
||||
@@ -843,26 +975,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)
|
||||
->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) {
|
||||
// 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');
|
||||
if ($lvTypeId) {
|
||||
EmployeeSimper::updateOrCreate(
|
||||
$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' => $fallbackDate,
|
||||
'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;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\VehicleActivity;
|
||||
@@ -159,19 +160,23 @@ class GateInspectionController extends Controller
|
||||
public function approve(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$currentGuard = $user ? $user->securityGuard : null;
|
||||
$guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null);
|
||||
$guard = $user ? ($user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first() ?: SecurityGuard::where('name', $user->name)->first() ?: SecurityGuard::where('badge_id', $user->username)->first()) : null;
|
||||
|
||||
if (!$guardId) {
|
||||
$request->validate([
|
||||
'security_guard_id' => ['required', 'exists:security_guards,id'],
|
||||
], [
|
||||
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam yang melakukan pemeriksaan fisik.',
|
||||
'security_guard_id.exists' => 'Petugas Satpam yang dipilih tidak valid dalam sistem.',
|
||||
]);
|
||||
$guardId = $request->input('security_guard_id');
|
||||
if (!$guard && $user) {
|
||||
$guard = SecurityGuard::firstOrCreate(
|
||||
['user_id' => $user->id],
|
||||
[
|
||||
'badge_id' => $user->username ?: ('PG-' . str_pad($user->id, 3, '0', STR_PAD_LEFT)),
|
||||
'name' => $user->name,
|
||||
'team' => 1,
|
||||
'gate_id' => session('active_gate_id') ?: Gate::first()?->id,
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$guardId = $guard?->id ?: ($request->input('security_guard_id') ?: SecurityGuard::value('id'));
|
||||
|
||||
$activity = VehicleActivity::with(['vehicle', 'gate'])->findOrFail($id);
|
||||
|
||||
if ($activity->validation_status !== 'pending') {
|
||||
@@ -179,6 +184,10 @@ class GateInspectionController extends Controller
|
||||
}
|
||||
|
||||
$guard = SecurityGuard::find($guardId);
|
||||
if ($guard && ! $guard->is_active && ! ($user && $user->isSuperAdmin())) {
|
||||
return back()->with('error', 'Aksi Ditolak: Petugas Satpam berstatus Nonaktif tidak diizinkan memvalidasi aktivitas pos gerbang.');
|
||||
}
|
||||
|
||||
$guardName = $guard?->name ?? ($user?->name ?? 'Petugas Pos Gerbang');
|
||||
|
||||
DB::transaction(function () use ($guardId, $guardName, $activity, $user) {
|
||||
@@ -237,24 +246,34 @@ class GateInspectionController extends Controller
|
||||
public function reject(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$currentGuard = $user ? $user->securityGuard : null;
|
||||
$guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null);
|
||||
$guard = $user ? ($user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first() ?: SecurityGuard::where('name', $user->name)->first() ?: SecurityGuard::where('badge_id', $user->username)->first()) : null;
|
||||
|
||||
if (!$guardId) {
|
||||
$request->validate([
|
||||
'security_guard_id' => ['required', 'exists:security_guards,id'],
|
||||
], [
|
||||
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam.',
|
||||
]);
|
||||
$guardId = $request->input('security_guard_id');
|
||||
if (!$guard && $user) {
|
||||
$guard = SecurityGuard::firstOrCreate(
|
||||
['user_id' => $user->id],
|
||||
[
|
||||
'badge_id' => $user->username ?: ('PG-' . str_pad($user->id, 3, '0', STR_PAD_LEFT)),
|
||||
'name' => $user->name,
|
||||
'team' => 1,
|
||||
'gate_id' => session('active_gate_id') ?: Gate::first()?->id,
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$guardId = $guard?->id ?: ($request->input('security_guard_id') ?: SecurityGuard::value('id'));
|
||||
|
||||
$request->validate([
|
||||
'rejection_note' => ['required', 'string', 'max:500'],
|
||||
], [
|
||||
'rejection_note.required' => 'Alasan penolakan wajib diisi.',
|
||||
]);
|
||||
|
||||
$guard = SecurityGuard::find($guardId);
|
||||
if ($guard && ! $guard->is_active && ! ($user && $user->isSuperAdmin())) {
|
||||
return back()->with('error', 'Aksi Ditolak: Petugas Satpam berstatus Nonaktif tidak diizinkan memvalidasi aktivitas pos gerbang.');
|
||||
}
|
||||
|
||||
$activity = VehicleActivity::with('vehicle')->findOrFail($id);
|
||||
|
||||
if ($activity->validation_status !== 'pending') {
|
||||
@@ -268,6 +287,15 @@ class GateInspectionController extends Controller
|
||||
'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.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
@@ -258,9 +259,23 @@ class SecurityGuardController extends Controller
|
||||
]);
|
||||
|
||||
// 3. Otomatis buat / sinkronkan profil Employee untuk Satpam (Divisi: Private Guard, Jabatan: Anggota)
|
||||
Employee::firstOrCreate(
|
||||
['nik' => $badgeId],
|
||||
[
|
||||
$guardEmp = Employee::withTrashed()->where('nik', $badgeId)->first();
|
||||
if ($guardEmp) {
|
||||
if ($guardEmp->trashed()) {
|
||||
$guardEmp->restore();
|
||||
}
|
||||
$guardEmp->update([
|
||||
'user_id' => $user->id,
|
||||
'name' => $request->input('name'),
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => $guardEmp->unit_kerja ?: 'Private Guard',
|
||||
'division' => ($guardEmp->division && $guardEmp->division !== '-') ? $guardEmp->division : 'Private Guard',
|
||||
'position' => ($guardEmp->position && $guardEmp->position !== '-') ? $guardEmp->position : 'Anggota',
|
||||
'is_operator' => false,
|
||||
]);
|
||||
} else {
|
||||
Employee::create([
|
||||
'nik' => $badgeId,
|
||||
'user_id' => $user->id,
|
||||
'name' => $request->input('name'),
|
||||
'employee_type' => 'Karyawan',
|
||||
@@ -268,35 +283,52 @@ class SecurityGuardController extends Controller
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
'is_operator' => false,
|
||||
]
|
||||
);
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
return back()->with('success', "Petugas Satpam {$request->input('name')} (ID: {$request->input('badge_id')}) berhasil didaftarkan.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Perbarui data Satpam (Nama, Regu, Penempatan Pos, dan Password opsional).
|
||||
* Perbarui data Satpam (ID Satpam, Nama, Regu, Penempatan Pos, dan Password opsional).
|
||||
*/
|
||||
public function update(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$guard = SecurityGuard::with('user')->findOrFail($id);
|
||||
|
||||
$newBadgeId = strtoupper(trim((string) $request->input('badge_id')));
|
||||
$request->merge(['badge_id' => $newBadgeId]);
|
||||
|
||||
$emp = Employee::where('user_id', $guard->user_id)->orWhere('nik', $guard->badge_id)->first();
|
||||
|
||||
$request->validate([
|
||||
'badge_id' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:50',
|
||||
Rule::unique('security_guards', 'badge_id')->ignore($guard->id),
|
||||
Rule::unique('users', 'username')->ignore($guard->user_id),
|
||||
Rule::unique('employees', 'nik')->ignore($emp?->id),
|
||||
],
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'team' => ['required', 'integer', 'in:1,2,3'],
|
||||
'gate_id' => ['nullable', 'exists:gates,id'],
|
||||
'password' => ['nullable', 'string', 'min:4'],
|
||||
], [
|
||||
'badge_id.required' => 'ID Satpam wajib diisi.',
|
||||
'badge_id.unique' => 'ID Satpam / NIK ini sudah digunakan oleh petugas/karyawan lain.',
|
||||
'name.required' => 'Nama lengkap Satpam wajib diisi.',
|
||||
'team.required' => 'Silakan pilih Regu Satpam (1, 2, atau 3).',
|
||||
'password.min' => 'Password minimal terdiri dari 4 karakter.',
|
||||
]);
|
||||
|
||||
DB::transaction(function () use ($request, $guard) {
|
||||
DB::transaction(function () use ($request, $guard, $newBadgeId, $emp) {
|
||||
$oldBadgeId = $guard->badge_id;
|
||||
$gateId = $request->has('gate_id') ? ($request->input('gate_id') ?: null) : $guard->gate_id;
|
||||
|
||||
$guard->update([
|
||||
'badge_id' => $newBadgeId,
|
||||
'name' => $request->input('name'),
|
||||
'team' => (int) $request->input('team'),
|
||||
'gate_id' => $gateId,
|
||||
@@ -305,9 +337,14 @@ class SecurityGuardController extends Controller
|
||||
if ($guard->user) {
|
||||
$userData = [
|
||||
'name' => $request->input('name'),
|
||||
'username' => $newBadgeId,
|
||||
'gate_id' => $gateId,
|
||||
];
|
||||
|
||||
if ($guard->user->email === strtolower((string) $oldBadgeId) . '@kmh.co.id') {
|
||||
$userData['email'] = strtolower($newBadgeId) . '@kmh.co.id';
|
||||
}
|
||||
|
||||
if ($request->filled('password')) {
|
||||
$userData['password'] = Hash::make($request->input('password'));
|
||||
}
|
||||
@@ -316,9 +353,9 @@ class SecurityGuardController extends Controller
|
||||
}
|
||||
|
||||
// Sinkronkan nama dan profil Employee Satpam
|
||||
$emp = Employee::where('user_id', $guard->user_id)->orWhere('nik', $guard->badge_id)->first();
|
||||
if ($emp) {
|
||||
$emp->update([
|
||||
'nik' => $newBadgeId,
|
||||
'name' => $guard->name,
|
||||
'unit_kerja' => $emp->unit_kerja ?: 'Private Guard',
|
||||
'division' => ($emp->division && $emp->division !== '-') ? $emp->division : 'Private Guard',
|
||||
@@ -327,7 +364,7 @@ class SecurityGuardController extends Controller
|
||||
}
|
||||
});
|
||||
|
||||
return back()->with('success', "Data petugas Satpam {$guard->name} berhasil diperbarui.");
|
||||
return back()->with('success', "Data petugas Satpam {$guard->name} ({$newBadgeId}) berhasil diperbarui.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -735,8 +735,11 @@ class P2hInspectionController extends Controller
|
||||
]);
|
||||
|
||||
// Jika unit dinyatakan aman dan sebelumnya breakdown karena review, status unit disetujui operasi
|
||||
if (!$record->hasDefects() && $record->vehicle->status === 'Breakdown') {
|
||||
$record->vehicle->update(['status' => 'Operation']);
|
||||
if (!$record->hasDefects() && $record->vehicle && $record->vehicle->status === 'Breakdown') {
|
||||
$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.");
|
||||
|
||||
@@ -134,15 +134,24 @@ class SupportTimesheetController extends Controller
|
||||
$timesheets = $query->paginate($perPage)->withQueryString();
|
||||
|
||||
// KPI Ringkasan Data Terfilter
|
||||
$statsQuery = clone $this->getFilteredQuery($request);
|
||||
$totalEntries = (clone $statsQuery)->count();
|
||||
$totalOperatingHours = (clone $statsQuery)->sum('operating_hours');
|
||||
$totalFuelLiters = (clone $statsQuery)->sum('fuel_liters');
|
||||
$activeUnitsCount = (clone $statsQuery)->distinct('vehicle_id')->count('vehicle_id');
|
||||
$breakdownCount = (clone $statsQuery)->where('status', 'Breakdown')->count();
|
||||
$statsItems = (clone $this->getFilteredQuery($request))->get();
|
||||
$totalEntries = $statsItems->count();
|
||||
$totalOperatingHours = 0.0;
|
||||
foreach ($statsItems as $item) {
|
||||
$totalOperatingHours += (float) ($item->effective_operating_hours ?? 0);
|
||||
}
|
||||
$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()
|
||||
->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) {
|
||||
$q->whereNotNull('parent_id')
|
||||
->orWhereDoesntHave('units');
|
||||
@@ -168,8 +177,37 @@ class SupportTimesheetController extends Controller
|
||||
}
|
||||
|
||||
$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) {
|
||||
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
|
||||
? (float) $validated['end_meter']
|
||||
: 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';
|
||||
$updaterName = auth()->user()?->name ?? 'Admin QMA';
|
||||
$timesheetNo = null;
|
||||
@@ -325,6 +382,25 @@ class SupportTimesheetController extends Controller
|
||||
'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)
|
||||
$updateData = [
|
||||
'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,
|
||||
]);
|
||||
|
||||
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 = [];
|
||||
foreach ($timesheets as $idx => $ts) {
|
||||
$endMeter = $ts->effective_end_meter;
|
||||
$opHours = $ts->effective_operating_hours;
|
||||
|
||||
$rows[] = [
|
||||
$idx + 1,
|
||||
$ts->timesheet_no,
|
||||
@@ -523,8 +612,8 @@ class SupportTimesheetController extends Controller
|
||||
$ts->operator?->nik ?: '-',
|
||||
$ts->meter_type,
|
||||
number_format($ts->start_meter, 2, ',', '.'),
|
||||
number_format($ts->end_meter, 2, ',', '.'),
|
||||
number_format($ts->operating_hours, 2, ',', '.'),
|
||||
$endMeter !== null ? number_format($endMeter, 2, ',', '.') : '-',
|
||||
$opHours !== null ? number_format($opHours, 2, ',', '.') : '-',
|
||||
number_format($ts->standby_hours, 2, ',', '.'),
|
||||
number_format($ts->breakdown_hours, 2, ',', '.'),
|
||||
$ts->location,
|
||||
@@ -606,6 +695,9 @@ class SupportTimesheetController extends Controller
|
||||
|
||||
$rows = [];
|
||||
foreach ($timesheets as $idx => $ts) {
|
||||
$endMeter = $ts->effective_end_meter;
|
||||
$opHours = $ts->effective_operating_hours;
|
||||
|
||||
$rows[] = [
|
||||
$idx + 1,
|
||||
$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->shift,
|
||||
number_format($ts->start_meter, 1, ',', '.'),
|
||||
number_format($ts->end_meter, 1, ',', '.'),
|
||||
number_format($ts->operating_hours, 1, ',', '.') . ' ' . $ts->meter_type,
|
||||
$endMeter !== null ? number_format($endMeter, 1, ',', '.') : '-',
|
||||
($opHours !== null ? number_format($opHours, 1, ',', '.') : '-') . ' ' . $ts->meter_type,
|
||||
$ts->location,
|
||||
$ts->status,
|
||||
];
|
||||
|
||||
@@ -143,12 +143,48 @@ class UnitTransferController extends Controller
|
||||
->map(fn($group) => $group->count())
|
||||
->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()
|
||||
->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')
|
||||
->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
|
||||
$drivers = Employee::where('is_operator', true)
|
||||
->orderBy('name')
|
||||
@@ -166,6 +202,7 @@ class UnitTransferController extends Controller
|
||||
'originLocations',
|
||||
'selectedOriginLocation',
|
||||
'transporterUnits',
|
||||
'transporterLocations',
|
||||
'drivers',
|
||||
'locationSuggestions',
|
||||
'defaultDocNumber',
|
||||
@@ -186,6 +223,8 @@ class UnitTransferController extends Controller
|
||||
'to_site_status' => ['required', 'in:inside_site,outside_site'],
|
||||
'description' => ['nullable', 'string', 'max:2000'],
|
||||
'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_unit_name' => ['nullable', 'string', 'max:255'],
|
||||
'transporter_driver_id' => ['nullable', 'integer', 'exists:employees,id'],
|
||||
@@ -221,14 +260,25 @@ class UnitTransferController extends Controller
|
||||
$fromLocation = $vehicle->location ?: ($validated['from_location'] ?? 'Site Kerinci');
|
||||
$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
|
||||
$transporterUnitName = !empty($validated['transporter_unit_name']) ? trim($validated['transporter_unit_name']) : null;
|
||||
if (empty($transporterUnitName) && !empty($validated['transporter_vehicle_id'])) {
|
||||
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']);
|
||||
if ($transporterType === 'internal' && !empty($transporterVehicleId)) {
|
||||
$transporterVeh = Vehicle::find($transporterVehicleId);
|
||||
if ($transporterVeh) {
|
||||
$plate = $transporterVeh->license_plate ? " ({$transporterVeh->license_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
|
||||
@@ -262,7 +312,9 @@ class UnitTransferController extends Controller
|
||||
'description' => !empty($validated['description']) ? trim($validated['description']) : null,
|
||||
'reported_by' => $reportedBy,
|
||||
'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_driver_id' => $validated['transporter_driver_id'] ?? null,
|
||||
'transporter_driver_name' => $transporterDriverName,
|
||||
@@ -285,6 +337,9 @@ class UnitTransferController extends Controller
|
||||
|
||||
// 3. Catat di audit log riwayat pergerakan unit (VehicleLocationHistory)
|
||||
$transporterSummary = $transporterUnitName ? " Pengangkut: {$transporterUnitName}" : "";
|
||||
if ($transporterOriginLocation) {
|
||||
$transporterSummary .= " [Asal: {$transporterOriginLocation}]";
|
||||
}
|
||||
if ($transporterDriverName) {
|
||||
$transporterSummary .= " (Driver: {$transporterDriverName})";
|
||||
}
|
||||
@@ -305,9 +360,9 @@ class UnitTransferController extends Controller
|
||||
'recorded_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
// 4. Jika opsi perbarui posisi truk pengangkut aktif
|
||||
if ($updateTransporter && !empty($validated['transporter_vehicle_id'])) {
|
||||
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']);
|
||||
// 4. Jika opsi perbarui posisi truk pengangkut aktif (Hanya armada internal)
|
||||
if ($transporterType === 'internal' && $updateTransporter && !empty($transporterVehicleId)) {
|
||||
$transporterVeh = Vehicle::find($transporterVehicleId);
|
||||
if ($transporterVeh && $transporterVeh->id !== $vehicle->id) {
|
||||
$transporterNote = $docNumber
|
||||
? "Armada Pengangkut BAST {$docNumber} untuk {$vehicle->code} ke {$toLocation}"
|
||||
@@ -320,9 +375,10 @@ class UnitTransferController extends Controller
|
||||
'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}) transfer internal ke {$toLocation}";
|
||||
|
||||
VehicleLocationHistory::create([
|
||||
'vehicle_id' => $transporterVeh->id,
|
||||
'site_status' => $validated['to_site_status'],
|
||||
|
||||
@@ -277,56 +277,15 @@ class VehicleController extends Controller
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
$query = Vehicle::unitSupportCategories()->withCount('units');
|
||||
|
||||
// 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');
|
||||
$selectedGroup = $request->input('group');
|
||||
$selectedType = $request->input('type');
|
||||
|
||||
// Master data daftar divisi perusahaan (gabungan standar + data existing di Employee & Vehicle)
|
||||
$standardDivisions = collect([
|
||||
@@ -353,17 +312,364 @@ class VehicleController extends Controller
|
||||
->values()
|
||||
->all();
|
||||
|
||||
// Daftar semua kode Heavy Equipment untuk validasi unik langsung di form
|
||||
$existingCodes = Vehicle::unitSupports()->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
|
||||
// Master data daftar kelompok operasional, kategori & tipe alat berat
|
||||
$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(
|
||||
'level',
|
||||
'groups',
|
||||
'vehicles',
|
||||
'totalSupport',
|
||||
'totalGroups',
|
||||
'totalUnits',
|
||||
'totalOperation',
|
||||
'totalStandby',
|
||||
'totalBreakdown',
|
||||
'groupMetadata',
|
||||
'groupTypesMap',
|
||||
'availableLocations',
|
||||
'availableBrands',
|
||||
'availableGroups',
|
||||
'availableCategories',
|
||||
'availableTypes',
|
||||
'availableDivisions',
|
||||
'existingCodes'
|
||||
));
|
||||
@@ -378,6 +684,19 @@ class VehicleController extends Controller
|
||||
|
||||
$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')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
@@ -455,6 +774,19 @@ class VehicleController extends Controller
|
||||
{
|
||||
$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')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
@@ -494,6 +826,19 @@ class VehicleController extends Controller
|
||||
{
|
||||
$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')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
@@ -744,6 +1089,19 @@ class VehicleController extends Controller
|
||||
$category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id);
|
||||
$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')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
@@ -821,6 +1179,19 @@ class VehicleController extends Controller
|
||||
$category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id);
|
||||
$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')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
@@ -986,7 +1357,7 @@ class VehicleController extends Controller
|
||||
$rules = [
|
||||
'code' => ['required', 'string', 'max:50', 'unique:vehicles,code'],
|
||||
'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'],
|
||||
'serial_number' => ['nullable', 'string', 'max:100'],
|
||||
'ownership' => ['nullable', 'string', 'max:150'],
|
||||
@@ -1001,12 +1372,14 @@ class VehicleController extends Controller
|
||||
// Atribut opsional spesifik Heavy Equipment (Kendaraan Berat)
|
||||
if ($category === 'unit_support') {
|
||||
$rules = array_merge($rules, [
|
||||
'operational_group' => ['required', 'string', 'max:50'],
|
||||
'unit_type' => ['required', 'string', 'max:100'],
|
||||
'unit_category' => ['nullable', 'string', 'max:100'],
|
||||
'unit_type' => ['nullable', 'string', 'max:100'],
|
||||
'brand' => ['nullable', 'string', 'max:100'],
|
||||
'model_number' => ['nullable', 'string', 'max:100'],
|
||||
'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)],
|
||||
'location' => ['nullable', 'string', 'max:150'],
|
||||
'site_status' => ['nullable', 'in:inside_site,outside_site'],
|
||||
'fuel_consumption' => ['nullable', 'numeric', 'min:0'],
|
||||
'silo_document' => ['nullable', 'string', 'max:150'],
|
||||
'stnk_document' => ['nullable', 'string', 'max:150'],
|
||||
@@ -1018,6 +1391,8 @@ class VehicleController extends Controller
|
||||
$validated = $request->validate($rules, [
|
||||
'code.required' => 'Kode kendaraan wajib diisi.',
|
||||
'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.',
|
||||
'current_km.required' => 'Nilai KM / HM awal wajib diisi.',
|
||||
'status.required' => 'Status operasional wajib dipilih.',
|
||||
@@ -1026,6 +1401,37 @@ class VehicleController extends Controller
|
||||
if ($category === 'unit_support') {
|
||||
$validated['status'] = $validated['status'] ?? 'Operation';
|
||||
$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');
|
||||
@@ -1039,19 +1445,20 @@ class VehicleController extends Controller
|
||||
$vehicle = Vehicle::create($validated);
|
||||
|
||||
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->code;
|
||||
$template = P2hTemplate::firstOrCreate(
|
||||
['code' => $vehicle->code],
|
||||
['code' => $templateCode],
|
||||
[
|
||||
'name' => $vehicle->unit_category ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk kategori {$vehicle->brand_type} (Kode: {$vehicle->code}).",
|
||||
'name' => $vehicle->unit_category ?: ($vehicle->unit_type ?: $vehicle->brand_type),
|
||||
'description' => "Template form inspeksi P2H resmi untuk " . ($vehicle->unit_category ?: $vehicle->brand_type) . " (Kode: {$templateCode}).",
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
$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.");
|
||||
}
|
||||
@@ -1064,24 +1471,38 @@ class VehicleController extends Controller
|
||||
{
|
||||
$vehicle = Vehicle::findOrFail($id);
|
||||
$oldCode = $vehicle->code;
|
||||
$newCode = strtoupper(trim($request->input('code')));
|
||||
$newCode = strtoupper(trim($request->input('code', $vehicle->code)));
|
||||
|
||||
// Pra-proses untuk unit support: auto-sintesis brand_type dan default current_km
|
||||
if ($vehicle->isUnitSupport() || $request->input('category') === 'unit_support') {
|
||||
if (!$request->filled('brand_type')) {
|
||||
$brandPart = trim(($request->input('brand') ?? '') . ' ' . ($request->input('model_number') ?? ''));
|
||||
$synthesizedBrand = $brandPart ?: ($vehicle->brand_type ?: ($request->input('unit_type') ?: $vehicle->code));
|
||||
$request->merge(['brand_type' => $synthesizedBrand]);
|
||||
}
|
||||
if (!$request->filled('current_km')) {
|
||||
$request->merge(['current_km' => $vehicle->current_km ?? 0]);
|
||||
}
|
||||
}
|
||||
|
||||
$rules = [
|
||||
'code' => ['required', 'string', 'max:50', Rule::unique('vehicles', 'code')->ignore($vehicle->id)],
|
||||
'category' => ['required', 'in:light_vehicle,unit_support'],
|
||||
'brand_type' => ['required', 'string', 'max:150'],
|
||||
'brand_type' => ['nullable', 'string', 'max:150'],
|
||||
'license_plate' => ['nullable', 'string', 'max:30'],
|
||||
'serial_number' => ['nullable', 'string', 'max:100'],
|
||||
'ownership' => ['nullable', 'string', 'max:150'],
|
||||
'division' => ['nullable', 'string', 'max:100'],
|
||||
'status' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'numeric', 'min:0'],
|
||||
'status' => ['required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => ['nullable', 'numeric', 'min:0'],
|
||||
'operational_group' => ['nullable', 'string', 'max:50'],
|
||||
'unit_category' => ['nullable', 'string', 'max:100'],
|
||||
'unit_type' => ['nullable', 'string', 'max:100'],
|
||||
'brand' => ['nullable', 'string', 'max:100'],
|
||||
'model_number' => ['nullable', 'string', 'max:100'],
|
||||
'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)],
|
||||
'location' => ['nullable', 'string', 'max:150'],
|
||||
'site_status' => ['nullable', 'in:inside_site,outside_site'],
|
||||
'fuel_consumption' => ['nullable', 'numeric', 'min:0'],
|
||||
'silo_document' => ['nullable', 'string', 'max:150'],
|
||||
'stnk_document' => ['nullable', 'string', 'max:150'],
|
||||
@@ -1095,10 +1516,41 @@ class VehicleController extends Controller
|
||||
$validated = $request->validate($rules, [
|
||||
'code.required' => 'Kode kendaraan wajib diisi.',
|
||||
'code.unique' => 'Kode sudah ada, silakan gunakan kode lain.',
|
||||
'brand_type.required' => 'Merek dan tipe wajib diisi.',
|
||||
'current_km.required' => 'Nilai KM / HM wajib diisi.',
|
||||
]);
|
||||
|
||||
if ($vehicle->isUnitSupport() || ($validated['category'] ?? '') === 'unit_support') {
|
||||
$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')) {
|
||||
ImageCompressionService::deleteIfExists($vehicle->photo_path);
|
||||
$validated['photo_path'] = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75);
|
||||
|
||||
@@ -27,6 +27,12 @@ class CheckRole
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Proteksi: Cek apakah petugas satpam berstatus Nonaktif
|
||||
$guard = $user->securityGuard ?: \App\Models\SecurityGuard::where('user_id', $user->id)->first();
|
||||
if ($guard && ! $guard->is_active) {
|
||||
abort(403, 'Akses Ditolak: Akun Petugas Satpam Anda berstatus Nonaktif. Silakan hubungi Administrator PG.');
|
||||
}
|
||||
|
||||
// Cek via kolom role string atau Spatie hasAnyRole
|
||||
if (in_array($userRole, $roles) || (method_exists($user, 'hasAnyRole') && $user->hasAnyRole($roles))) {
|
||||
return $next($request);
|
||||
|
||||
@@ -32,7 +32,7 @@ class EmployeeSimper extends Model
|
||||
|
||||
public function employee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class);
|
||||
return $this->belongsTo(Employee::class)->withTrashed();
|
||||
}
|
||||
|
||||
public function simperType(): BelongsTo
|
||||
|
||||
@@ -49,7 +49,7 @@ class P2hRecord extends Model
|
||||
|
||||
public function employee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class);
|
||||
return $this->belongsTo(Employee::class)->withTrashed();
|
||||
}
|
||||
|
||||
public function template(): BelongsTo
|
||||
|
||||
@@ -98,6 +98,7 @@ class SimperType extends Model
|
||||
protected $appends = [
|
||||
'scopes',
|
||||
'category_scope_display',
|
||||
'short_scope_display',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -184,6 +185,34 @@ class SimperType extends Model
|
||||
return implode(', ', $formatted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Teks ringkas pendek untuk badge di UI (maksimal 2 kategori + counter jika panjang).
|
||||
*/
|
||||
public function getShortScopeDisplayAttribute(): string
|
||||
{
|
||||
$scopes = $this->scopes;
|
||||
|
||||
if (empty($scopes) || in_array(self::SCOPE_ALL, $scopes, true)) {
|
||||
return 'UNIVERSAL';
|
||||
}
|
||||
|
||||
if (count($scopes) === 1 && $scopes[0] === self::SCOPE_LIGHT_VEHICLE) {
|
||||
return 'LV';
|
||||
}
|
||||
|
||||
$formatted = array_map(function ($s) {
|
||||
if ($s === self::SCOPE_LIGHT_VEHICLE) return 'LV';
|
||||
if ($s === self::SCOPE_ALL) return 'Universal';
|
||||
return strtoupper(str_replace('_', ' ', $s));
|
||||
}, $scopes);
|
||||
|
||||
if (count($formatted) > 2) {
|
||||
return $formatted[0] . ', ' . $formatted[1] . ' (+' . (count($formatted) - 2) . ')';
|
||||
}
|
||||
|
||||
return implode(', ', $formatted);
|
||||
}
|
||||
|
||||
public function employeeSimpers(): HasMany
|
||||
{
|
||||
return $this->hasMany(EmployeeSimper::class);
|
||||
|
||||
@@ -45,6 +45,11 @@ class UnitSupportTimesheet extends Model
|
||||
'fuel_liters' => 'decimal:2',
|
||||
];
|
||||
|
||||
protected $appends = [
|
||||
'effective_end_meter',
|
||||
'effective_operating_hours',
|
||||
];
|
||||
|
||||
public function vehicle(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Vehicle::class);
|
||||
@@ -52,7 +57,7 @@ class UnitSupportTimesheet extends Model
|
||||
|
||||
public function operator(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class, 'operator_id');
|
||||
return $this->belongsTo(Employee::class, 'operator_id')->withTrashed();
|
||||
}
|
||||
|
||||
public function createdByUser(): BelongsTo
|
||||
@@ -60,6 +65,53 @@ class UnitSupportTimesheet extends Model
|
||||
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).
|
||||
* Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records.
|
||||
|
||||
@@ -24,7 +24,9 @@ class UnitTransfer extends Model
|
||||
'description',
|
||||
'reported_by',
|
||||
'user_id',
|
||||
'transporter_type',
|
||||
'transporter_vehicle_id',
|
||||
'transporter_origin_location',
|
||||
'transporter_unit_name',
|
||||
'transporter_driver_id',
|
||||
'transporter_driver_name',
|
||||
@@ -66,7 +68,7 @@ class UnitTransfer extends Model
|
||||
*/
|
||||
public function transporterDriver(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class, 'transporter_driver_id');
|
||||
return $this->belongsTo(Employee::class, 'transporter_driver_id')->withTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+18
-9
@@ -33,17 +33,26 @@ class User extends Authenticatable
|
||||
});
|
||||
|
||||
static::deleting(function (User $user) {
|
||||
if ($user->employee) {
|
||||
if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
$employee = $user->employee ?: Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
$guard = $user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first();
|
||||
|
||||
if ($user->isForceDeleting()) {
|
||||
$employeeTrashed = $employee ?: Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
if ($employeeTrashed && ($employeeTrashed->activities()->exists() || $employeeTrashed->p2hRecords()->exists() || $employeeTrashed->supportTimesheets()->exists())) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
}
|
||||
$user->employee->delete();
|
||||
}
|
||||
if ($user->securityGuard) {
|
||||
if ($user->securityGuard->activities()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
$guardTrashed = $guard ?: SecurityGuard::withTrashed()->where('user_id', $user->id)->first();
|
||||
if ($guardTrashed && $guardTrashed->activities()->exists()) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
}
|
||||
} else {
|
||||
// Soft delete: cukup cascade soft delete data employee & securityGuard jika ada dan belum terhapus
|
||||
if ($employee && ! $employee->trashed()) {
|
||||
$employee->delete();
|
||||
}
|
||||
if ($guard && ! $guard->trashed()) {
|
||||
$guard->delete();
|
||||
}
|
||||
$user->securityGuard->delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ class Vehicle extends Model
|
||||
'photo_path',
|
||||
'unit_category',
|
||||
'unit_type',
|
||||
'operational_group',
|
||||
'brand',
|
||||
'model_number',
|
||||
'production_year',
|
||||
|
||||
@@ -56,7 +56,7 @@ class VehicleActivity extends Model
|
||||
|
||||
public function driver(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class, 'driver_id');
|
||||
return $this->belongsTo(Employee::class, 'driver_id')->withTrashed();
|
||||
}
|
||||
|
||||
public function gate(): BelongsTo
|
||||
|
||||
@@ -149,8 +149,8 @@ class DatabaseBackupService
|
||||
*/
|
||||
public function createKmhBackup(?array $selectedTables = null, bool $includeMedia = false, ?string $customFilename = null): string
|
||||
{
|
||||
@set_time_limit(600);
|
||||
@ini_set('memory_limit', '512M');
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
if (!class_exists('ZipArchive')) {
|
||||
throw new RuntimeException('Ekstensi PHP ZipArchive diperlukan untuk memaketkan arsip.');
|
||||
@@ -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 = [
|
||||
'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)',
|
||||
@@ -249,7 +212,6 @@ class DatabaseBackupService
|
||||
'database' => $database,
|
||||
'table_count' => count($targetTables),
|
||||
'tables' => $targetTables,
|
||||
'table_details' => $tableDetails,
|
||||
'has_media' => $includeMedia,
|
||||
'laravel_version' => app()->version(),
|
||||
'php_version' => PHP_VERSION,
|
||||
@@ -275,215 +237,13 @@ 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).
|
||||
*/
|
||||
public function restore(string $backupFilenameOrPath): void
|
||||
{
|
||||
@set_time_limit(600);
|
||||
@ini_set('memory_limit', '512M');
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
$filePath = File::exists($backupFilenameOrPath)
|
||||
? $backupFilenameOrPath
|
||||
@@ -914,55 +674,67 @@ class DatabaseBackupService
|
||||
|
||||
fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n");
|
||||
|
||||
$query = DB::table($tableName);
|
||||
|
||||
// Pastikan data yang berada di tong sampah (soft-deleted) tidak bocor ke dalam data backup
|
||||
$sql = "SELECT * FROM `{$tableName}`";
|
||||
if (Schema::hasColumn($tableName, 'deleted_at')) {
|
||||
$query->whereNull('deleted_at');
|
||||
$sql .= " WHERE `deleted_at` IS NULL";
|
||||
}
|
||||
|
||||
$totalRows = $query->count();
|
||||
try {
|
||||
$stmt = $pdo->query($sql);
|
||||
} catch (\Throwable $e) {
|
||||
$stmt = null;
|
||||
}
|
||||
|
||||
if ($totalRows === 0) {
|
||||
fwrite($handle, "-- (Tabel kosong)\n\n");
|
||||
if (!$stmt) {
|
||||
fwrite($handle, "-- (Tabel kosong atau gagal dibaca)\n\n");
|
||||
return;
|
||||
}
|
||||
|
||||
$query->orderBy(DB::raw('1'))->chunk(200, function ($rows) use ($handle, $pdo, $tableName) {
|
||||
if ($rows->isEmpty()) return;
|
||||
$batch = [];
|
||||
$batchSize = 500;
|
||||
$columnsStr = null;
|
||||
$hasData = false;
|
||||
|
||||
$columns = array_keys((array) $rows->first());
|
||||
$escapedColumns = array_map(fn ($c) => "`{$c}`", $columns);
|
||||
$columnsStr = implode(', ', $escapedColumns);
|
||||
|
||||
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
|
||||
|
||||
$rowCount = count($rows);
|
||||
$i = 0;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$i++;
|
||||
$values = [];
|
||||
|
||||
foreach ((array) $row as $val) {
|
||||
if (is_null($val)) {
|
||||
$values[] = 'NULL';
|
||||
} elseif (is_int($val) || is_float($val)) {
|
||||
$values[] = (string) $val;
|
||||
} elseif (is_bool($val)) {
|
||||
$values[] = $val ? '1' : '0';
|
||||
} else {
|
||||
$values[] = $pdo->quote((string) $val);
|
||||
}
|
||||
}
|
||||
|
||||
$line = ' (' . implode(', ', $values) . ')';
|
||||
$line .= ($i === $rowCount) ? ";\n" : ",\n";
|
||||
fwrite($handle, $line);
|
||||
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
|
||||
$hasData = true;
|
||||
if ($columnsStr === null) {
|
||||
$columns = array_keys($row);
|
||||
$escapedColumns = array_map(fn ($c) => "`{$c}`", $columns);
|
||||
$columnsStr = implode(', ', $escapedColumns);
|
||||
}
|
||||
});
|
||||
|
||||
fwrite($handle, "\n");
|
||||
$values = [];
|
||||
foreach ($row as $val) {
|
||||
if (is_null($val)) {
|
||||
$values[] = 'NULL';
|
||||
} elseif (is_int($val) || is_float($val)) {
|
||||
$values[] = (string) $val;
|
||||
} elseif (is_bool($val)) {
|
||||
$values[] = $val ? '1' : '0';
|
||||
} else {
|
||||
$values[] = $pdo->quote((string) $val);
|
||||
}
|
||||
}
|
||||
|
||||
$batch[] = ' (' . implode(', ', $values) . ')';
|
||||
|
||||
if (count($batch) >= $batchSize) {
|
||||
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
|
||||
fwrite($handle, implode(",\n", $batch) . ";\n");
|
||||
$batch = [];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($batch)) {
|
||||
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
|
||||
fwrite($handle, implode(",\n", $batch) . ";\n");
|
||||
}
|
||||
|
||||
if (!$hasData) {
|
||||
fwrite($handle, "-- (Tabel kosong)\n\n");
|
||||
} else {
|
||||
fwrite($handle, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,773 @@
|
||||
<?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 sudah tersimpan di server.
|
||||
* Tidak memerlukan pengunggahan ulang berkas dari PC (sangat cepat & ramah kuota).
|
||||
*
|
||||
* @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 inspectServerFile(string $filename): array
|
||||
{
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
$backupDir = $this->backupService->getBackupDirectory();
|
||||
$realPath = $backupDir . DIRECTORY_SEPARATOR . basename($filename);
|
||||
if (!is_file($realPath)) {
|
||||
throw new RuntimeException("Berkas arsip '{$filename}' tidak ditemukan di penyimpanan server.");
|
||||
}
|
||||
|
||||
$kmhContent = file_get_contents($realPath);
|
||||
if ($kmhContent === false) {
|
||||
throw new RuntimeException("Gagal membaca berkas .kmh dari server.");
|
||||
}
|
||||
|
||||
$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'] ?? [];
|
||||
|
||||
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(filemtime($realPath));
|
||||
|
||||
$tempDir = storage_path('app/temp_converter');
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
|
||||
// Bersihkan file sementara yang lebih tua dari 1 jam (3600 detik)
|
||||
foreach (File::files($tempDir) as $f) {
|
||||
if ((time() - $f->getMTime()) > 3600) {
|
||||
@unlink($f->getPathname());
|
||||
}
|
||||
}
|
||||
|
||||
$token = bin2hex(random_bytes(16));
|
||||
$cachedKmhPath = $tempDir . '/' . $token . '.kmh';
|
||||
copy($realPath, $cachedKmhPath);
|
||||
|
||||
return [
|
||||
'token' => $token,
|
||||
'filename' => basename($filename),
|
||||
'size_human' => $this->backupService->formatBytes((int) filesize($realPath)),
|
||||
'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'] ?? config('database.connections.' . config('database.default') . '.database', 'rkm_kmh'),
|
||||
'has_media' => (bool) ($manifest['has_media'] ?? false),
|
||||
];
|
||||
} finally {
|
||||
$zip->close();
|
||||
@unlink($tempZipPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
$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 1 jam (3600 detik)
|
||||
foreach (File::files($tempDir) as $f) {
|
||||
if ((time() - $f->getMTime()) > 3600) {
|
||||
@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
|
||||
{
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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->Ln(6);
|
||||
$sigY = $pdf->GetY();
|
||||
$pdf->SetFont('Arial', 'B', 7.5);
|
||||
$pdf->SetTextColor(15, 23, 42);
|
||||
$colWidth = 75;
|
||||
$x1 = 20;
|
||||
$x2 = 115;
|
||||
|
||||
// Kolom 1: Operator Lapangan
|
||||
$pdf->SetXY(15, $sigY);
|
||||
$pdf->Cell(56, 4, 'Diperiksa Oleh (Operator):', 0, 1, 'C');
|
||||
$pdf->SetXY(15, $sigY + 16);
|
||||
$pdf->SetXY($x1, $sigY);
|
||||
$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->Cell(56, 4, 'Diverifikasi Oleh (Admin QMA):', 0, 1, 'C');
|
||||
$pdf->SetXY(77, $sigY + 16);
|
||||
$pdf->Cell($colWidth, 4, 'Diperiksa Oleh (Operator):', 0, 1, 'C');
|
||||
|
||||
$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->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';
|
||||
$pdf->Cell(56, 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');
|
||||
$pdf->Cell($colWidth, 4, '( ' . $valName . ' )', 0, 1, 'C');
|
||||
|
||||
// Kolom 3: Pengawas K3 / HSE
|
||||
$pdf->SetXY(139, $sigY);
|
||||
$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->SetXY($x2, $sigY + 22.5);
|
||||
$pdf->SetFont('Arial', '', 7.5);
|
||||
$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');
|
||||
}
|
||||
|
||||
@@ -104,14 +104,15 @@ class SimperPdfExporter extends FPDF
|
||||
$this->SetFont('Arial', 'B', 7.5);
|
||||
|
||||
$cols = [
|
||||
['NO', 10, 'C'],
|
||||
['NIK', 30, 'C'],
|
||||
['NAMA KARYAWAN', 62, 'L'],
|
||||
['JABATAN', 45, 'L'],
|
||||
['UNIT / DIVISI', 40, 'L'],
|
||||
['STATUS DRIVER', 26, 'C'],
|
||||
['MASA BERLAKU', 26, 'C'],
|
||||
['STATUS SIMPER', 28, 'C'],
|
||||
['NO', 8, 'C'],
|
||||
['NIK', 25, 'C'],
|
||||
['NAMA KARYAWAN', 52, 'L'],
|
||||
['JABATAN', 38, 'L'],
|
||||
['UNIT / DIVISI', 34, 'L'],
|
||||
['DRIVER', 22, 'C'],
|
||||
['JENIS SIMPER', 34, 'C'],
|
||||
['MASA BERLAKU', 25, 'C'],
|
||||
['STATUS', 29, 'C'],
|
||||
];
|
||||
|
||||
foreach ($cols as $col) {
|
||||
@@ -180,32 +181,42 @@ class SimperPdfExporter extends FPDF
|
||||
|
||||
// Kolom 1: No
|
||||
$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)
|
||||
$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)
|
||||
$nama = mb_strimwidth($emp->name, 0, 36, '...');
|
||||
$pdf->Cell(62, 6.5, ' ' . $nama, 'B', 0, 'L', $fill);
|
||||
// Kolom 3: Nama Lengkap (Bold, Truncate jika > 30 karakter)
|
||||
$nama = mb_strimwidth($emp->name, 0, 30, '...');
|
||||
$pdf->Cell(52, 6.5, ' ' . $nama, 'B', 0, 'L', $fill);
|
||||
|
||||
// Kolom 4: Jabatan
|
||||
$pdf->SetFont('Arial', '', 7.5);
|
||||
$jabatan = mb_strimwidth($emp->position ?: '-', 0, 26, '...');
|
||||
$pdf->Cell(45, 6.5, ' ' . $jabatan, 'B', 0, 'L', $fill);
|
||||
$jabatan = mb_strimwidth($emp->position ?: '-', 0, 22, '...');
|
||||
$pdf->Cell(38, 6.5, ' ' . $jabatan, 'B', 0, 'L', $fill);
|
||||
|
||||
// Kolom 5: Unit / Divisi
|
||||
$unit = mb_strimwidth($emp->unit_kerja ?: ($emp->division ?: '-'), 0, 24, '...');
|
||||
$pdf->Cell(40, 6.5, ' ' . $unit, 'B', 0, 'L', $fill);
|
||||
$unit = mb_strimwidth($emp->unit_kerja ?: ($emp->division ?: '-'), 0, 20, '...');
|
||||
$pdf->Cell(34, 6.5, ' ' . $unit, 'B', 0, 'L', $fill);
|
||||
|
||||
// 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
|
||||
$pdf->Cell(26, 6.5, $expDate, 'B', 0, 'C', $fill);
|
||||
// Kolom 7: Rincian Jenis SIMPER
|
||||
$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') {
|
||||
$pdf->SetTextColor(4, 120, 87); // #047857 Green
|
||||
} elseif ($statusText === 'Segera Habis') {
|
||||
@@ -216,7 +227,7 @@ class SimperPdfExporter extends FPDF
|
||||
$pdf->SetTextColor(100, 116, 139); // #64748b Slate
|
||||
}
|
||||
$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();
|
||||
$fill = ! $fill;
|
||||
|
||||
@@ -16,7 +16,7 @@ class SimpleXlsxExporter
|
||||
* @param array $alignments Optional per-column alignment: 'center' or 'left'
|
||||
* @return string Raw zip content
|
||||
*/
|
||||
public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = []): string
|
||||
public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = [], ?string $sheetName = null): string
|
||||
{
|
||||
$numCols = count($headers);
|
||||
$lastColLetter = self::colLetter($numCols);
|
||||
@@ -143,10 +143,11 @@ class SimpleXlsxExporter
|
||||
</cellXfs>
|
||||
</styleSheet>';
|
||||
|
||||
$cleanSheetName = htmlspecialchars(mb_substr($sheetName ?: 'Data', 0, 31), ENT_XML1);
|
||||
$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">
|
||||
<sheets>
|
||||
<sheet name="Data SIMPER" sheetId="1" r:id="rId1" />
|
||||
<sheet name="' . $cleanSheetName . '" sheetId="1" r:id="rId1" />
|
||||
</sheets>
|
||||
</workbook>';
|
||||
|
||||
|
||||
@@ -378,6 +378,36 @@ class TrashService
|
||||
EmployeeSimper::onlyTrashed()
|
||||
->where('employee_id', $item->id)
|
||||
->restore();
|
||||
|
||||
$user = User::onlyTrashed()->where('id', $item->user_id)->orWhere('username', $item->nik)->first();
|
||||
if ($user) {
|
||||
$user->restore();
|
||||
if ($user->role && ! $user->hasRole($user->role)) {
|
||||
$role = \Spatie\Permission\Models\Role::where('name', $user->role)->first();
|
||||
if ($role) {
|
||||
$user->assignRole($role);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($item instanceof User) {
|
||||
if ($item->role && ! $item->hasRole($item->role)) {
|
||||
$role = \Spatie\Permission\Models\Role::where('name', $item->role)->first();
|
||||
if ($role) {
|
||||
$item->assignRole($role);
|
||||
}
|
||||
}
|
||||
|
||||
$employee = Employee::onlyTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
|
||||
if ($employee) {
|
||||
$employee->restore();
|
||||
}
|
||||
|
||||
$guard = SecurityGuard::onlyTrashed()->where('user_id', $item->id)->first();
|
||||
if ($guard) {
|
||||
$guard->restore();
|
||||
}
|
||||
}
|
||||
|
||||
if ($item instanceof SimperType) {
|
||||
@@ -422,6 +452,11 @@ class TrashService
|
||||
}
|
||||
|
||||
if ($item instanceof Employee) {
|
||||
// Cegah hapus permanen jika karyawan memiliki riwayat operasional (menjaga integritas data)
|
||||
if ($item->activities()->exists() || $item->p2hRecords()->exists() || $item->supportTimesheets()->exists()) {
|
||||
throw new \RuntimeException("Karyawan '{$item->name}' ({$item->nik}) memiliki riwayat transaksi aktif dan tidak dapat dihapus permanen untuk menjaga integritas data.");
|
||||
}
|
||||
|
||||
EmployeeSimper::withTrashed()
|
||||
->where('employee_id', $item->id)
|
||||
->forceDelete();
|
||||
@@ -448,6 +483,14 @@ class TrashService
|
||||
}
|
||||
|
||||
if ($item instanceof User) {
|
||||
$employee = Employee::withTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
|
||||
if ($employee && ($employee->activities()->exists() || $employee->p2hRecords()->exists() || $employee->supportTimesheets()->exists())) {
|
||||
throw new \RuntimeException("User '{$item->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H dan tidak dapat dihapus permanen untuk menjaga integritas data.");
|
||||
}
|
||||
$guard = SecurityGuard::withTrashed()->where('user_id', $item->id)->first();
|
||||
if ($guard && $guard->activities()->exists()) {
|
||||
throw new \RuntimeException("User '{$item->name}' memiliki riwayat data validasi pos gerbang dan tidak dapat dihapus permanen untuk menjaga integritas data.");
|
||||
}
|
||||
ImageCompressionService::deleteIfExists($item->photo_path ?? null);
|
||||
}
|
||||
|
||||
@@ -469,8 +512,12 @@ class TrashService
|
||||
$model = $categories[$category]['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
$this->forceDeleteItem($category, $item->id);
|
||||
$totalDeleted++;
|
||||
try {
|
||||
$this->forceDeleteItem($category, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
return $totalDeleted;
|
||||
}
|
||||
@@ -480,8 +527,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$totalDeleted++;
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,8 +561,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
|
||||
foreach ($expiredItems as $item) {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$prunedCount++;
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$prunedCount++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
};
|
||||
+29
@@ -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');
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\User;
|
||||
@@ -86,6 +87,20 @@ class SecurityGuardSeeder extends Seeder
|
||||
} else {
|
||||
$updatedGuards++;
|
||||
}
|
||||
|
||||
// 3. Sinkronisasi Profil Master Personil / Karyawan (Data SIMPER)
|
||||
Employee::updateOrCreate(
|
||||
['nik' => $username],
|
||||
[
|
||||
'user_id' => $user->id,
|
||||
'name' => $p['name'],
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
'is_operator' => false,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$this->command?->info("Selesai! {$insertedGuards} satpam baru, {$updatedGuards} satpam diperbarui, {$usersCreated} akun login user dibuat (password default: 123456).");
|
||||
|
||||
@@ -9,6 +9,11 @@ server {
|
||||
index index.php index.html;
|
||||
|
||||
client_max_body_size 500M;
|
||||
client_body_buffer_size 1M;
|
||||
client_body_timeout 3600s;
|
||||
client_header_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
keepalive_timeout 3600s;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
@@ -56,7 +61,8 @@ server {
|
||||
fastcgi_hide_header X-Powered-By;
|
||||
fastcgi_buffers 16 16k;
|
||||
fastcgi_buffer_size 32k;
|
||||
fastcgi_read_timeout 300;
|
||||
fastcgi_read_timeout 3600;
|
||||
fastcgi_send_timeout 3600;
|
||||
}
|
||||
|
||||
location ~ /\.(?!well-known).* {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
upload_max_filesize = 500M
|
||||
post_max_size = 500M
|
||||
memory_limit = 1024M
|
||||
max_execution_time = 600
|
||||
max_input_time = 600
|
||||
max_execution_time = 3600
|
||||
max_input_time = 3600
|
||||
date.timezone = Asia/Jakarta
|
||||
expose_php = Off
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"resources/css/app.css": {
|
||||
"file": "assets/app-CmcfnDoH.css",
|
||||
"file": "assets/app-C1c9fBHF.css",
|
||||
"src": "resources/css/app.css",
|
||||
"isEntry": true,
|
||||
"name": "app",
|
||||
|
||||
@@ -16,7 +16,14 @@
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-bold bg-indigo-50 text-indigo-700 border border-indigo-200">
|
||||
@if(auth()->user()?->hasRole('super_admin') || auth()->user()?->role === 'super_admin')
|
||||
<button type="button" onclick="openClearLogsModal()"
|
||||
class="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-bold text-rose-700 bg-rose-50 hover:bg-rose-100 border border-rose-200 transition cursor-pointer shadow-2xs">
|
||||
<i class="fa-regular fa-trash-can text-sm"></i>
|
||||
<span>Kosongkan Log</span>
|
||||
</button>
|
||||
@endif
|
||||
<span class="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-bold bg-indigo-50 text-indigo-700 border border-indigo-200">
|
||||
<i class="fa-solid fa-shield-halved"></i>
|
||||
<span>Rekaman Keamanan Sistem</span>
|
||||
</span>
|
||||
@@ -518,10 +525,19 @@
|
||||
document.getElementById('logDetailModal').classList.add('hidden');
|
||||
}
|
||||
|
||||
function openClearLogsModal() {
|
||||
document.getElementById('clearLogsModal')?.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function closeClearLogsModal() {
|
||||
document.getElementById('clearLogsModal')?.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Tutup saat klik di luar modal / Escape key
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') {
|
||||
closeLogDetailModal();
|
||||
closeClearLogsModal();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -530,5 +546,50 @@
|
||||
closeLogDetailModal();
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('clearLogsModal')?.addEventListener('click', function(e) {
|
||||
if (e.target === this) {
|
||||
closeClearLogsModal();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@if(auth()->user()?->hasRole('super_admin') || auth()->user()?->role === 'super_admin')
|
||||
<!-- Modal Konfirmasi Kosongkan Log Aktivitas -->
|
||||
<div id="clearLogsModal" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
|
||||
<div class="relative w-full max-w-md bg-white rounded-3xl shadow-2xl border border-slate-100 overflow-hidden transform transition-all animate-in fade-in zoom-in-95 duration-150">
|
||||
<div class="p-6 text-center">
|
||||
<div class="w-14 h-14 rounded-2xl bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100 text-2xl shadow-inner">
|
||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||
</div>
|
||||
<h3 class="text-lg font-black text-slate-900 tracking-tight">Kosongkan Riwayat Log Admin?</h3>
|
||||
<p class="text-xs text-slate-500 mt-2 leading-relaxed">
|
||||
Tindakan ini akan menghapus <strong>seluruh catatan riwayat aktivitas admin</strong> saat ini. Sangat disarankan dilakukan sebelum sistem resmi di-launching agar riwayat bersih.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="{{ route('admin.activity_logs.clear') }}" class="px-6 pb-6 space-y-4">
|
||||
@csrf
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5 text-left">
|
||||
Konfirmasi Keamanan (Ketik <span class="text-rose-600 font-mono">KOSONGKAN</span> atau Password Super Admin):
|
||||
</label>
|
||||
<input type="text" name="confirmation" placeholder="Ketik KOSONGKAN"
|
||||
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:border-rose-500 focus:ring-2 focus:ring-rose-500/20 font-mono transition">
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end space-x-2 pt-2">
|
||||
<button type="button" onclick="closeClearLogsModal()"
|
||||
class="px-4 py-2 rounded-xl text-xs font-bold text-slate-600 hover:bg-slate-100 transition cursor-pointer">
|
||||
Batal
|
||||
</button>
|
||||
<button type="submit"
|
||||
class="px-4 py-2 rounded-xl text-xs font-bold text-white bg-rose-600 hover:bg-rose-700 transition cursor-pointer shadow-sm">
|
||||
<i class="fa-regular fa-trash-can mr-1.5"></i> Ya, Kosongkan Semua Log
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
@endsection
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@
|
||||
<div>
|
||||
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5">
|
||||
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span>
|
||||
<span>Matriks Peran & Hak Akses Pengguna</span>
|
||||
<span>Matriks Role & Hak Akses Pengguna</span>
|
||||
<!-- Tooltip Super Admin Priviledge -->
|
||||
<div class="relative group/tip inline-flex">
|
||||
<button type="button"
|
||||
@@ -75,167 +75,294 @@
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- Ringkasan Role Cards -->
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
|
||||
@foreach($roles as $role)
|
||||
@php
|
||||
$isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']);
|
||||
$badgeColor = match($role->name) {
|
||||
'super_admin' => 'bg-indigo-600 text-white',
|
||||
'hse_admin' => 'bg-emerald-600 text-white',
|
||||
'qma_admin' => 'bg-blue-600 text-white',
|
||||
'pg_admin' => 'bg-purple-600 text-white',
|
||||
'gate_officer' => 'bg-amber-600 text-white',
|
||||
default => 'bg-slate-700 text-white'
|
||||
};
|
||||
@endphp
|
||||
<div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm flex flex-col justify-between">
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span class="w-2.5 h-2.5 rounded-full {{ $badgeColor }}"></span>
|
||||
@if(!$isCoreRole)
|
||||
<button type="button"
|
||||
onclick='openDeleteRoleModal({{ $role->id }}, "{{ $role->name }}")'
|
||||
class="text-slate-400 hover:text-rose-600 transition"
|
||||
title="Hapus Role Kustom">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
<!-- Selector Tab Role Interaktif (Compact & User Friendly) -->
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs font-bold uppercase tracking-wider text-slate-500 flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-id-badge text-indigo-600"></i>
|
||||
<span>Pilih Peran Pengguna (Role):</span>
|
||||
</span>
|
||||
<span class="text-[11px] text-slate-400">Pilih salah satu peran untuk melihat dan mengatur izinnya</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
|
||||
@foreach($roles as $role)
|
||||
@php
|
||||
$isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']);
|
||||
$dotColor = match($role->name) {
|
||||
'super_admin' => 'bg-indigo-600',
|
||||
'hse_admin' => 'bg-emerald-600',
|
||||
'qma_admin' => 'bg-blue-600',
|
||||
'pg_admin' => 'bg-purple-600',
|
||||
'gate_officer' => 'bg-amber-600',
|
||||
default => 'bg-slate-700'
|
||||
};
|
||||
@endphp
|
||||
<button type="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
|
||||
<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
|
||||
</div>
|
||||
<h2 class="text-xs font-bold text-slate-800 capitalize">{{ str_replace('_', ' ', $role->name) }}</h2>
|
||||
<p class="text-[10px] text-slate-400 mt-0.5 font-mono">{{ $role->name }}</p>
|
||||
</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
|
||||
</button>
|
||||
@endforeach
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Matriks Role & Permissions Table -->
|
||||
<!-- Kontainer Panel Hak Akses Per Role (Hanya Role Aktif yang Ditampilkan) -->
|
||||
<div class="space-y-6">
|
||||
@foreach($roles as $role)
|
||||
<div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden">
|
||||
<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">
|
||||
<div class="flex items-center gap-3">
|
||||
<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">
|
||||
@php
|
||||
$rolePermNames = $role->permissions->pluck('name')->toArray();
|
||||
$isSuperAdmin = $role->name === 'super_admin';
|
||||
@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>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-sm font-bold text-slate-900 capitalize flex items-center gap-2">
|
||||
<span>Peran: {{ str_replace('_', ' ', $role->name) }}</span>
|
||||
@if($role->name === 'super_admin')
|
||||
<div class="relative group/satip inline-flex">
|
||||
<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">
|
||||
<i class="fa-solid fa-crown text-[8px]"></i>
|
||||
<span>AKSES LENGKAP</span>
|
||||
<i class="fa-solid fa-circle-info text-[9px] text-indigo-500"></i>
|
||||
</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">
|
||||
<div class="flex items-start gap-2.5">
|
||||
<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">
|
||||
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>
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<h2 class="text-base font-extrabold text-slate-800 capitalize">
|
||||
Pengaturan Hak Akses: {{ str_replace('_', ' ', $role->name) }}
|
||||
</h2>
|
||||
@if($isSuperAdmin)
|
||||
<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">
|
||||
<i class="fa-solid fa-crown text-[9px]"></i>
|
||||
<span>BYPASS PENUH</span>
|
||||
</span>
|
||||
@else
|
||||
<span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-indigo-100 text-indigo-800 border border-indigo-200">
|
||||
Peran: <code class="font-mono">{{ $role->name }}</code>
|
||||
</span>
|
||||
@endif
|
||||
</h2>
|
||||
<p class="text-[11px] text-slate-400">Atur centang hak akses menu yang diizinkan untuk peran pengguna ini.</p>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
@if($role->name !== 'super_admin')
|
||||
<button type="submit"
|
||||
form="form-role-{{ $role->id }}"
|
||||
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">
|
||||
<i class="fa-solid fa-floppy-disk"></i>
|
||||
<span>Simpan Hak Akses</span>
|
||||
</button>
|
||||
@endif
|
||||
<!-- Tombol Aksi & Simpan -->
|
||||
<div class="flex items-center gap-2 self-end md:self-auto flex-wrap">
|
||||
@if(!$isSuperAdmin)
|
||||
<button type="button"
|
||||
onclick="toggleAllRolePermissions({{ $role->id }}, true)"
|
||||
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="Centang semua hak akses untuk peran ini">
|
||||
<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>
|
||||
|
||||
@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 }}"
|
||||
action="{{ route('admin.roles.permissions.update', $role->id) }}"
|
||||
method="POST"
|
||||
class="p-5">
|
||||
@csrf
|
||||
|
||||
@php
|
||||
$rolePermNames = $role->permissions->pluck('name')->toArray();
|
||||
@endphp
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div id="module-grid-{{ $role->id }}" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
@foreach($modules as $moduleKey => $module)
|
||||
<div class="bg-slate-50/70 border border-slate-200/60 rounded-xl p-4 space-y-3">
|
||||
<h3 class="text-xs font-bold text-slate-800 flex items-center justify-between pb-2 border-b border-slate-200/60">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<i class="{{ $module['icon'] }} text-indigo-600 text-xs"></i>
|
||||
<span>{{ $module['name'] }}</span>
|
||||
</span>
|
||||
<span class="text-[10px] text-slate-400 font-semibold">{{ count($module['permissions']) }} hak akses</span>
|
||||
</h3>
|
||||
|
||||
<div class="space-y-2">
|
||||
@foreach($module['permissions'] as $permKey => $permMeta)
|
||||
@php
|
||||
$isChecked = $role->name === 'super_admin' || in_array($permKey, $rolePermNames);
|
||||
@endphp
|
||||
<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">
|
||||
<input type="checkbox"
|
||||
name="permissions[]"
|
||||
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>
|
||||
@php
|
||||
$totalInModule = count($module['permissions']);
|
||||
$activeInModule = 0;
|
||||
foreach($module['permissions'] as $pKey => $pMeta) {
|
||||
if ($isSuperAdmin || in_array($pKey, $rolePermNames)) {
|
||||
$activeInModule++;
|
||||
}
|
||||
}
|
||||
@endphp
|
||||
<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"
|
||||
data-module-key="{{ $moduleKey }}">
|
||||
<div>
|
||||
<!-- Header Modul -->
|
||||
<div class="flex items-center justify-between pb-2.5 border-b border-slate-200/60 mb-2.5">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-6 h-6 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center text-xs">
|
||||
<i class="{{ $module['icon'] }}"></i>
|
||||
</div>
|
||||
</label>
|
||||
@endforeach
|
||||
<h3 class="text-xs font-bold text-slate-800 leading-snug">
|
||||
{{ $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>
|
||||
@endforeach
|
||||
</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>
|
||||
</div>
|
||||
@endforeach
|
||||
@@ -306,6 +433,164 @@
|
||||
</div>
|
||||
|
||||
<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() {
|
||||
document.getElementById('createRoleModal').classList.remove('hidden');
|
||||
document.documentElement.classList.add('modal-open');
|
||||
|
||||
@@ -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>
|
||||
</p>
|
||||
@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>
|
||||
|
||||
<!-- Badge Kanan -->
|
||||
|
||||
@@ -204,32 +204,32 @@
|
||||
@endphp
|
||||
|
||||
<div class="p-4 rounded-xl border {{ $isChecked ? 'border-emerald-200 bg-emerald-50/20' : 'border-slate-200 bg-slate-50/50' }} hover:border-slate-300 transition">
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="flex items-center space-x-3 text-xs font-bold text-slate-900 cursor-pointer">
|
||||
<div class="flex items-start sm:items-center justify-between gap-2.5">
|
||||
<label class="flex items-start sm:items-center space-x-3 text-xs font-bold text-slate-900 cursor-pointer flex-1 min-w-0">
|
||||
<input type="checkbox"
|
||||
name="simper_assignments[{{ $st->id }}][enabled]"
|
||||
value="1"
|
||||
id="chkSimper_{{ $st->id }}"
|
||||
{{ $isChecked ? 'checked' : '' }}
|
||||
onchange="toggleSimperRow({{ $st->id }})"
|
||||
class="w-4 h-4 rounded text-[#1b5e20] border-slate-300 focus:ring-emerald-500 cursor-pointer">
|
||||
<div>
|
||||
<span class="font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
|
||||
<span class="text-slate-400 font-mono text-[11px] ml-1">({{ $st->code }})</span>
|
||||
class="w-4 h-4 mt-0.5 sm:mt-0 rounded text-[#1b5e20] border-slate-300 focus:ring-emerald-500 flex-shrink-0 cursor-pointer">
|
||||
<div class="min-w-0">
|
||||
<span class="block truncate font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
|
||||
<span class="block text-slate-400 font-mono text-[10px] font-semibold">{{ $st->code }}</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
@if($st->coversScope('all'))
|
||||
<span class="text-[10px] font-mono px-2 py-0.5 rounded bg-purple-50 text-purple-700 font-bold border border-purple-200">
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-purple-50 text-purple-700 font-bold border border-purple-200 flex-shrink-0">
|
||||
SEMUA ARMADA
|
||||
</span>
|
||||
@elseif($st->scopes === ['light_vehicle'])
|
||||
<span class="text-[10px] font-mono px-2 py-0.5 rounded bg-blue-50 text-blue-700 font-bold border border-blue-200">
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-blue-50 text-blue-700 font-bold border border-blue-200 flex-shrink-0">
|
||||
LV
|
||||
</span>
|
||||
@else
|
||||
<span class="text-[10px] font-mono px-2 py-0.5 rounded bg-amber-50 text-amber-700 font-bold border border-amber-200 max-w-[200px] truncate" title="{{ $st->category_scope_display }}">
|
||||
{{ strtoupper($st->category_scope_display) }}
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-amber-50 text-amber-700 font-bold border border-amber-200 max-w-[140px] sm:max-w-[200px] truncate flex-shrink-0" title="{{ $st->category_scope_display }}">
|
||||
{{ $st->short_scope_display ?? strtoupper($st->category_scope_display) }}
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
@@ -242,18 +242,23 @@
|
||||
</label>
|
||||
<input type="text"
|
||||
name="simper_assignments[{{ $st->id }}][simper_number]"
|
||||
id="inputSimperNum_{{ $st->id }}"
|
||||
value="{{ $simperNum }}"
|
||||
{{ $isChecked ? '' : 'disabled' }}
|
||||
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>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">
|
||||
Masa Berlaku SIMPER
|
||||
Masa Berlaku SIMPER <span class="text-rose-500">*</span>
|
||||
</label>
|
||||
<input type="date"
|
||||
name="simper_assignments[{{ $st->id }}][expired_at]"
|
||||
id="inputSimperExp_{{ $st->id }}"
|
||||
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">
|
||||
min="{{ date('Y-m-d') }}"
|
||||
{{ $isChecked ? 'required' : '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>
|
||||
@@ -359,11 +364,32 @@
|
||||
function toggleSimperRow(id) {
|
||||
const chk = document.getElementById(`chkSimper_${id}`);
|
||||
const fields = document.getElementById(`fieldsSimper_${id}`);
|
||||
const numInp = document.getElementById(`inputSimperNum_${id}`);
|
||||
const expInp = document.getElementById(`inputSimperExp_${id}`);
|
||||
const todayStr = new Date().toISOString().split('T')[0];
|
||||
|
||||
if (chk && fields) {
|
||||
if (chk.checked) {
|
||||
fields.classList.remove('hidden');
|
||||
if (numInp) numInp.disabled = false;
|
||||
if (expInp) {
|
||||
expInp.disabled = false;
|
||||
expInp.required = true;
|
||||
expInp.min = todayStr;
|
||||
if (!expInp.value) {
|
||||
const d = new Date();
|
||||
d.setFullYear(d.getFullYear() + 1);
|
||||
expInp.value = d.toISOString().split('T')[0];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fields.classList.add('hidden');
|
||||
if (numInp) numInp.disabled = true;
|
||||
if (expInp) {
|
||||
expInp.disabled = true;
|
||||
expInp.required = false;
|
||||
expInp.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +281,7 @@
|
||||
<i class="fa-solid fa-up-right-from-square text-[11px]"></i>
|
||||
</a>
|
||||
<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"
|
||||
title="Perpanjang Masa Berlaku SIMPER">
|
||||
Perpanjang
|
||||
@@ -483,18 +483,21 @@
|
||||
<div class="space-y-2 max-h-[48vh] overflow-y-auto pr-1">
|
||||
@foreach($availableSimperTypes as $st)
|
||||
<div class="p-3 rounded-2xl border border-slate-200 bg-slate-50/70 hover:bg-slate-50 transition">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<label class="flex items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
|
||||
<div class="flex items-start sm:items-center justify-between gap-2.5">
|
||||
<label class="flex items-start sm:items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
|
||||
<input type="checkbox"
|
||||
name="simper_assignments[{{ $st->id }}][enabled]"
|
||||
value="1"
|
||||
id="addSimperCheck_{{ $st->id }}"
|
||||
onchange="toggleAddSimperFields({{ $st->id }})"
|
||||
class="w-4 h-4 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0">
|
||||
<span class="truncate">{{ $st->name }} ({{ $st->code }})</span>
|
||||
class="w-4 h-4 mt-0.5 sm:mt-0 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0 cursor-pointer">
|
||||
<div class="min-w-0">
|
||||
<span class="block truncate font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
|
||||
<span class="block text-[10px] font-mono text-slate-400 font-semibold">{{ $st->code }}</span>
|
||||
</div>
|
||||
</label>
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase flex-shrink-0" title="{{ $st->category_scope_display }}">
|
||||
{{ $st->category_scope_display }}
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase max-w-[140px] sm:max-w-[200px] truncate flex-shrink-0" title="{{ $st->category_scope_display }}">
|
||||
{{ $st->short_scope_display ?? $st->category_scope_display }}
|
||||
</span>
|
||||
</div>
|
||||
<div id="addSimperFields_{{ $st->id }}" class="hidden grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2 pt-2 border-t border-slate-200/60">
|
||||
@@ -633,43 +636,123 @@
|
||||
</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 class="bg-white rounded-3xl shadow-2xl max-w-md w-full p-7 border border-slate-100 overflow-hidden">
|
||||
<div class="flex items-center justify-between pb-4 border-b border-slate-100">
|
||||
<h3 class="text-xl font-bold text-slate-900 tracking-tight">Perpanjang SIMPER</h3>
|
||||
<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-3.5 border-b border-slate-100 flex-shrink-0">
|
||||
<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">
|
||||
<i class="fa-solid fa-xmark text-lg"></i>
|
||||
</button>
|
||||
</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
|
||||
<div class="bg-slate-50 p-3.5 rounded-2xl border border-slate-200/80">
|
||||
<span class="text-xs text-slate-400 block font-medium">Pengemudi:</span>
|
||||
<strong id="renewName" class="block text-base text-slate-900 font-bold mt-0.5"></strong>
|
||||
<!-- Identitas Personel (Karyawan / Sukon) -->
|
||||
<div class="bg-slate-50/90 p-3.5 rounded-2xl border border-slate-200/80 flex items-start justify-between gap-3">
|
||||
<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>
|
||||
|
||||
<!-- 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>
|
||||
<label class="block text-sm font-bold text-slate-800 mb-2">Status Driver</label>
|
||||
<select name="is_operator" id="renewOperator" onchange="toggleSimperInput('renew')"
|
||||
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">
|
||||
<option value="1">YA (Aktif Mengemudi)</option>
|
||||
<option value="0">TIDAK (Bukan Driver)</option>
|
||||
<label for="renewSimperTypeSelect" class="block text-xs font-bold text-slate-800 mb-1.5 flex items-center justify-between">
|
||||
<span>Pilih SIMPER yang Ingin Diperpanjang <span class="text-rose-500">*</span></span>
|
||||
<span class="text-[10px] text-slate-400 font-normal">Pilih satu atau semua</span>
|
||||
</label>
|
||||
<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>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-bold text-slate-800 mb-2">Masa Berlaku Baru <span class="text-rose-500">*</span></label>
|
||||
<input type="date" name="simper_expired_at" id="renewDate" required
|
||||
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">
|
||||
|
||||
<!-- Detail SIMPER Terpilih (Live Information Box) -->
|
||||
<div id="renewSelectedDetailBox" class="p-3 rounded-xl bg-slate-50 border border-slate-200/80 text-xs space-y-1">
|
||||
<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 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()"
|
||||
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
|
||||
</button>
|
||||
<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">
|
||||
Simpan Data
|
||||
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">
|
||||
<i class="fa-solid fa-floppy-disk text-xs"></i>
|
||||
<span>Simpan Perpanjangan</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -839,18 +922,21 @@
|
||||
<div class="space-y-2 max-h-[50vh] overflow-y-auto pr-1">
|
||||
@foreach($availableSimperTypes as $st)
|
||||
<div class="p-3 rounded-2xl border border-slate-200 bg-slate-50/70 hover:bg-slate-50 transition">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<label class="flex items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
|
||||
<div class="flex items-start sm:items-center justify-between gap-2.5">
|
||||
<label class="flex items-start sm:items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
|
||||
<input type="checkbox"
|
||||
name="simper_assignments[{{ $st->id }}][enabled]"
|
||||
value="1"
|
||||
id="editSimperCheck_{{ $st->id }}"
|
||||
onchange="toggleEditSimperFields({{ $st->id }})"
|
||||
class="w-4 h-4 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0">
|
||||
<span class="truncate">{{ $st->name }} ({{ $st->code }})</span>
|
||||
class="w-4 h-4 mt-0.5 sm:mt-0 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0 cursor-pointer">
|
||||
<div class="min-w-0">
|
||||
<span class="block truncate font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
|
||||
<span class="block text-[10px] font-mono text-slate-400 font-semibold">{{ $st->code }}</span>
|
||||
</div>
|
||||
</label>
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase flex-shrink-0" title="{{ $st->category_scope_display }}">
|
||||
{{ $st->category_scope_display }}
|
||||
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase max-w-[140px] sm:max-w-[200px] truncate flex-shrink-0" title="{{ $st->category_scope_display }}">
|
||||
{{ $st->short_scope_display ?? $st->category_scope_display }}
|
||||
</span>
|
||||
</div>
|
||||
<div id="editSimperFields_{{ $st->id }}" class="hidden grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2 pt-2 border-t border-slate-200/60">
|
||||
@@ -1120,13 +1206,32 @@
|
||||
function toggleAddSimperFields(id) {
|
||||
const check = document.getElementById(`addSimperCheck_${id}`);
|
||||
const fields = document.getElementById(`addSimperFields_${id}`);
|
||||
const numInp = document.getElementById(`addSimperNum_${id}`);
|
||||
const expInp = document.getElementById(`addSimperExp_${id}`);
|
||||
const todayStr = new Date().toISOString().split('T')[0];
|
||||
|
||||
if (check && fields) {
|
||||
if (check.checked) {
|
||||
fields.classList.remove('hidden');
|
||||
if (numInp) numInp.disabled = false;
|
||||
if (expInp) {
|
||||
expInp.disabled = false;
|
||||
expInp.required = true;
|
||||
expInp.min = todayStr;
|
||||
if (!expInp.value) {
|
||||
const d = new Date();
|
||||
d.setFullYear(d.getFullYear() + 1);
|
||||
expInp.value = d.toISOString().split('T')[0];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fields.classList.add('hidden');
|
||||
const expInp = document.getElementById(`addSimperExp_${id}`);
|
||||
if (expInp) expInp.value = '';
|
||||
if (numInp) numInp.disabled = true;
|
||||
if (expInp) {
|
||||
expInp.disabled = true;
|
||||
expInp.required = false;
|
||||
expInp.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
syncAddPrimarySimperDate();
|
||||
@@ -1152,13 +1257,32 @@
|
||||
function toggleEditSimperFields(id) {
|
||||
const check = document.getElementById(`editSimperCheck_${id}`);
|
||||
const fields = document.getElementById(`editSimperFields_${id}`);
|
||||
const numInp = document.getElementById(`editSimperNum_${id}`);
|
||||
const expInp = document.getElementById(`editSimperExp_${id}`);
|
||||
const todayStr = new Date().toISOString().split('T')[0];
|
||||
|
||||
if (check && fields) {
|
||||
if (check.checked) {
|
||||
fields.classList.remove('hidden');
|
||||
if (numInp) numInp.disabled = false;
|
||||
if (expInp) {
|
||||
expInp.disabled = false;
|
||||
expInp.required = true;
|
||||
expInp.min = todayStr;
|
||||
if (!expInp.value) {
|
||||
const d = new Date();
|
||||
d.setFullYear(d.getFullYear() + 1);
|
||||
expInp.value = d.toISOString().split('T')[0];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fields.classList.add('hidden');
|
||||
const expInp = document.getElementById(`editSimperExp_${id}`);
|
||||
if (expInp) expInp.value = '';
|
||||
if (numInp) numInp.disabled = true;
|
||||
if (expInp) {
|
||||
expInp.disabled = true;
|
||||
expInp.required = false;
|
||||
expInp.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
syncEditPrimarySimperDate();
|
||||
@@ -1248,9 +1372,9 @@
|
||||
const fields = document.getElementById(`editSimperFields_${id}`);
|
||||
if (fields) fields.classList.add('hidden');
|
||||
const num = document.getElementById(`editSimperNum_${id}`);
|
||||
if (num) num.value = '';
|
||||
if (num) { num.value = ''; num.disabled = true; }
|
||||
const exp = document.getElementById(`editSimperExp_${id}`);
|
||||
if (exp) exp.value = '';
|
||||
if (exp) { exp.value = ''; exp.disabled = true; }
|
||||
});
|
||||
|
||||
// Isi checklist SIMPER dari data emp.simpers
|
||||
@@ -1263,8 +1387,8 @@
|
||||
if (cb) {
|
||||
cb.checked = true;
|
||||
if (fields) fields.classList.remove('hidden');
|
||||
if (num) num.value = s.simper_number || '';
|
||||
if (exp && s.expired_at) exp.value = s.expired_at.substring(0, 10);
|
||||
if (num) { num.value = s.simper_number || ''; num.disabled = false; }
|
||||
if (exp && s.expired_at) { exp.value = s.expired_at.substring(0, 10); exp.disabled = false; }
|
||||
}
|
||||
});
|
||||
} else if (emp.is_operator && expDate) {
|
||||
@@ -1274,8 +1398,10 @@
|
||||
const id = firstCb.id.replace('editSimperCheck_', '');
|
||||
const fields = document.getElementById(`editSimperFields_${id}`);
|
||||
if (fields) fields.classList.remove('hidden');
|
||||
const num = document.getElementById(`editSimperNum_${id}`);
|
||||
if (num) num.disabled = false;
|
||||
const exp = document.getElementById(`editSimperExp_${id}`);
|
||||
if (exp) exp.value = expDate;
|
||||
if (exp) { exp.value = expDate; exp.disabled = false; }
|
||||
}
|
||||
}
|
||||
syncEditPrimarySimperDate();
|
||||
@@ -1320,28 +1446,310 @@
|
||||
|
||||
document.getElementById('editForm').action = `/hse/employees/${emp.id}`;
|
||||
document.getElementById('editModal').classList.remove('hidden');
|
||||
document.documentElement.classList.add('modal-open');
|
||||
document.body.classList.add('modal-open');
|
||||
}
|
||||
|
||||
function closeEditModal() {
|
||||
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) {
|
||||
document.getElementById('renewName').textContent = name;
|
||||
document.getElementById('renewOperator').value = isOperator ? '1' : '0';
|
||||
document.getElementById('renewDate').value = expiredDate;
|
||||
|
||||
// Cek status driver untuk mengunci/membuka input SIMPER
|
||||
toggleSimperInput('renew');
|
||||
const allMasterSimperTypes = @json($availableSimperTypes ?? []);
|
||||
let currentRenewEmployee = null;
|
||||
|
||||
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.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() {
|
||||
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) {
|
||||
@@ -1349,12 +1757,20 @@
|
||||
document.getElementById('deleteEmployeeNik').textContent = nik;
|
||||
document.getElementById('deleteEmployeeForm').action = `/hse/employees/${id}`;
|
||||
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() {
|
||||
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)
|
||||
@@ -1442,11 +1858,19 @@
|
||||
});
|
||||
const addSimperDateInp = document.getElementById('addSimperDateInput');
|
||||
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() {
|
||||
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) {
|
||||
const wrapper = document.getElementById('addSimperDateWrapper');
|
||||
@@ -1472,11 +1896,19 @@
|
||||
// Modal Impor Karyawan via Excel
|
||||
function openImportKaryawanModal() {
|
||||
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() {
|
||||
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) {
|
||||
const display = document.getElementById('importFileName');
|
||||
|
||||
@@ -165,8 +165,13 @@
|
||||
onclick="switchP2hSection('{{ $secKey }}')"
|
||||
id="p2h-tab-{{ $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 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>
|
||||
@endforeach
|
||||
</div>
|
||||
@@ -213,13 +218,13 @@
|
||||
</div>
|
||||
|
||||
@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">
|
||||
<label class="cursor-pointer">
|
||||
<input type="radio"
|
||||
name="items[{{ $item->id }}][condition]"
|
||||
value="baik"
|
||||
checked
|
||||
{{ old("items.{$item->id}.condition") === 'baik' ? 'checked' : '' }}
|
||||
onchange="handleConditionChange({{ $item->id }}, 'baik')"
|
||||
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">
|
||||
@@ -231,6 +236,7 @@
|
||||
<input type="radio"
|
||||
name="items[{{ $item->id }}][condition]"
|
||||
value="rusak"
|
||||
{{ old("items.{$item->id}.condition") === 'rusak' ? 'checked' : '' }}
|
||||
onchange="handleConditionChange({{ $item->id }}, 'rusak')"
|
||||
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">
|
||||
@@ -289,15 +295,15 @@
|
||||
@endforeach
|
||||
</div>
|
||||
|
||||
<!-- Navigasi Cepat Antar Section (Sebelumnya & Selanjutnya) -->
|
||||
<!-- Navigasi Wizard Bertahap Antar Section -->
|
||||
@if(count($groupedItems) > 1)
|
||||
<div class="px-4 py-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between">
|
||||
@if($prevKey)
|
||||
<button type="button"
|
||||
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>
|
||||
<span>Bagian Sebelumnya</span>
|
||||
<span>Kembali</span>
|
||||
</button>
|
||||
@else
|
||||
<div></div>
|
||||
@@ -305,15 +311,18 @@
|
||||
|
||||
@if($nextKey)
|
||||
<button type="button"
|
||||
onclick="switchP2hSection('{{ $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">
|
||||
<span>Bagian Selanjutnya</span>
|
||||
onclick="completeAndNextSection('{{ $secKey }}', '{{ $nextKey }}')"
|
||||
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>Selesaikan Bagian Ini & Lanjut</span>
|
||||
<i class="fa-solid fa-chevron-right text-[10px]"></i>
|
||||
</button>
|
||||
@else
|
||||
<span class="text-[11px] font-semibold text-slate-400 flex items-center">
|
||||
<i class="fa-solid fa-flag-checkered mr-1.5 text-emerald-600"></i> Bagian Terakhir
|
||||
</span>
|
||||
<button type="button"
|
||||
onclick="markLastSectionComplete('{{ $secKey }}')"
|
||||
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
|
||||
</div>
|
||||
@endif
|
||||
@@ -324,24 +333,36 @@
|
||||
|
||||
<!-- Card Catatan Umum Operator -->
|
||||
<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">
|
||||
Catatan Umum / Keterangan Tambahan Operator
|
||||
<label for="general_notes" class="flex items-center justify-between text-xs font-bold uppercase tracking-wider text-slate-700">
|
||||
<span>Catatan Umum / Keterangan Tambahan Operator</span>
|
||||
<span class="text-[10px] font-medium text-slate-400 normal-case italic">(opsional / boleh dikosongkan)</span>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
<!-- Tombol Aksi Submit -->
|
||||
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 flex items-center justify-between gap-3">
|
||||
<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">
|
||||
Batal
|
||||
</a>
|
||||
<!-- Card Tombol Aksi Submit P2H (Aktif Setelah Seluruh Bagian Ditinjau) -->
|
||||
<div id="p2hSubmitCard" class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 transition-all">
|
||||
<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">
|
||||
<div class="flex items-center gap-2">
|
||||
<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"
|
||||
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 class="flex items-center justify-between gap-3">
|
||||
<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">
|
||||
Batal
|
||||
</a>
|
||||
|
||||
<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>
|
||||
</form>
|
||||
</div>
|
||||
@@ -349,20 +370,26 @@
|
||||
|
||||
@section('scripts')
|
||||
<script>
|
||||
const allSectionKeys = @json($sectionKeys);
|
||||
const completedSections = {};
|
||||
|
||||
function switchP2hSection(secKey) {
|
||||
// 1. Update tab styling
|
||||
const allTabs = document.querySelectorAll('.p2h-section-tab');
|
||||
allTabs.forEach(tab => {
|
||||
const key = tab.dataset.sectionKey;
|
||||
const isCompleted = !!completedSections[key];
|
||||
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' });
|
||||
} 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 {
|
||||
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');
|
||||
allPanels.forEach(panel => {
|
||||
if (panel.id === 'p2h-content-' + secKey) {
|
||||
@@ -371,6 +398,102 @@
|
||||
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) {
|
||||
@@ -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>
|
||||
@endsection
|
||||
|
||||
@@ -471,6 +471,38 @@
|
||||
openGateSelectionModal(true);
|
||||
});
|
||||
@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>
|
||||
|
||||
<!-- MODAL LIGHTBOX PRATINJAU FOTO DRIVER & MOBIL LV -->
|
||||
@@ -581,4 +613,105 @@
|
||||
</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
|
||||
<!-- Petugas yang Menolak (Otomatis Akun Login) -->
|
||||
<div class="p-3 bg-slate-50 border border-slate-200/80 rounded-2xl flex items-center justify-between text-xs">
|
||||
<span class="text-slate-500 font-medium">Petugas Pemeriksa:</span>
|
||||
<span class="font-bold text-slate-800 flex items-center space-x-1.5">
|
||||
<i class="fa-solid fa-user-shield text-[#1b5e20]"></i>
|
||||
<span>{{ auth()->user()?->name ?? 'Petugas Pos Gerbang' }}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 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
|
||||
|
||||
@@ -374,10 +374,14 @@
|
||||
<form id="editGuardForm" method="POST" action="" class="mt-5 space-y-4">
|
||||
@csrf
|
||||
|
||||
<!-- ID Satpam (Read-only) -->
|
||||
<!-- ID Satpam (Username Login) -->
|
||||
<div>
|
||||
<label class="block text-sm font-bold text-slate-800 mb-2">ID Satpam (Username Login)</label>
|
||||
<input type="text" id="editBadgeId" disabled class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-slate-100 text-slate-600 font-mono font-bold">
|
||||
<label for="editBadgeId" class="block text-sm font-bold text-slate-800 mb-2">
|
||||
ID Satpam (Username Login) <span class="text-rose-500">*</span>
|
||||
</label>
|
||||
<input type="text" name="badge_id" id="editBadgeId" required placeholder="Contoh: SEC-001"
|
||||
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 font-mono font-bold placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition">
|
||||
<p class="text-[11px] text-slate-400 mt-1">Mengubah ID Satpam otomatis memperbarui username login dan NIK Karyawan.</p>
|
||||
</div>
|
||||
|
||||
<!-- Nama Lengkap -->
|
||||
|
||||
@@ -113,32 +113,41 @@
|
||||
</div>
|
||||
@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">
|
||||
<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>
|
||||
<span>Cek fisik kendaraan lalu klik verifikasi untuk membuka portal</span>
|
||||
<span>Cek fisik kendaraan lalu pilih verifikasi atau tolak</span>
|
||||
</span>
|
||||
|
||||
@can('gate.approve')
|
||||
<form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-full 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>
|
||||
<div class="flex items-center gap-2 w-full sm:w-auto">
|
||||
@can('gate.reject')
|
||||
<button type="button"
|
||||
onclick="openRejectModal({{ $act->id }}, '{{ addslashes($act->vehicle->code . ' (' . ($act->vehicle->license_plate ?? 'Tanpa Plat') . ')') }}', '{{ addslashes($act->driver->name ?? 'Pengemudi') }}', '{{ strtolower($act->direction) }}')"
|
||||
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">
|
||||
<i class="fa-solid fa-ban text-xs"></i>
|
||||
<span>Tolak</span>
|
||||
</button>
|
||||
</form>
|
||||
@else
|
||||
<span class="text-xs text-slate-400 italic">Tidak memiliki izin verifikasi</span>
|
||||
@endcan
|
||||
@endcan
|
||||
|
||||
@can('gate.approve')
|
||||
<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>
|
||||
|
||||
@@ -658,7 +658,6 @@
|
||||
}, 500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Panduan Halaman Modal
|
||||
function openGuideModal() {
|
||||
|
||||
@@ -301,11 +301,23 @@
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<!-- Odometer Awal -->
|
||||
<!-- Odometer Awal & Akhir -->
|
||||
<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">
|
||||
{{ number_format($ts->start_meter, 1, ',', '.') }} {{ $ts->meter_type }}
|
||||
</span>
|
||||
<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 }}@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
|
||||
</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>
|
||||
|
||||
<!-- Lokasi & Aktivitas -->
|
||||
@@ -361,9 +373,9 @@
|
||||
'operator_type' => $ts->operator?->employee_type ?: 'Karyawan',
|
||||
'operator_nik' => $ts->operator?->nik ?: '-',
|
||||
'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,
|
||||
'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, ',', '.'),
|
||||
'breakdown_hours' => number_format($ts->breakdown_hours, 1, ',', '.'),
|
||||
'fuel_liters' => $ts->fuel_liters ? number_format($ts->fuel_liters, 0, ',', '.') : '-',
|
||||
@@ -479,37 +491,37 @@
|
||||
<!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
Lokasi Kerja <span class="text-rose-500">*</span>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Lokasi Kerja <span class="text-rose-500">*</span></span>
|
||||
<span class="sr-only">Tentukan Lokasi Dulu</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
|
||||
</label>
|
||||
<select id="addLocationSelect"
|
||||
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">
|
||||
<div class="relative">
|
||||
<input type="text"
|
||||
id="addCustomLocationInput"
|
||||
name="custom_location"
|
||||
placeholder="Ketik nama lokasi kerja baru..."
|
||||
oninput="onCustomLocationTyped(this.value, 'add')"
|
||||
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]">
|
||||
id="addLocationInput"
|
||||
name="location"
|
||||
list="addLocationsDatalist"
|
||||
required
|
||||
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>
|
||||
<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>
|
||||
@@ -517,13 +529,27 @@
|
||||
<span>Heavy Equipment <span class="text-rose-500">*</span></span>
|
||||
<span id="addUnitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
|
||||
</label>
|
||||
<select name="vehicle_id"
|
||||
id="addVehicleSelect"
|
||||
required
|
||||
onchange="onVehicleSelectChanged(this, '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 Terlebih Dahulu --</option>
|
||||
</select>
|
||||
<div class="space-y-1.5">
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<input type="text"
|
||||
id="addVehicleSearch"
|
||||
placeholder="Ketik untuk filter unit (kode / merek)..."
|
||||
oninput="filterTimesheetVehicleOptions(this.value, 'add')"
|
||||
autocomplete="off"
|
||||
class="w-full pl-8 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
|
||||
<button type="button" onclick="clearTimesheetVehicleFilter('add')" id="clearAddVehicleSearchBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
|
||||
<i class="fa-solid fa-xmark text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<select name="vehicle_id"
|
||||
id="addVehicleSelect"
|
||||
required
|
||||
onchange="onVehicleSelectChanged(this, '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 Terlebih Dahulu --</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="addVehiclePreview" class="hidden mt-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-200/80 text-[11px] text-emerald-900 flex items-center justify-between">
|
||||
<span id="addVehiclePreviewText" class="font-bold"></span>
|
||||
<span id="addVehicleLastKmText" class="text-emerald-700 font-mono text-[10px]"></span>
|
||||
@@ -626,7 +652,7 @@
|
||||
</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>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
@@ -644,6 +670,28 @@
|
||||
</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>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
Satuan Meteran <span class="text-rose-500">*</span>
|
||||
@@ -653,21 +701,21 @@
|
||||
<option value="KM">KM (Odometer)</option>
|
||||
</select>
|
||||
</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>
|
||||
|
||||
<!-- Baris 5: Status Akhir Unit (Shift diset otomatis) -->
|
||||
<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 -->
|
||||
<div>
|
||||
@@ -811,37 +859,37 @@
|
||||
<!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
Lokasi Kerja <span class="text-rose-500">*</span>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Lokasi Kerja <span class="text-rose-500">*</span></span>
|
||||
<span class="sr-only">Tentukan Lokasi Dulu</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
|
||||
</label>
|
||||
<select id="editLocationSelect"
|
||||
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">
|
||||
<div class="relative">
|
||||
<input type="text"
|
||||
id="editCustomLocationInput"
|
||||
name="custom_location"
|
||||
placeholder="Ketik nama lokasi kerja baru..."
|
||||
oninput="onCustomLocationTyped(this.value, 'edit')"
|
||||
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]">
|
||||
id="editLocationInput"
|
||||
name="location"
|
||||
list="editLocationsDatalist"
|
||||
required
|
||||
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>
|
||||
<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>
|
||||
@@ -849,13 +897,27 @@
|
||||
<span>Heavy Equipment <span class="text-rose-500">*</span></span>
|
||||
<span id="editUnitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
|
||||
</label>
|
||||
<select name="vehicle_id"
|
||||
id="editVehicleSelect"
|
||||
required
|
||||
onchange="onVehicleSelectChanged(this, '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 Terlebih Dahulu --</option>
|
||||
</select>
|
||||
<div class="space-y-1.5">
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<input type="text"
|
||||
id="editVehicleSearch"
|
||||
placeholder="Ketik untuk filter unit (kode / merek)..."
|
||||
oninput="filterTimesheetVehicleOptions(this.value, 'edit')"
|
||||
autocomplete="off"
|
||||
class="w-full pl-8 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
|
||||
<button type="button" onclick="clearTimesheetVehicleFilter('edit')" id="clearEditVehicleSearchBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
|
||||
<i class="fa-solid fa-xmark text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<select name="vehicle_id"
|
||||
id="editVehicleSelect"
|
||||
required
|
||||
onchange="onVehicleSelectChanged(this, '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 Terlebih Dahulu --</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="editVehiclePreview" class="hidden mt-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-200/80 text-[11px] text-emerald-900 flex items-center justify-between">
|
||||
<span id="editVehiclePreviewText" class="font-bold"></span>
|
||||
<span id="editVehicleLastKmText" class="text-emerald-700 font-mono text-[10px]"></span>
|
||||
@@ -956,7 +1018,7 @@
|
||||
</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>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
@@ -974,6 +1036,28 @@
|
||||
</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>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
Satuan Meteran <span class="text-rose-500">*</span>
|
||||
@@ -983,21 +1067,22 @@
|
||||
<option value="KM">KM (Odometer)</option>
|
||||
</select>
|
||||
</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>
|
||||
|
||||
<!-- Baris 5: Status Akhir Unit (Shift disimpan secara otomatis) -->
|
||||
<!-- Baris 5: Shift (disimpan otomatis) -->
|
||||
<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 -->
|
||||
<div>
|
||||
@@ -1318,23 +1403,15 @@
|
||||
const modal = document.getElementById('addTimesheetModal');
|
||||
if (modal) {
|
||||
// Reset form pilihan lokasi & unit
|
||||
const addLocSelect = document.getElementById('addLocationSelect');
|
||||
if (addLocSelect) addLocSelect.selectedIndex = 0;
|
||||
const customWrap = document.getElementById('addCustomLocationWrapper');
|
||||
if (customWrap) customWrap.classList.add('hidden');
|
||||
const customInput = document.getElementById('addCustomLocationInput');
|
||||
if (customInput) customInput.value = '';
|
||||
const addLocInput = document.getElementById('addLocationInput');
|
||||
if (addLocInput) addLocInput.value = '';
|
||||
const finalLoc = document.getElementById('addFinalLocation');
|
||||
if (finalLoc) finalLoc.value = '';
|
||||
|
||||
const vehSelect = document.getElementById('addVehicleSelect');
|
||||
if (vehSelect) {
|
||||
vehSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
|
||||
}
|
||||
const counter = document.getElementById('addUnitCounterBadge');
|
||||
if (counter) counter.classList.add('hidden');
|
||||
const preview = document.getElementById('addVehiclePreview');
|
||||
if (preview) preview.classList.add('hidden');
|
||||
const endMeter = document.getElementById('addEndMeter');
|
||||
if (endMeter) endMeter.value = '';
|
||||
|
||||
onTimesheetLocationTyped('', 'add');
|
||||
|
||||
const startMeter = document.getElementById('addStartMeter');
|
||||
if (startMeter) startMeter.value = '';
|
||||
@@ -1424,37 +1501,14 @@
|
||||
document.getElementById('editTimesheetSubtitle').textContent = `No: ${ts.timesheet_no} (${unitCode || '-'})`;
|
||||
|
||||
// 1. Sinkronisasi Lokasi Kerja
|
||||
const locSelect = document.getElementById('editLocationSelect');
|
||||
const locInput = document.getElementById('editLocationInput');
|
||||
const finalLoc = document.getElementById('editFinalLocation');
|
||||
const customWrap = document.getElementById('editCustomLocationWrapper');
|
||||
const targetLoc = ts.location || '';
|
||||
|
||||
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');
|
||||
if (locInput) locInput.value = targetLoc;
|
||||
if (finalLoc) finalLoc.value = targetLoc;
|
||||
|
||||
// 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
|
||||
let selectedOpType = 'all';
|
||||
@@ -1487,6 +1541,10 @@
|
||||
document.getElementById('editMeterType').value = ts.meter_type || 'HM';
|
||||
|
||||
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('editStatus').value = ts.status || 'Operation';
|
||||
@@ -1520,10 +1578,17 @@
|
||||
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) {
|
||||
const customWrapper = document.getElementById(`${prefix}CustomLocationWrapper`);
|
||||
const customInput = document.getElementById(`${prefix}CustomLocationInput`);
|
||||
const finalLocation = document.getElementById(`${prefix}FinalLocation`);
|
||||
const vehicleSelect = document.getElementById(`${prefix}VehicleSelect`);
|
||||
const counterBadge = document.getElementById(`${prefix}UnitCounterBadge`);
|
||||
@@ -1531,58 +1596,48 @@
|
||||
|
||||
if (!vehicleSelect) return;
|
||||
|
||||
// Tangani pilihan custom atau ALL
|
||||
if (selectedLoc === '__CUSTOM__') {
|
||||
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;
|
||||
}
|
||||
if (finalLocation) {
|
||||
finalLocation.value = (selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]' || !selectedLoc) ? '' : selectedLoc;
|
||||
}
|
||||
|
||||
const allUnits = window.unitSupportsData || [];
|
||||
let filteredUnits = [];
|
||||
|
||||
if (!selectedLoc) {
|
||||
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__') {
|
||||
if (!selectedLoc || selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]') {
|
||||
filteredUnits = allUnits;
|
||||
} else {
|
||||
const norm = selectedLoc.trim().toLowerCase();
|
||||
filteredUnits = allUnits.filter(u => {
|
||||
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
|
||||
if (preselectVehicleId) {
|
||||
const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId));
|
||||
if (!foundInFiltered) {
|
||||
const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId));
|
||||
if (extra) filteredUnits.unshift(extra);
|
||||
}
|
||||
// Jika dalam mode edit dan preselectVehicleId tidak ditemukan di lokasi ini, sertakan unit tersebut
|
||||
if (preselectVehicleId) {
|
||||
const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId));
|
||||
if (!foundInFiltered) {
|
||||
const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId));
|
||||
if (extra) filteredUnits.unshift(extra);
|
||||
}
|
||||
}
|
||||
|
||||
// Update badge counter
|
||||
if (counterBadge) {
|
||||
counterBadge.classList.remove('hidden');
|
||||
if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
|
||||
counterBadge.textContent = `${filteredUnits.length} Total Unit`;
|
||||
} else {
|
||||
counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
|
||||
}
|
||||
counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
|
||||
}
|
||||
|
||||
// Reset input filter unit realtime
|
||||
const vSearch = document.getElementById(`${prefix}VehicleSearch`);
|
||||
if (vSearch) vSearch.value = '';
|
||||
const vClear = document.getElementById(`clear${prefix === 'add' ? 'Add' : 'Edit'}VehicleSearchBtn`);
|
||||
if (vClear) vClear.classList.add('hidden');
|
||||
|
||||
// Render option heavy equipment
|
||||
vehicleSelect.innerHTML = '';
|
||||
const defaultPrompt = document.createElement('option');
|
||||
@@ -1590,7 +1645,7 @@
|
||||
defaultPrompt.disabled = true;
|
||||
defaultPrompt.textContent = filteredUnits.length > 0
|
||||
? `-- 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);
|
||||
|
||||
let hasSelected = false;
|
||||
@@ -1633,6 +1688,58 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Realtime Dropdown Heavy Equipment pada Timesheet berdasarkan Ketikan
|
||||
*/
|
||||
function filterTimesheetVehicleOptions(query, prefix) {
|
||||
const select = document.getElementById(`${prefix}VehicleSelect`);
|
||||
const clearBtn = document.getElementById(`clear${prefix === 'add' ? 'Add' : 'Edit'}VehicleSearchBtn`);
|
||||
const badge = document.getElementById(`${prefix}UnitCounterBadge`);
|
||||
if (!select) return;
|
||||
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
if (clearBtn) {
|
||||
clearBtn.classList.toggle('hidden', !q);
|
||||
}
|
||||
|
||||
let visibleCount = 0;
|
||||
let firstMatch = null;
|
||||
|
||||
Array.from(select.options).forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
const code = (opt.getAttribute('data-code') || '').toLowerCase();
|
||||
const brand = (opt.getAttribute('data-brand') || '').toLowerCase();
|
||||
const loc = (opt.getAttribute('data-location') || '').toLowerCase();
|
||||
const text = opt.textContent.toLowerCase();
|
||||
|
||||
const match = text.includes(q) || code.includes(q) || brand.includes(q) || loc.includes(q);
|
||||
opt.hidden = !match;
|
||||
if (match) {
|
||||
visibleCount++;
|
||||
if (!firstMatch) firstMatch = opt;
|
||||
}
|
||||
});
|
||||
|
||||
if (badge) {
|
||||
badge.classList.remove('hidden');
|
||||
badge.textContent = q ? `${visibleCount} Unit Cocok` : `${visibleCount} Unit Ready`;
|
||||
}
|
||||
|
||||
if (q && visibleCount === 1 && firstMatch) {
|
||||
select.value = firstMatch.value;
|
||||
onVehicleSelectChanged(select, prefix);
|
||||
}
|
||||
}
|
||||
|
||||
function clearTimesheetVehicleFilter(prefix) {
|
||||
const input = document.getElementById(`${prefix}VehicleSearch`);
|
||||
if (input) input.value = '';
|
||||
filterTimesheetVehicleOptions('', prefix);
|
||||
}
|
||||
|
||||
// 7. Handler saat Heavy Equipment Dipilih
|
||||
function onVehicleSelectChanged(selectEl, prefix) {
|
||||
const opt = selectEl.options[selectEl.selectedIndex];
|
||||
@@ -1670,10 +1777,13 @@
|
||||
updateMeterUnitLabels(prefix);
|
||||
}
|
||||
|
||||
// Jika lokasi kerja dipilih 'ALL', sinkronkan finalLocation ke lokasi unit
|
||||
const locSelect = document.getElementById(`${prefix}LocationSelect`);
|
||||
// Jika lokasi kerja dipilih 'ALL' atau kosong, sinkronkan ke lokasi unit
|
||||
const locInput = document.getElementById(`${prefix}LocationInput`);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1690,6 +1800,10 @@
|
||||
if (label) {
|
||||
label.textContent = unit;
|
||||
}
|
||||
const endLabel = document.getElementById(`${prefix}EndMeterUnitLabel`);
|
||||
if (endLabel) {
|
||||
endLabel.textContent = unit;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('addMeterType')?.addEventListener('change', () => updateMeterUnitLabels('add'));
|
||||
|
||||
@@ -68,29 +68,43 @@
|
||||
<div>
|
||||
<label for="origin_location" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Lokasi Awal (Asal Unit) <span class="text-rose-500">*</span></span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Filter Berdasarkan Posisi</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / filter</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<select name="from_location"
|
||||
id="origin_location"
|
||||
required
|
||||
onchange="onOriginLocationChanged(this.value)"
|
||||
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-bold">
|
||||
<option value="" disabled {{ empty($selectedOriginLocation) && !old('from_location') ? 'selected' : '' }}>
|
||||
-- Pilih Lokasi Awal Alat Berat --
|
||||
</option>
|
||||
<option value="ALL" {{ old('from_location', $selectedOriginLocation) === 'ALL' ? 'selected' : '' }}>
|
||||
[Tampilkan Semua Lokasi / Semua Alat Berat]
|
||||
</option>
|
||||
@foreach($originLocations as $locName => $count)
|
||||
<option value="{{ $locName }}" {{ old('from_location', $selectedOriginLocation) === $locName ? 'selected' : '' }}>
|
||||
{{ $locName }} ({{ $count }} Unit Tersedia)
|
||||
<div class="space-y-1.5">
|
||||
<div class="relative">
|
||||
<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="originLocationSearch"
|
||||
placeholder="Ketik untuk memfilter pilihan lokasi asal..."
|
||||
oninput="filterOriginLocationSelect(this.value)"
|
||||
autocomplete="off"
|
||||
class="w-full pl-9 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
|
||||
<button type="button" onclick="clearOriginLocationFilter()" id="clearOriginLocationFilterBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
|
||||
<i class="fa-solid fa-xmark text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<select name="from_location"
|
||||
id="origin_location"
|
||||
required
|
||||
onchange="onOriginLocationChanged(this.value)"
|
||||
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-bold">
|
||||
<option value="" disabled {{ empty($selectedOriginLocation) && !old('from_location') ? 'selected' : '' }}>
|
||||
-- Pilih Lokasi Awal Alat Berat --
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<option value="ALL" {{ old('from_location', $selectedOriginLocation) === 'ALL' ? 'selected' : '' }}>
|
||||
[Tampilkan Semua Lokasi / Semua Alat Berat]
|
||||
</option>
|
||||
@foreach($originLocations as $locName => $count)
|
||||
<option value="{{ $locName }}" {{ old('from_location', $selectedOriginLocation) === $locName ? 'selected' : '' }}>
|
||||
{{ $locName }} ({{ $count }} Unit Tersedia)
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-[10px] text-slate-400 mt-1">Memilih lokasi awal akan memfilter unit alat berat yang berada di titik tersebut.</p>
|
||||
<p class="text-[10px] text-slate-400 mt-1">Ketik nama lokasi atau pilih dari daftar untuk memfilter unit.</p>
|
||||
</div>
|
||||
|
||||
<!-- PILIH ALAT BERAT YANG AKAN DIPINDAHKAN -->
|
||||
@@ -99,27 +113,41 @@
|
||||
<span>Unit Alat Berat yang Dipindahkan <span class="text-rose-500">*</span></span>
|
||||
<span id="unitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
|
||||
</label>
|
||||
<select name="vehicle_id"
|
||||
id="vehicle_id"
|
||||
required
|
||||
onchange="onHeavyUnitSelected(this)"
|
||||
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 font-semibold">
|
||||
<option value="" disabled {{ empty($selectedVehicleId) && !old('vehicle_id') ? 'selected' : '' }}>
|
||||
-- Pilih Lokasi Awal Terlebih Dahulu --
|
||||
</option>
|
||||
@foreach($heavyUnits as $unit)
|
||||
<option value="{{ $unit->id }}"
|
||||
data-code="{{ $unit->code }}"
|
||||
data-brand="{{ $unit->brand_type }}"
|
||||
data-category="{{ $unit->unit_category ?? ($unit->parent?->brand_type ?? 'Heavy Equipment') }}"
|
||||
data-location="{{ $unit->location ?: 'Site Kerinci' }}"
|
||||
data-site-status="{{ $unit->site_status ?? 'inside_site' }}"
|
||||
data-photo="{{ $unit->photo_url }}"
|
||||
{{ old('vehicle_id', $selectedVehicleId) == $unit->id ? 'selected' : '' }}>
|
||||
{{ $unit->code }} - {{ $unit->brand_type }} [Posisi: {{ $unit->location ?: 'Site Kerinci' }}]
|
||||
<div class="space-y-1.5">
|
||||
<div class="relative">
|
||||
<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="heavyUnitSearch"
|
||||
placeholder="Ketik kode / merek untuk filter unit..."
|
||||
oninput="filterHeavyUnitOptions(this.value)"
|
||||
autocomplete="off"
|
||||
class="w-full pl-9 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
|
||||
<button type="button" onclick="clearHeavyUnitFilter()" id="clearHeavyUnitFilterBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
|
||||
<i class="fa-solid fa-xmark text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<select name="vehicle_id"
|
||||
id="vehicle_id"
|
||||
required
|
||||
onchange="onHeavyUnitSelected(this)"
|
||||
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 font-semibold">
|
||||
<option value="" disabled {{ empty($selectedVehicleId) && !old('vehicle_id') ? 'selected' : '' }}>
|
||||
-- Pilih Lokasi Awal Terlebih Dahulu --
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
@foreach($heavyUnits as $unit)
|
||||
<option value="{{ $unit->id }}"
|
||||
data-code="{{ $unit->code }}"
|
||||
data-brand="{{ $unit->brand_type }}"
|
||||
data-category="{{ $unit->unit_category ?? ($unit->parent?->brand_type ?? 'Heavy Equipment') }}"
|
||||
data-location="{{ $unit->location ?: 'Site Kerinci' }}"
|
||||
data-site-status="{{ $unit->site_status ?? 'inside_site' }}"
|
||||
data-photo="{{ $unit->photo_url }}"
|
||||
{{ old('vehicle_id', $selectedVehicleId) == $unit->id ? 'selected' : '' }}>
|
||||
{{ $unit->code }} - {{ $unit->brand_type }} [Posisi: {{ $unit->location ?: 'Site Kerinci' }}]
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
@error('vehicle_id')
|
||||
<p class="text-rose-500 text-[11px] font-semibold mt-1">{{ $message }}</p>
|
||||
@enderror
|
||||
@@ -282,11 +310,55 @@
|
||||
</div>
|
||||
<div>
|
||||
<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>
|
||||
|
||||
<!-- 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">
|
||||
<i class="fa-solid fa-route text-blue-700 text-sm mt-0.5"></i>
|
||||
<div class="flex-1">
|
||||
@@ -295,64 +367,128 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Grid 2 Kolom: Pilih Mobil Pengangkut & Nama Pengangkut -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<!-- Pilih Mobil dari Unit Kita -->
|
||||
<div>
|
||||
<label for="transporter_vehicle_id" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Pilih Kendaraan Pengangkut (Armada Kita)</span>
|
||||
<span id="transporterLocationHint" class="text-[10px] text-slate-400 font-normal">Truk / Lowbed / Towing</span>
|
||||
</label>
|
||||
<select name="transporter_vehicle_id"
|
||||
id="transporter_vehicle_id"
|
||||
onchange="onTransporterSelected(this)"
|
||||
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">
|
||||
<option value="">-- Tanpa Truk Pengangkut / Rental Luar / Mobilisasi Mandiri --</option>
|
||||
@foreach($transporterUnits as $tu)
|
||||
<option value="{{ $tu->id }}"
|
||||
data-code="{{ $tu->code }}"
|
||||
data-name="{{ $tu->code }} - {{ $tu->brand_type }}{{ $tu->license_plate ? ' (' . $tu->license_plate . ')' : '' }}"
|
||||
data-location="{{ $tu->location ?: 'Pool Workshop GA' }}"
|
||||
{{ old('transporter_vehicle_id') == $tu->id ? 'selected' : '' }}>
|
||||
{{ $tu->code }} - {{ $tu->brand_type }} [Posisi: {{ $tu->location ?: 'Pool Workshop' }}]
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Input / Snapshot Nama Armada Pengangkut -->
|
||||
<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">
|
||||
<!-- ============================================== -->
|
||||
<!-- KONTAINER 1: PENGANGKUT DARI DALAM KMH -->
|
||||
<!-- ============================================== -->
|
||||
<div id="transporterInternalContainer" class="space-y-4">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<!-- KIRI: PILIH LOKASI ASAL PENGANGKUT (INTERNAL) -->
|
||||
<div>
|
||||
<label for="transporter_origin_location_select" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Lokasi Asal Kendaraan Pengangkut</span>
|
||||
<span class="text-[10px] text-blue-700 font-semibold">Filter Berdasarkan Posisi</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<select id="transporter_origin_location_select"
|
||||
onchange="onTransporterOriginChanged(this.value)"
|
||||
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">
|
||||
<option value="" selected>-- Pilih Lokasi Asal Kendaraan Pengangkut --</option>
|
||||
<option value="ALL">[Tampilkan Semua Lokasi / Semua Armada]</option>
|
||||
@foreach($transporterLocations as $tLoc => $tCount)
|
||||
<option value="{{ $tLoc }}" {{ old('transporter_origin_location') === $tLoc ? 'selected' : '' }}>
|
||||
{{ $tLoc }} ({{ $tCount }} Unit Tersedia)
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
<p class="text-[10px] text-slate-400 mt-1">Pilih lokasi asal untuk memfilter unit pengangkut yang standby di titik tersebut.</p>
|
||||
</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>
|
||||
|
||||
<!-- Opsi Sinkronisasi Lokasi Truk Pengangkut -->
|
||||
<div 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>
|
||||
<!-- ============================================== -->
|
||||
<!-- KONTAINER 2: PENGANGKUT DARI LUAR KMH -->
|
||||
<!-- ============================================== -->
|
||||
<div id="transporterExternalContainer" class="hidden space-y-4">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<!-- KIRI: ASAL KENDARAAN PENGANGKUT (ISIAN TEKS MANUAL) -->
|
||||
<div>
|
||||
<label for="transporter_origin_location_input" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Asal Kendaraan Pengangkut (Luar)</span>
|
||||
<span class="text-[10px] text-slate-400 font-normal">Ketik Bebas / Rekomendasi</span>
|
||||
</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>
|
||||
|
||||
<!-- 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 -->
|
||||
<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 -->
|
||||
<div>
|
||||
<label for="transporter_driver_name" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
@@ -482,8 +618,20 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Inisialisasi daftar semua unit alat berat dari options
|
||||
// Inisialisasi daftar semua unit alat berat & armada pengangkut
|
||||
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() {
|
||||
const unitSelect = document.getElementById('vehicle_id');
|
||||
@@ -504,17 +652,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');
|
||||
if (originSelect && originSelect.value) {
|
||||
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
|
||||
const currentSiteStatus = document.querySelector('input[name="to_site_status"]:checked')?.value || 'inside_site';
|
||||
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)
|
||||
* Nomor BAST dan Dokumen hanya muncul saat transfer ke LUAR site.
|
||||
@@ -577,6 +901,11 @@
|
||||
// Kosongkan options
|
||||
unitSelect.innerHTML = '';
|
||||
|
||||
const searchInput = document.getElementById('heavyUnitSearch');
|
||||
if (searchInput) searchInput.value = '';
|
||||
const searchClear = document.getElementById('clearHeavyUnitFilterBtn');
|
||||
if (searchClear) searchClear.classList.add('hidden');
|
||||
|
||||
if (!selectedLocation) {
|
||||
const defaultOpt = document.createElement('option');
|
||||
defaultOpt.value = '';
|
||||
@@ -679,47 +1008,148 @@
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler saat Armada Pengangkut Terpilih
|
||||
*/
|
||||
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
|
||||
* Update Banner Logistik Rute Perjalanan (Mendukung Internal & Eksternal)
|
||||
*/
|
||||
function updateRouteBanner() {
|
||||
const banner = document.getElementById('routeLogisticsBanner');
|
||||
const text = document.getElementById('routeLogisticsText');
|
||||
const transporterSelect = document.getElementById('transporter_vehicle_id');
|
||||
const originSelect = document.getElementById('origin_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 (!optTransporter || !optTransporter.value) {
|
||||
banner.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
if (!banner || !text) return;
|
||||
|
||||
const transporterCode = optTransporter.getAttribute('data-code');
|
||||
const transporterLoc = optTransporter.getAttribute('data-location') || 'Pool Workshop';
|
||||
const originLoc = originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
|
||||
const destLoc = destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
|
||||
const originLoc = originSelect && originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
|
||||
const destLoc = destinationInput && destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
|
||||
|
||||
banner.classList.remove('hidden');
|
||||
if (transporterLoc === originLoc) {
|
||||
text.innerHTML = `Truk <strong>${transporterCode}</strong> saat ini standby di <strong>${transporterLoc}</strong> (sama dengan lokasi alat berat) → Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`;
|
||||
if (transporterType === 'internal') {
|
||||
const truckName = document.getElementById('final_transporter_unit_name')?.value || document.getElementById('internal_transporter_search')?.value.trim();
|
||||
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) → Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`;
|
||||
} else {
|
||||
text.innerHTML = `Truk <strong>${truckName}</strong> diberangkatkan dari <strong>${truckLoc}</strong> → Menjemput alat berat di <strong>${originLoc}</strong> → Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
|
||||
}
|
||||
} else {
|
||||
text.innerHTML = `Truk <strong>${transporterCode}</strong> diberangkatkan dari <strong>${transporterLoc}</strong> → Menjemput alat berat di <strong>${originLoc}</strong> → 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> → Menjemput alat berat di <strong>${originLoc}</strong> → Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Realtime Dropdown Lokasi Awal berdasarkan Ketikan
|
||||
*/
|
||||
function filterOriginLocationSelect(query) {
|
||||
const select = document.getElementById('origin_location');
|
||||
const clearBtn = document.getElementById('clearOriginLocationFilterBtn');
|
||||
if (!select) return;
|
||||
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
if (clearBtn) {
|
||||
clearBtn.classList.toggle('hidden', !q);
|
||||
}
|
||||
|
||||
let visibleCount = 0;
|
||||
let firstMatch = null;
|
||||
|
||||
Array.from(select.options).forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (opt.value === 'ALL') {
|
||||
opt.hidden = q.length > 0 && !opt.textContent.toLowerCase().includes(q);
|
||||
if (!opt.hidden && !firstMatch) firstMatch = opt;
|
||||
return;
|
||||
}
|
||||
const match = opt.textContent.toLowerCase().includes(q) || opt.value.toLowerCase().includes(q);
|
||||
opt.hidden = !match;
|
||||
if (match) {
|
||||
visibleCount++;
|
||||
if (!firstMatch) firstMatch = opt;
|
||||
}
|
||||
});
|
||||
|
||||
if (q && visibleCount === 1 && firstMatch) {
|
||||
select.value = firstMatch.value;
|
||||
onOriginLocationChanged(firstMatch.value);
|
||||
}
|
||||
}
|
||||
|
||||
function clearOriginLocationFilter() {
|
||||
const input = document.getElementById('originLocationSearch');
|
||||
if (input) input.value = '';
|
||||
filterOriginLocationSelect('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Realtime Dropdown Unit Alat Berat berdasarkan Ketikan Kode / Merek
|
||||
*/
|
||||
function filterHeavyUnitOptions(query) {
|
||||
const select = document.getElementById('vehicle_id');
|
||||
const clearBtn = document.getElementById('clearHeavyUnitFilterBtn');
|
||||
const badge = document.getElementById('unitCounterBadge');
|
||||
if (!select) return;
|
||||
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
if (clearBtn) {
|
||||
clearBtn.classList.toggle('hidden', !q);
|
||||
}
|
||||
|
||||
let visibleCount = 0;
|
||||
let firstMatch = null;
|
||||
|
||||
Array.from(select.options).forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
const code = (opt.getAttribute('data-code') || '').toLowerCase();
|
||||
const brand = (opt.getAttribute('data-brand') || '').toLowerCase();
|
||||
const cat = (opt.getAttribute('data-category') || '').toLowerCase();
|
||||
const text = opt.textContent.toLowerCase();
|
||||
|
||||
const match = text.includes(q) || code.includes(q) || brand.includes(q) || cat.includes(q);
|
||||
opt.hidden = !match;
|
||||
if (match) {
|
||||
visibleCount++;
|
||||
if (!firstMatch) firstMatch = opt;
|
||||
}
|
||||
});
|
||||
|
||||
if (badge) {
|
||||
badge.classList.remove('hidden');
|
||||
badge.textContent = q ? `${visibleCount} Unit Cocok` : `${visibleCount} Unit Tersedia`;
|
||||
}
|
||||
|
||||
if (q && visibleCount === 1 && firstMatch) {
|
||||
select.value = firstMatch.value;
|
||||
onHeavyUnitSelected(select);
|
||||
}
|
||||
}
|
||||
|
||||
function clearHeavyUnitFilter() {
|
||||
const input = document.getElementById('heavyUnitSearch');
|
||||
if (input) input.value = '';
|
||||
filterHeavyUnitOptions('');
|
||||
}
|
||||
</script>
|
||||
@endsection
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
@section('title', 'Transfer Unit Alat Berat - Admin QMA | PT Kerinci Merangin Hidro')
|
||||
|
||||
@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) -->
|
||||
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||
<!-- Header Judul & Tombol Aksi -->
|
||||
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
|
||||
<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]">
|
||||
MANAJEMEN SISTEM
|
||||
</span>
|
||||
@@ -19,22 +19,22 @@
|
||||
<i class="fa-solid fa-info"></i>
|
||||
</button>
|
||||
</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
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<!-- 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 -->
|
||||
<div class="relative inline-block w-full sm:w-auto flex-1 sm:flex-none" id="exportDropdownContainer">
|
||||
<button type="button"
|
||||
onclick="toggleExportMenu(event)"
|
||||
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>
|
||||
<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>
|
||||
<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">
|
||||
@@ -51,21 +51,9 @@
|
||||
|
||||
@canany(['qma.vehicles.create', 'qma.vehicles.edit'])
|
||||
<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">
|
||||
<i class="fa-solid fa-truck-moving text-sm"></i>
|
||||
<span class="hidden sm:inline">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>
|
||||
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-xs"></i>
|
||||
<span>Transfer Unit Baru</span>
|
||||
</a>
|
||||
@endcanany
|
||||
</div>
|
||||
@@ -73,8 +61,8 @@
|
||||
|
||||
<!-- Alert Notifikasi Flash -->
|
||||
@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="w-7 h-7 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0">
|
||||
<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-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>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
@@ -84,8 +72,8 @@
|
||||
@endif
|
||||
|
||||
@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="w-7 h-7 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center shrink-0">
|
||||
<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-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>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
@@ -94,178 +82,184 @@
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- KPI Ringkasan Pemindahan Unit -->
|
||||
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3.5">
|
||||
<!-- KPI Ringkasan Pemindahan Unit (Ramping & Sleek) -->
|
||||
<div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3">
|
||||
<!-- 1. Total Transfer -->
|
||||
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Pemindahan</p>
|
||||
<h3 class="text-2xl font-black text-slate-800 mt-1">{{ number_format($totalTransfers, 0, ',', '.') }}</h3>
|
||||
<span class="text-[10px] text-slate-400 font-medium block mt-1">Semua Dokumen BAST</span>
|
||||
<div class="bg-white p-3 sm:p-3.5 rounded-xl border border-slate-200/80 shadow-2xs flex items-center justify-between">
|
||||
<div>
|
||||
<p class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Total BAST</p>
|
||||
<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>
|
||||
|
||||
<!-- 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">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p>
|
||||
<h3 class="text-2xl font-black text-blue-800 mt-1">{{ number_format($thisMonthCount, 0, ',', '.') }}</h3>
|
||||
<span class="text-[10px] text-blue-600 font-semibold block mt-1">{{ \Carbon\Carbon::now()->translatedFormat('F Y') }}</span>
|
||||
<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">
|
||||
<div>
|
||||
<p class="text-[10px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p>
|
||||
<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>
|
||||
|
||||
<!-- 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">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p>
|
||||
<h3 class="text-2xl font-black text-emerald-800 mt-1">{{ number_format($insideCount, 0, ',', '.') }}</h3>
|
||||
<span class="text-[10px] text-emerald-600 font-semibold block mt-1">Area Proyek KMH</span>
|
||||
<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">
|
||||
<div>
|
||||
<p class="text-[10px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p>
|
||||
<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>
|
||||
|
||||
<!-- 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">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p>
|
||||
<h3 class="text-2xl font-black text-amber-800 mt-1">{{ number_format($outsideCount, 0, ',', '.') }}</h3>
|
||||
<span class="text-[10px] text-amber-600 font-semibold block mt-1">Workshop/Luar Proyek</span>
|
||||
<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">
|
||||
<div>
|
||||
<p class="text-[10px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p>
|
||||
<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>
|
||||
|
||||
<!-- Filter Card -->
|
||||
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs">
|
||||
<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 -->
|
||||
<div class="relative md:col-span-2">
|
||||
<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"
|
||||
name="search"
|
||||
value="{{ request('search') }}"
|
||||
placeholder="Cari No BAST, Unit, Lokasi, Driver, Pelapor..."
|
||||
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">
|
||||
</div>
|
||||
<!-- Kotak Pencarian & Filter Ramping (Inline Format Referensi HSE) -->
|
||||
<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">
|
||||
<!-- Search Text (Kiri) -->
|
||||
<div class="relative w-full sm:max-w-md">
|
||||
<span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
|
||||
<i class="fa-solid fa-magnifying-glass text-xs"></i>
|
||||
</span>
|
||||
<input type="text"
|
||||
name="search"
|
||||
id="transferSearchInput"
|
||||
value="{{ request('search') }}"
|
||||
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 -->
|
||||
<div>
|
||||
<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>
|
||||
@foreach($heavyUnits as $hu)
|
||||
<option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}>
|
||||
{{ $hu->code }} - {{ $hu->brand_type }}
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</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">
|
||||
<option value="all">Semua Alat Berat</option>
|
||||
@foreach($heavyUnits as $hu)
|
||||
<option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}>
|
||||
{{ $hu->code }} - {{ $hu->brand_type }}
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
|
||||
<!-- Filter Status Area Tujuan -->
|
||||
<div>
|
||||
<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="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>
|
||||
</select>
|
||||
</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">
|
||||
<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="outside_site" {{ request('to_site_status') === 'outside_site' ? 'selected' : '' }}>Di Luar Site</option>
|
||||
</select>
|
||||
|
||||
<!-- Tombol Filter & Reset -->
|
||||
<div class="flex items-center space-x-2">
|
||||
<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">
|
||||
Filter
|
||||
</button>
|
||||
@if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date']))
|
||||
<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">
|
||||
<i class="fa-solid fa-rotate-left"></i>
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date']))
|
||||
<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">
|
||||
<i class="fa-solid fa-rotate-left mr-1"></i>Reset
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- 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="overflow-x-auto">
|
||||
<table class="min-w-full text-xs text-left border-collapse">
|
||||
<!-- Header Tabel Navy Gelap Solid #06213f -->
|
||||
<thead class="bg-[#06213f] text-white font-bold text-[11px] uppercase tracking-wider">
|
||||
<tr>
|
||||
<th class="py-3.5 px-4 text-center w-12">NO</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap">TANGGAL & NO TRANSFER</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap">BERITA ACARA (BAST)</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap min-w-[180px]">UNIT ALAT BERAT</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap min-w-[200px]">PERPINDAHAN LOKASI</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap">ARMADA & SUPIR</th>
|
||||
<th class="py-3.5 px-4 whitespace-nowrap">PELAPOR</th>
|
||||
<th class="py-3.5 px-4 text-center whitespace-nowrap w-28">AKSI</th>
|
||||
<th class="py-3 px-3.5 text-center w-10">NO</th>
|
||||
<th class="py-3 px-3.5 whitespace-nowrap">DOKUMEN & TANGGAL</th>
|
||||
<th class="py-3 px-3.5 whitespace-nowrap">UNIT ALAT BERAT</th>
|
||||
<th class="py-3 px-3.5 whitespace-nowrap">RUTE PEMINDAHAN</th>
|
||||
<th class="py-3 px-3.5 whitespace-nowrap">PENGANGKUT & SUPIR</th>
|
||||
<th class="py-3 px-3.5 whitespace-nowrap">PELAPOR</th>
|
||||
<th class="py-3 px-3.5 text-center whitespace-nowrap w-24">AKSI</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100 text-slate-700 bg-white">
|
||||
@forelse($transfers as $index => $t)
|
||||
<tr class="hover:bg-slate-50/80 transition">
|
||||
<!-- 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 }}
|
||||
</td>
|
||||
|
||||
<!-- 2. Tanggal & No Transfer -->
|
||||
<td class="py-3.5 px-3.5 whitespace-nowrap">
|
||||
<div class="font-bold text-slate-900">
|
||||
{{ $t->transfer_date ? $t->transfer_date->translatedFormat('d M Y') : '-' }}
|
||||
</div>
|
||||
<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->transfer_no }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<!-- 3. Berita Acara -->
|
||||
<td class="py-3.5 px-3.5 min-w-[200px]">
|
||||
@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">
|
||||
<!-- 2. Dokumen BAST & Tanggal Transfer -->
|
||||
<td class="py-2.5 px-3.5 whitespace-nowrap">
|
||||
<div class="flex items-center space-x-1.5">
|
||||
@if($t->document_number)
|
||||
<span class="font-bold text-slate-900 font-mono text-xs">
|
||||
{{ $t->document_number }}
|
||||
</span>
|
||||
@if($t->document_file_path)
|
||||
<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>
|
||||
</a>
|
||||
@endif
|
||||
@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">
|
||||
<i class="fa-solid fa-truck-monster text-sm"></i>
|
||||
<span class="px-1.5 py-0.5 rounded text-[10px] font-bold text-slate-600 bg-slate-100 border border-slate-200">
|
||||
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">•</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>
|
||||
@endif
|
||||
<div>
|
||||
<div class="font-black text-slate-900 tracking-tight">
|
||||
<div class="font-black text-slate-900 tracking-tight text-xs">
|
||||
{{ $t->vehicle?->code ?? '-' }}
|
||||
</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 ?? '-' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<!-- 5. Lokasi Asal -> Lokasi Tujuan -->
|
||||
<td class="py-3.5 px-3.5">
|
||||
<div class="flex items-center space-x-1.5 text-xs">
|
||||
<!-- 4. Rute Pemindahan -->
|
||||
<td class="py-2.5 px-3.5">
|
||||
<div class="flex items-center space-x-1.5 text-xs whitespace-nowrap">
|
||||
<span class="text-slate-600 font-medium">{{ $t->from_location }}</span>
|
||||
<i class="fa-solid fa-arrow-right text-[10px] text-emerald-600"></i>
|
||||
<span class="font-extrabold text-[#1b5e20]">{{ $t->to_location }}</span>
|
||||
<i class="fa-solid fa-arrow-right text-[10px] text-slate-400"></i>
|
||||
<span class="font-bold text-[#1b5e20]">{{ $t->to_location }}</span>
|
||||
</div>
|
||||
<div class="mt-1">
|
||||
<div class="mt-0.5">
|
||||
@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>Di Dalam Site</span>
|
||||
</span>
|
||||
@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>Di Luar Site</span>
|
||||
</span>
|
||||
@@ -273,34 +267,39 @@
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<!-- 6. Armada & Supir Pengangkut -->
|
||||
<td class="py-3.5 px-3.5 whitespace-nowrap">
|
||||
<div class="font-semibold text-slate-800">
|
||||
<i class="fa-solid fa-truck-moving text-slate-400 mr-1 text-[11px]"></i>
|
||||
{{ $t->transporter_unit_name ?: ($t->transporterVehicle?->code ?? 'Tanpa Pengangkut') }}
|
||||
<!-- 5. Armada & Supir Pengangkut -->
|
||||
<td class="py-2.5 px-3.5 whitespace-nowrap">
|
||||
<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 text-[10px]"></i>
|
||||
<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 class="text-[11px] text-slate-500 mt-0.5">
|
||||
<i class="fa-solid fa-id-badge text-slate-400 mr-1 text-[11px]"></i>
|
||||
{{ $t->transporter_driver_name ?: ($t->transporterDriver?->name ?? '-') }}
|
||||
<div class="text-[11px] text-slate-500 mt-0.5 flex items-center gap-1.5">
|
||||
<span>{{ $t->transporter_driver_name ?: ($t->transporterDriver?->name ?? '-') }}</span>
|
||||
@if($t->transporter_origin_location)
|
||||
<span class="text-[10px] text-slate-400">| Asal: {{ $t->transporter_origin_location }}</span>
|
||||
@endif
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<!-- 7. Pelapor -->
|
||||
<td class="py-3.5 px-3.5 whitespace-nowrap">
|
||||
<div class="font-bold text-slate-800">
|
||||
<!-- 6. Pelapor -->
|
||||
<td class="py-2.5 px-3.5 whitespace-nowrap">
|
||||
<div class="font-bold text-slate-800 text-xs">
|
||||
{{ $t->reported_by }}
|
||||
</div>
|
||||
<div class="text-[10px] text-slate-400">
|
||||
Petugas QMA
|
||||
QMA
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<!-- 8. Aksi -->
|
||||
<td class="py-3.5 px-3.5 text-center whitespace-nowrap">
|
||||
<div class="inline-flex items-center space-x-1.5">
|
||||
<!-- 7. Aksi -->
|
||||
<td class="py-2.5 px-3.5 text-center whitespace-nowrap">
|
||||
<div class="inline-flex items-center space-x-1">
|
||||
<!-- Tombol Lihat Detail BAST -->
|
||||
<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">
|
||||
<i class="fa-solid fa-file-invoice text-xs"></i>
|
||||
</a>
|
||||
@@ -309,7 +308,7 @@
|
||||
@can('qma.vehicles.delete')
|
||||
<button type="button"
|
||||
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">
|
||||
<i class="fa-solid fa-trash text-xs"></i>
|
||||
</button>
|
||||
@@ -319,18 +318,18 @@
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="8" class="py-12 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">
|
||||
<td colspan="7" class="py-8 sm:py-10 text-center text-slate-400">
|
||||
<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>
|
||||
</div>
|
||||
<p class="text-sm 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">
|
||||
Belum ada transaksi pemindahan alat berat yang tercatat. Silakan klik tombol "Buat Transfer Unit" untuk membuat Berita Acara baru.
|
||||
<p class="text-xs font-bold text-slate-700">Belum Ada Data Pemindahan Unit</p>
|
||||
<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 di bawah untuk membuat Berita Acara baru.
|
||||
</p>
|
||||
@canany(['qma.vehicles.create', 'qma.vehicles.edit'])
|
||||
<div class="mt-4">
|
||||
<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">
|
||||
<i class="fa-solid fa-plus"></i>
|
||||
<div class="mt-3">
|
||||
<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 text-xs"></i>
|
||||
<span>Buat Transfer Unit Baru</span>
|
||||
</a>
|
||||
</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-900">
|
||||
{{ $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>
|
||||
</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>
|
||||
<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">
|
||||
@@ -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.
|
||||
</p>
|
||||
|
||||
<!-- KOLOM TANDA TANGAN (4 PIHAK) -->
|
||||
<!-- KOLOM TANDA TANGAN (2 PIHAK) -->
|
||||
<div class="pt-6">
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center text-xs">
|
||||
<!-- 1. Yang Menyerahkan (Driver / Pengangkut) -->
|
||||
<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 Menyerahkan / Pengangkut,</p>
|
||||
<div class="py-6">
|
||||
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-8 text-center text-xs max-w-2xl mx-auto">
|
||||
<!-- 1. Yang Melakukan / Mencatat Pemindahan -->
|
||||
<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-700 text-xs uppercase tracking-wider">Yang Mencatat Pemindahan,</p>
|
||||
<div class="py-8">
|
||||
<span class="text-[11px] text-slate-400 italic">( Tanda Tangan )</span>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1">
|
||||
{{ $transfer->transporter_driver_name ?: 'Driver Pengangkut' }}
|
||||
<p class="font-bold text-slate-900 border-t border-slate-300 pt-2 text-sm">
|
||||
{{ $transfer->user?->name ?? $transfer->reported_by }}
|
||||
</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>
|
||||
|
||||
<!-- 2. Yang Melaporkan (Petugas QMA) -->
|
||||
<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 Melaporkan,</p>
|
||||
<div class="py-6">
|
||||
<span class="text-[10px] text-slate-300 italic">(Tanda Tangan)</span>
|
||||
<!-- 2. Admin QMA (Mengetahui / Menyetujui) -->
|
||||
<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-700 text-xs uppercase tracking-wider">Mengetahui / Menyetujui,</p>
|
||||
<div class="py-8">
|
||||
<span class="text-[11px] text-slate-400 italic">( Tanda Tangan )</span>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-bold text-slate-900 border-t border-slate-300 pt-1">
|
||||
{{ $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 class="font-bold text-slate-900 border-t border-slate-300 pt-2 text-sm">
|
||||
( .................................... )
|
||||
</p>
|
||||
<p class="text-[10px] text-slate-400">PIC {{ $transfer->to_location }}</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>
|
||||
<p class="text-[11px] text-slate-500 font-medium">Admin QMA</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -645,6 +645,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
|
||||
<span>Divisi Penanggung Jawab</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / filter</span>
|
||||
</label>
|
||||
<input type="text" name="division" id="edit_division" list="divisionsDatalistSupportUnits" placeholder="Ketik atau pilih divisi..." class="w-full text-xs px-3.5 py-2 rounded-xl border border-slate-200 bg-white text-slate-800 font-medium focus:outline-none focus:border-emerald-600">
|
||||
<datalist id="divisionsDatalistSupportUnits">
|
||||
@foreach($availableDivisions ?? [] as $div)
|
||||
<option value="{{ $div }}">{{ $div }}</option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1.5">Dokumen SILO</label>
|
||||
@@ -1161,6 +1174,9 @@
|
||||
}
|
||||
document.getElementById('edit_silo').value = unit.silo_document || '';
|
||||
document.getElementById('edit_kir').value = unit.kir_document || '';
|
||||
if (document.getElementById('edit_division')) {
|
||||
document.getElementById('edit_division').value = unit.division || '';
|
||||
}
|
||||
|
||||
const editPhotoPreview = document.getElementById('editPhotoPreview');
|
||||
const editPhotoPlaceholder = document.getElementById('editPhotoPlaceholder');
|
||||
|
||||
+4
-3
@@ -88,7 +88,7 @@ Route::middleware('auth')->group(function () {
|
||||
Route::post('/vehicles/unit-support/{id}/units', [VehicleController::class, 'storeSupportUnit'])->name('vehicles.support.units.store')->middleware('permission:qma.vehicles.create');
|
||||
|
||||
Route::post('/vehicles', [VehicleController::class, 'store'])->name('vehicles.store')->middleware('permission:qma.vehicles.create');
|
||||
Route::post('/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit');
|
||||
Route::match(['PUT', 'POST'], '/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit');
|
||||
Route::delete('/vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy')->middleware('permission:qma.vehicles.delete');
|
||||
Route::get('/activity-log', [ActivityLogController::class, 'index'])->name('activity.log')->middleware('permission:qma.logs.view');
|
||||
Route::get('/activity-log/support-timesheet', [SupportTimesheetController::class, 'index'])->name('activity.support_timesheet')->middleware('permission:qma.logs.view');
|
||||
@@ -214,13 +214,14 @@ Route::middleware('auth')->group(function () {
|
||||
|
||||
// Log Riwayat Aktivitas Super Admin
|
||||
Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index');
|
||||
Route::post('/activity-logs/clear', [AdminActivityLogController::class, 'clear'])->name('activity_logs.clear');
|
||||
|
||||
// Backup & Restore Sistem (Database & Media)
|
||||
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
|
||||
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::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::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload');
|
||||
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1');
|
||||
|
||||
@@ -311,59 +311,32 @@ class BackupAndRestoreTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_inspect_server_kmh_backup(): void
|
||||
public function test_super_admin_can_inspect_and_convert_server_backup_file(): void
|
||||
{
|
||||
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_inspect_server.kmh');
|
||||
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, 'test_server_conv.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,
|
||||
// 1. Inspect server file via AJAX
|
||||
$inspectResponse = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'server_filename' => $filename,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJson([
|
||||
$inspectResponse->assertStatus(200);
|
||||
$inspectResponse->assertJson([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'filename' => 'arsip_lama_2bulan_lalu.kmh',
|
||||
'is_valid' => true,
|
||||
'encryption_cipher' => 'AES-256-CBC',
|
||||
],
|
||||
]);
|
||||
$token = $inspectResponse->json('data.token');
|
||||
$this->assertNotEmpty($token);
|
||||
|
||||
$this->assertContains('users', $response->json('data.tables'));
|
||||
}
|
||||
// 2. Convert using token to SQL
|
||||
$convResponse = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'token' => $token,
|
||||
'tables' => ['users'],
|
||||
'format' => 'sql',
|
||||
]);
|
||||
|
||||
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);
|
||||
$convResponse->assertStatus(200);
|
||||
$this->assertEquals('application/sql', $convResponse->headers->get('Content-Type'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use App\Models\VehicleLocationHistory;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CleanTestLogsCommandTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected User $superAdmin;
|
||||
protected User $regularUser;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed();
|
||||
$this->seedSampleData();
|
||||
|
||||
$this->superAdmin = User::where('role', 'super_admin')->first();
|
||||
$this->regularUser = User::where('role', 'employee')->first();
|
||||
}
|
||||
|
||||
public function test_artisan_clean_test_logs_command_cleans_activities_and_admin_logs(): void
|
||||
{
|
||||
// Pastikan ada data aktivitas dan log admin
|
||||
AdminActivityLog::record(
|
||||
actionType: 'create',
|
||||
module: 'Test Module',
|
||||
description: 'Uji coba aktivitas log admin'
|
||||
);
|
||||
|
||||
$vehicle = Vehicle::first();
|
||||
$employee = Employee::first();
|
||||
$gate = Gate::first();
|
||||
|
||||
VehicleActivity::create([
|
||||
'transaction_no' => 'TRX-TEST-001',
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $employee->id,
|
||||
'gate_id' => $gate->id,
|
||||
'direction' => 'in',
|
||||
'previous_km' => 95,
|
||||
'current_km' => 100,
|
||||
'distance' => 5,
|
||||
'purpose' => 'Uji Coba Lapangan',
|
||||
'recorded_at' => now(),
|
||||
'validation_status' => 'approved',
|
||||
]);
|
||||
|
||||
$this->assertGreaterThan(0, VehicleActivity::count());
|
||||
$this->assertGreaterThan(0, AdminActivityLog::count());
|
||||
|
||||
// Jalankan perintah artisan pembersihan
|
||||
$this->artisan('kmh:clean-test-logs --force')
|
||||
->assertSuccessful();
|
||||
|
||||
// Verifikasi log bersih
|
||||
$this->assertEquals(0, VehicleActivity::count());
|
||||
$this->assertEquals(0, VehicleLocationHistory::count());
|
||||
$this->assertEquals(0, AdminActivityLog::count());
|
||||
|
||||
// Verifikasi master data tetap utuh
|
||||
$this->assertGreaterThan(0, Vehicle::count());
|
||||
$this->assertGreaterThan(0, Employee::count());
|
||||
$this->assertGreaterThan(0, User::count());
|
||||
}
|
||||
|
||||
public function test_super_admin_can_clear_activity_logs_via_web(): void
|
||||
{
|
||||
AdminActivityLog::record(
|
||||
actionType: 'create',
|
||||
module: 'Test Module',
|
||||
description: 'Uji coba aktivitas log admin untuk web'
|
||||
);
|
||||
|
||||
$this->assertGreaterThan(0, AdminActivityLog::count());
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.activity_logs.clear'), [
|
||||
'confirmation' => 'KOSONGKAN',
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
$this->assertEquals(0, AdminActivityLog::count());
|
||||
}
|
||||
|
||||
public function test_non_super_admin_cannot_clear_activity_logs_via_web(): void
|
||||
{
|
||||
$response = $this->actingAs($this->regularUser)
|
||||
->post(route('admin.activity_logs.clear'), [
|
||||
'confirmation' => 'KOSONGKAN',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
}
|
||||
}
|
||||
@@ -190,4 +190,95 @@ class GateInspectionTest extends TestCase
|
||||
'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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase
|
||||
$this->assertSoftDeleted('users', ['id' => $linkedUser->id]);
|
||||
}
|
||||
|
||||
public function test_cannot_delete_employee_with_operational_records(): void
|
||||
public function test_can_delete_employee_with_operational_records_and_preserves_history(): void
|
||||
{
|
||||
$superAdmin = User::factory()->create([
|
||||
'username' => 'superadmin_check',
|
||||
@@ -290,7 +290,7 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase
|
||||
'current_km' => 1000,
|
||||
]);
|
||||
|
||||
\App\Models\VehicleActivity::create([
|
||||
$activity = \App\Models\VehicleActivity::create([
|
||||
'transaction_no' => 'TRX-TEST-001',
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $employee->id,
|
||||
@@ -309,8 +309,13 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase
|
||||
->from(route('hse.employees.index'))
|
||||
->delete(route('hse.employees.destroy', $employee->id));
|
||||
|
||||
$response->assertSessionHas('error');
|
||||
$this->assertDatabaseHas('employees', ['id' => $employee->id]);
|
||||
$response->assertSessionHas('success');
|
||||
$this->assertSoftDeleted('employees', ['id' => $employee->id]);
|
||||
|
||||
// Pastikan riwayat operasional tetap terhubung via withTrashed()
|
||||
$activityFresh = \App\Models\VehicleActivity::find($activity->id);
|
||||
$this->assertNotNull($activityFresh->driver);
|
||||
$this->assertEquals($employee->name, $activityFresh->driver->name);
|
||||
}
|
||||
|
||||
public function test_hse_edit_modal_and_edit_page_render_division_and_position_inputs(): void
|
||||
@@ -430,4 +435,245 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase
|
||||
'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'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,4 +284,97 @@ class HseEmployeeImportTest extends TestCase
|
||||
'simper_expired_at' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_import_restores_soft_deleted_user_and_employee_without_duplicate_error(): void
|
||||
{
|
||||
// Simulasi kondisi VPS: User dan Employee dengan NIK 1111 pernah dihapus ke Tong Sampah
|
||||
$user = User::create([
|
||||
'username' => '1111',
|
||||
'name' => 'Ruadi Lama',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$employee = Employee::create([
|
||||
'nik' => '1111',
|
||||
'name' => 'Ruadi Lama',
|
||||
'unit_kerja' => 'Umum',
|
||||
'division' => 'GA',
|
||||
'position' => 'Staff',
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
|
||||
$user->delete(); // Soft delete ke Tong Sampah
|
||||
$employee->delete(); // Soft delete ke Tong Sampah
|
||||
|
||||
$this->assertSoftDeleted('users', ['username' => '1111']);
|
||||
$this->assertSoftDeleted('employees', ['nik' => '1111']);
|
||||
|
||||
// Impor file yang mengandung NIK 1111
|
||||
$csvContent = implode("\n", [
|
||||
'No,NIK,Nama Lengkap,Unit Kerja,Divisi,Jabatan,Operator Driver,Masa Berlaku SIMPER',
|
||||
'1,1111,Ruadi Baru Terpulihkan,Pembangkit,Mekanik,Staff,TIDAK,',
|
||||
]);
|
||||
|
||||
$file = UploadedFile::fake()->createWithContent('import_with_trashed.csv', $csvContent);
|
||||
|
||||
$response = $this->actingAs($this->hseAdmin)
|
||||
->post(route('hse.employees.import'), [
|
||||
'file' => $file,
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
// Pastikan dipulihkan dan tidak terjadi SQL duplicate entry error
|
||||
$this->assertNotSoftDeleted('users', ['username' => '1111']);
|
||||
$this->assertNotSoftDeleted('employees', ['nik' => '1111']);
|
||||
|
||||
$user->refresh();
|
||||
$employee->refresh();
|
||||
|
||||
$this->assertEquals('Ruadi Baru Terpulihkan', $user->name);
|
||||
$this->assertEquals('Ruadi Baru Terpulihkan', $employee->name);
|
||||
$this->assertEquals('Pembangkit', $employee->unit_kerja);
|
||||
}
|
||||
|
||||
public function test_import_updates_only_division_without_overwriting_other_existing_fields(): void
|
||||
{
|
||||
$existing = Employee::create([
|
||||
'nik' => 'KMH-DIV-001',
|
||||
'name' => 'Budi Santoso',
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => '-',
|
||||
'position' => 'Supervisor Listrik',
|
||||
'is_operator' => true,
|
||||
'simper_expired_at' => '2027-01-01',
|
||||
]);
|
||||
|
||||
// Excel hanya mengisi NIK, Nama, dan Divisi (kolom lainnya kosong/None)
|
||||
$csvContent = implode("\n", [
|
||||
'No,NIK,Nama Lengkap,Unit Kerja,Divisi,Jabatan,Operator Driver,Masa Berlaku SIMPER',
|
||||
'1,KMH-DIV-001,Budi Santoso,,Electrical & Instrumentation,,,',
|
||||
]);
|
||||
|
||||
$file = UploadedFile::fake()->createWithContent('update_division_only.csv', $csvContent);
|
||||
|
||||
$response = $this->actingAs($this->hseAdmin)
|
||||
->post(route('hse.employees.import'), [
|
||||
'file' => $file,
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
$existing->refresh();
|
||||
|
||||
// Divisi terupdate
|
||||
$this->assertEquals('Electrical & Instrumentation', $existing->division);
|
||||
|
||||
// Data lain yang tidak diisi di Excel tetap dipertahankan utuh
|
||||
$this->assertEquals('Pembangkit', $existing->unit_kerja);
|
||||
$this->assertEquals('Supervisor Listrik', $existing->position);
|
||||
$this->assertTrue((bool)$existing->is_operator);
|
||||
$this->assertEquals('2027-01-01 00:00:00', $existing->simper_expired_at);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,4 +425,131 @@ class HseSimperTypeTest extends TestCase
|
||||
$this->assertSoftDeleted('simper_types', ['id' => $simperType->id]);
|
||||
$this->assertSoftDeleted('employee_simpers', ['id' => $empSimper->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER tanpa memasukkan tanggal masa berlaku ditolak dengan pesan error.
|
||||
*/
|
||||
public function test_checking_simper_without_expiry_date_fails_validation(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-TEST',
|
||||
'name' => 'SIMPER Dump Truck',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-01',
|
||||
'name' => 'Operator Test',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => '',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('error');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER dengan tanggal masa berlaku di masa lampau ditolak.
|
||||
*/
|
||||
public function test_checking_simper_with_past_expiry_date_fails_validation(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-PAST',
|
||||
'name' => 'SIMPER Dump Truck',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-02',
|
||||
'name' => 'Operator Test Past',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => Carbon::yesterday()->toDateString(),
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('error');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER dengan tanggal masa depan berhasil disimpan.
|
||||
*/
|
||||
public function test_checking_simper_with_future_expiry_date_succeeds(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-OK',
|
||||
'name' => 'SIMPER Dump Truck OK',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-03',
|
||||
'name' => 'Operator Test Future',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$futureDate = Carbon::now()->addMonths(6)->toDateString();
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => $futureDate,
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('success');
|
||||
$this->assertDatabaseHas('employee_simpers', [
|
||||
'employee_id' => $employee->id,
|
||||
'simper_type_id' => $type->id,
|
||||
'expired_at' => $futureDate . ' 00:00:00',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,6 +334,8 @@ class P2hInspectionTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Manitou MT-X 733',
|
||||
'unit_category' => 'Telehandler',
|
||||
'unit_type' => 'Telehandler',
|
||||
'operational_group' => 'HEAVY',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 0,
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
<?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');
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin QMA dapat mengedit data unit alat berat termasuk divisi penanggung jawab tanpa mereset atau menambah unit baru.
|
||||
*/
|
||||
public function test_qma_admin_can_update_unit_support_division_and_details(): void
|
||||
{
|
||||
$unit = Vehicle::where('code', 'DT-01')->firstOrFail();
|
||||
|
||||
$response = $this->actingAs($this->qmaAdmin)->post("/qma/vehicles/{$unit->id}", [
|
||||
'code' => 'DT-01',
|
||||
'category' => 'unit_support',
|
||||
'operational_group' => 'HAULING',
|
||||
'unit_type' => 'DUMP TRUCK',
|
||||
'division' => 'Civil & Dam Construction',
|
||||
'status' => 'Operation',
|
||||
'location' => 'Main Dam',
|
||||
'site_status' => 'inside_site',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
$response->assertRedirect();
|
||||
|
||||
$unit->refresh();
|
||||
$this->assertEquals('Civil & Dam Construction', $unit->division);
|
||||
$this->assertEquals('HAULING', $unit->operational_group);
|
||||
$this->assertEquals('DUMP TRUCK', $unit->unit_type);
|
||||
}
|
||||
}
|
||||
@@ -155,6 +155,7 @@ class QmaModuleTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Caterpillar D6R',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'unit_type' => 'Track-type Tractor',
|
||||
'brand' => 'Caterpillar',
|
||||
'model_number' => 'D6R XL',
|
||||
@@ -174,6 +175,7 @@ class QmaModuleTest extends TestCase
|
||||
'code' => 'DZ01',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'silo_document' => 'SILO-2026/01',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -675,4 +675,61 @@ class QmaSupportTimesheetTest extends TestCase
|
||||
'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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,7 +302,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
$vehicle->refresh();
|
||||
$this->assertEquals('inside_site', $vehicle->site_status);
|
||||
$this->assertEquals($this->gate->name, $vehicle->location);
|
||||
$this->assertEquals($this->guard->name, $vehicle->location_updated_by);
|
||||
$this->assertEquals($this->gateOfficer->name, $vehicle->location_updated_by);
|
||||
$this->assertStringContainsString('TRX-IN-001', $vehicle->location_note);
|
||||
|
||||
// Verifikasi riwayat tersimpan otomatis bersumber gate_crossing
|
||||
@@ -312,7 +312,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
'location' => $this->gate->name,
|
||||
'source' => 'gate_crossing',
|
||||
'vehicle_activity_id' => $activity->id,
|
||||
'user_name' => $this->guard->name,
|
||||
'user_name' => $this->gateOfficer->name,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -362,7 +362,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
$vehicle->refresh();
|
||||
$this->assertEquals('outside_site', $vehicle->site_status);
|
||||
$this->assertEquals('Luar Site - Antar Dokumen ke Kantor Jambi', $vehicle->location);
|
||||
$this->assertEquals($this->guard->name, $vehicle->location_updated_by);
|
||||
$this->assertEquals($this->gateOfficer->name, $vehicle->location_updated_by);
|
||||
|
||||
// Verifikasi riwayat tersimpan otomatis
|
||||
$this->assertDatabaseHas('vehicle_location_histories', [
|
||||
|
||||
@@ -379,4 +379,37 @@ class QmaUnitTransferTest extends TestCase
|
||||
$this->assertEquals('Adit 2 Intake', $transporterHistory->location);
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\User;
|
||||
@@ -175,4 +176,98 @@ class SecurityGuardFilterTest extends TestCase
|
||||
$this->assertSoftDeleted('users', ['id' => $userId]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Memastikan petugas Satpam yang dinonaktifkan tidak dapat login dan ditolak middleware.
|
||||
*/
|
||||
public function test_deactivated_guard_cannot_login_and_blocked_by_middleware(): void
|
||||
{
|
||||
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-001')->first();
|
||||
$this->assertNotNull($guard);
|
||||
$user = $guard->user;
|
||||
$this->assertNotNull($user);
|
||||
|
||||
// 1. Nonaktifkan petugas satpam
|
||||
$guard->update(['is_active' => false]);
|
||||
|
||||
// Coba login -> Harus ditolak
|
||||
$loginResponse = $this->post(route('login'), [
|
||||
'username' => $user->username,
|
||||
'password' => 'password',
|
||||
]);
|
||||
$loginResponse->assertSessionHasErrors('username');
|
||||
$this->assertGuest();
|
||||
|
||||
// 2. Jika dalam sesi aktif tapi di-nonaktifkan -> Middleware tolak dengan 403
|
||||
$middlewareResponse = $this->actingAs($user)->get(route('pg.dashboard'));
|
||||
$middlewareResponse->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_admin_pg_can_edit_guard_badge_id_and_syncs_with_user_and_employee(): void
|
||||
{
|
||||
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-002')->first();
|
||||
$this->assertNotNull($guard);
|
||||
$this->assertNotNull($guard->user);
|
||||
|
||||
// Pastikan ada Employee dengan NIK lama
|
||||
$emp = Employee::firstOrCreate(
|
||||
['nik' => 'SEC-002'],
|
||||
[
|
||||
'user_id' => $guard->user_id,
|
||||
'name' => $guard->name,
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
]
|
||||
);
|
||||
|
||||
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
|
||||
'badge_id' => 'SEC-002-EDIT',
|
||||
'name' => 'Budi Santoso Diperbarui',
|
||||
'team' => 3,
|
||||
'password' => 'newpassword123',
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHasNoErrors();
|
||||
|
||||
// Verifikasi SecurityGuard
|
||||
$guard->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $guard->badge_id);
|
||||
$this->assertEquals('Budi Santoso Diperbarui', $guard->name);
|
||||
$this->assertEquals(3, $guard->team);
|
||||
|
||||
// Verifikasi User login
|
||||
$guard->user->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $guard->user->username);
|
||||
$this->assertEquals('[email protected]', $guard->user->email);
|
||||
|
||||
// Verifikasi Employee NIK
|
||||
$emp->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $emp->nik);
|
||||
$this->assertEquals('Budi Santoso Diperbarui', $emp->name);
|
||||
|
||||
// Verifikasi login dengan ID baru dan password baru
|
||||
$this->post('/logout');
|
||||
$loginResponse = $this->post('/login', [
|
||||
'username' => 'SEC-002-EDIT',
|
||||
'password' => 'newpassword123',
|
||||
]);
|
||||
$loginResponse->assertRedirect();
|
||||
$this->assertAuthenticatedAs($guard->user);
|
||||
}
|
||||
|
||||
public function test_editing_guard_with_duplicate_badge_id_is_rejected(): void
|
||||
{
|
||||
$guard = SecurityGuard::where('badge_id', 'SEC-002')->first();
|
||||
|
||||
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
|
||||
'badge_id' => 'SEC-001', // sudah dipakai oleh guard 1
|
||||
'name' => 'Budi Duplicate',
|
||||
'team' => 2,
|
||||
]);
|
||||
|
||||
$response->assertSessionHasErrors('badge_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ class UnitSupportBusinessProcessTest extends TestCase
|
||||
->get(route('qma.vehicles.support'));
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('TEST-CAT');
|
||||
$response->assertSee('Tambah Kategori Heavy Equipment');
|
||||
$response->assertSee('Tambah Unit');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class UserSoftDeleteAndProtectionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed();
|
||||
}
|
||||
|
||||
public function test_deleting_user_with_operational_history_soft_deletes_cleanly_without_500(): void
|
||||
{
|
||||
$superAdmin = User::where('username', 'superadmin')->first();
|
||||
|
||||
// Buat user & employee sukon/karyawan
|
||||
$user = User::factory()->create([
|
||||
'name' => 'Supri Driver',
|
||||
'username' => '123456',
|
||||
'email' => '[email protected]',
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$user->assignRole('employee');
|
||||
|
||||
$employee = Employee::create([
|
||||
'user_id' => $user->id,
|
||||
'nik' => '123456',
|
||||
'name' => 'Supri Driver',
|
||||
'employee_type' => 'Sukon',
|
||||
'division' => 'subkon',
|
||||
'position' => 'Driver',
|
||||
'is_operator' => true,
|
||||
]);
|
||||
|
||||
$gate = Gate::first() ?: Gate::create(['name' => 'Gate Utama', 'code' => 'GU-01']);
|
||||
$vehicle = Vehicle::first() ?: Vehicle::factory()->create();
|
||||
|
||||
// Buat aktivitas riwayat operasional kendaraan
|
||||
$activity = VehicleActivity::create([
|
||||
'transaction_no' => 'TRX-SUPRI-001',
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $employee->id,
|
||||
'gate_id' => $gate->id,
|
||||
'direction' => 'out',
|
||||
'previous_km' => 1000,
|
||||
'current_km' => 1050,
|
||||
'distance' => 50,
|
||||
'purpose' => 'Pengiriman Material',
|
||||
'recorded_at' => now(),
|
||||
'status' => 'approved',
|
||||
]);
|
||||
|
||||
// Super Admin menghapus akun user Supri dari menu Kelola Pengguna
|
||||
$response = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.users.destroy', $user->id));
|
||||
|
||||
// Harus berhasil redirect tanpa error 500
|
||||
$response->assertStatus(302);
|
||||
$response->assertRedirect(route('admin.users.index'));
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
// Pastikan User & Employee berstatus Soft Deleted (ada di tong sampah)
|
||||
$this->assertSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertSoftDeleted('employees', ['id' => $employee->id]);
|
||||
|
||||
// Pastikan riwayat aktivitas operasional tetap UTUH dan tidak hilang
|
||||
$this->assertDatabaseHas('vehicle_activities', [
|
||||
'id' => $activity->id,
|
||||
'driver_id' => $employee->id,
|
||||
]);
|
||||
|
||||
// Coba lakukan Hapus Permanen dari Tong Sampah -> Harus ditolak karena integritas audit
|
||||
$forceResponse = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.trash.force_delete', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$forceResponse->assertStatus(302);
|
||||
$forceResponse->assertSessionHas('error');
|
||||
|
||||
// User tetap ada di basis data (tidak terhapus permanen)
|
||||
$this->assertDatabaseHas('users', ['id' => $user->id]);
|
||||
|
||||
// Pulihkan akun dari Tong Sampah -> User & Employee harus aktif kembali beserta perannya
|
||||
$restoreResponse = $this->actingAs($superAdmin)
|
||||
->post(route('admin.trash.restore', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$restoreResponse->assertStatus(302);
|
||||
$restoreResponse->assertSessionHas('success');
|
||||
|
||||
$this->assertNotSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertNotSoftDeleted('employees', ['id' => $employee->id]);
|
||||
$this->assertTrue($user->fresh()->hasRole('employee'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user