Compare commits
48
Commits
aad095f0f9
...
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 | ||
|
|
433f07b505 | ||
|
|
2addb8ed4f | ||
|
|
18e4e6471e | ||
|
|
39a5ee67ef | ||
|
|
b0469611d7 | ||
|
|
f7b92a1c71 | ||
|
|
2ced848e3a | ||
|
|
6ee58817ce | ||
|
|
e3414b39af | ||
|
|
19e5418f9a | ||
|
|
6603b710d7 | ||
|
|
40767d2117 | ||
|
|
1e1286e3e2 | ||
|
|
48678df82b | ||
|
|
2c959ca392 | ||
|
|
315830c924 | ||
|
|
7675c3e500 | ||
|
|
68ff69e8e4 | ||
|
|
852404be32 | ||
|
|
af61766546 | ||
|
|
03af709a12 | ||
|
|
ee83b9d189 |
+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.
+2
-25
@@ -1,25 +1,5 @@
|
||||
# =========================================================================
|
||||
# STAGE 1: Frontend Asset Compilation via Vite & Node.js
|
||||
# =========================================================================
|
||||
FROM node:22-alpine AS frontend-builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy dependency manifests
|
||||
COPY package.json package-lock.json* ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci || npm install
|
||||
|
||||
# Copy source assets needed for compilation
|
||||
COPY vite.config.js ./
|
||||
COPY resources/ ./resources/
|
||||
|
||||
# Compile production assets into /app/public/build
|
||||
RUN npm run build
|
||||
|
||||
# =========================================================================
|
||||
# STAGE 2: PHP 8.3-FPM Alpine Production Runtime
|
||||
# PHP 8.3-FPM Alpine Production Runtime
|
||||
# =========================================================================
|
||||
FROM php:8.3-fpm-alpine AS app
|
||||
|
||||
@@ -63,12 +43,9 @@ COPY docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN sed -i 's/\r$//' /usr/local/bin/docker-entrypoint.sh \
|
||||
&& chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
# Copy application source code
|
||||
# Copy application source code (termasuk public/build pre-compiled dari git)
|
||||
COPY . /var/www
|
||||
|
||||
# Copy compiled frontend assets from Stage 1 (Overrides public/build)
|
||||
COPY --from=frontend-builder /app/public/build /var/www/public/build
|
||||
|
||||
# Install Composer production dependencies
|
||||
RUN composer install --no-dev --optimize-autoloader --no-interaction
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,8 @@ 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;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
@@ -18,7 +20,8 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
class BackupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected DatabaseBackupService $backupService
|
||||
protected DatabaseBackupService $backupService,
|
||||
protected KmhConverterService $converterService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -60,7 +63,35 @@ class BackupController extends Controller
|
||||
$log->file_exists = File::exists($fullPath);
|
||||
});
|
||||
|
||||
return view('admin.backups.index', compact('backupLogs', 'backups', 'stats', 'tableGroups'));
|
||||
// Ambil info batas upload server PHP saat ini
|
||||
$uploadMax = ini_get('upload_max_filesize') ?: '256M';
|
||||
$postMax = ini_get('post_max_size') ?: '256M';
|
||||
$maxUploadBytes = min($this->parseIniBytes($uploadMax), $this->parseIniBytes($postMax));
|
||||
$maxUploadHuman = $this->backupService->formatBytes($maxUploadBytes);
|
||||
|
||||
return view('admin.backups.index', compact('backupLogs', 'backups', 'stats', 'tableGroups', 'maxUploadBytes', 'maxUploadHuman'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Konversi notasi string PHP INI (misal 256M, 1G) ke byte integer.
|
||||
*/
|
||||
protected function parseIniBytes(string $val): int
|
||||
{
|
||||
$val = trim($val);
|
||||
$last = strtolower($val[strlen($val) - 1] ?? '');
|
||||
$num = (int) $val;
|
||||
switch ($last) {
|
||||
case 'g':
|
||||
$num *= 1024 * 1024 * 1024;
|
||||
break;
|
||||
case 'm':
|
||||
$num *= 1024 * 1024;
|
||||
break;
|
||||
case 'k':
|
||||
$num *= 1024;
|
||||
break;
|
||||
}
|
||||
return $num > 0 ? $num : 268435456; // Fallback 256 MB
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -192,11 +223,11 @@ class BackupController extends Controller
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'backup_file' => ['required', 'file', 'max:204800'], // Maks. 200 MB
|
||||
'backup_file' => ['required', 'file', 'max:1048576'], // Maks. 1024 MB (1 GB)
|
||||
], [
|
||||
'backup_file.required' => 'Pilih file backup yang ingin diunggah.',
|
||||
'backup_file.file' => 'File yang diunggah tidak valid.',
|
||||
'backup_file.max' => 'Ukuran file backup maksimal 200 MB.',
|
||||
'backup_file.max' => 'Ukuran file backup maksimal 1 GB.',
|
||||
]);
|
||||
|
||||
$originalName = basename($file->getClientOriginalName());
|
||||
@@ -348,8 +379,22 @@ 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) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -381,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ class RolePermissionController extends Controller
|
||||
$role = Role::findOrFail($roleId);
|
||||
|
||||
// Proteksi role inti sistem
|
||||
$coreRoles = ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer'];
|
||||
$coreRoles = ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'];
|
||||
if (in_array($role->name, $coreRoles)) {
|
||||
return redirect()->route('admin.roles.index')
|
||||
->with('error', "Aksi Ditolak: Role inti sistem [{$role->name}] tidak dapat dihapus.");
|
||||
|
||||
@@ -73,6 +73,7 @@ class TrashController extends Controller
|
||||
*/
|
||||
public function forceDelete(string $category, int $id): RedirectResponse
|
||||
{
|
||||
try {
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
|
||||
if (!$success) {
|
||||
@@ -91,6 +92,9 @@ class TrashController extends Controller
|
||||
);
|
||||
|
||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||
} catch (\Throwable $e) {
|
||||
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,6 +103,28 @@ class UserController extends Controller
|
||||
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
|
||||
}
|
||||
|
||||
$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'],
|
||||
@@ -111,6 +134,7 @@ class UserController extends Controller
|
||||
'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,8 +420,10 @@ class UserController extends Controller
|
||||
$userRole = $user->role ?? '';
|
||||
$userId = $user->id;
|
||||
|
||||
$user->syncRoles([]);
|
||||
try {
|
||||
DB::transaction(function () use ($user) {
|
||||
$user->delete();
|
||||
});
|
||||
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
@@ -409,7 +438,11 @@ class UserController extends Controller
|
||||
);
|
||||
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
|
||||
->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,11 +3,16 @@
|
||||
namespace App\Http\Controllers\Employee;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\P2hRecord;
|
||||
use App\Models\UnitSupportTimesheet;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use App\Services\P2hInspectionPdfExporter;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class DashboardController extends Controller
|
||||
@@ -199,6 +204,278 @@ class DashboardController extends Controller
|
||||
'rejection_note' => $activity->rejection_note,
|
||||
'recorded_at' => $activity->recorded_at ? $activity->recorded_at->format('H:i') . ' WIB' : null,
|
||||
'validated_at' => $activity->validated_at ? $activity->validated_at->format('H:i') . ' WIB' : null,
|
||||
])->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan halaman Riwayat Aktivitas Pribadi Karyawan.
|
||||
* Mengisolasi data hanya milik karyawan yang sedang login (P2H, Timesheet Alat Berat, dan Perjalanan LV).
|
||||
* Tab yang tampil dinamis menyesuaikan hak akses dan catatan riwayat yang dimiliki karyawan.
|
||||
*/
|
||||
public function history(Request $request): View
|
||||
{
|
||||
$user = auth()->user();
|
||||
if (!$user->isSuperAdmin() && !$user->can('employee.dashboard') && !$user->can('employee.timesheet') && !$user->can('employee.p2h') && !$user->isEmployee()) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki wewenang untuk membuka halaman riwayat aktivitas karyawan.');
|
||||
}
|
||||
|
||||
$employee = $user->getOrCreateEmployee();
|
||||
|
||||
// 1. Cek riwayat aktual yang pernah dikerjakan oleh karyawan
|
||||
$hasP2hRecords = $employee ? P2hRecord::where('employee_id', $employee->id)->exists() : false;
|
||||
$hasTimesheetRecords = $employee ? UnitSupportTimesheet::where('operator_id', $employee->id)->exists() : false;
|
||||
$hasTripRecords = $employee ? VehicleActivity::where('driver_id', $employee->id)->exists() : false;
|
||||
|
||||
// 2. Cek kualifikasi SIMPER karyawan terhadap jenis armada (Heavy Equipment vs Light Vehicle)
|
||||
$canHeavy = $user->isSuperAdmin() || ($employee && $employee->canOperateHeavyEquipment());
|
||||
$canLv = $user->isSuperAdmin() || ($employee && $employee->canDriveLightVehicle());
|
||||
|
||||
// 3. Modul P2H Heavy Equipment:
|
||||
// Hanya tampil jika karyawan memiliki riwayat P2H ATAU (memiliki hak akses employee.p2h DAN izin SIMPER alat berat)
|
||||
$canP2h = $hasP2hRecords || ($user->can('employee.p2h') && $canHeavy);
|
||||
|
||||
// 4. Modul Timesheet Heavy Equipment:
|
||||
// Hanya tampil jika karyawan memiliki riwayat timesheet ATAU (memiliki izin SIMPER alat berat dan status operator)
|
||||
$canTimesheet = $hasTimesheetRecords || ($canHeavy && ($employee?->is_operator || $user->can('qma.logs.view')));
|
||||
|
||||
// 5. Modul Perjalanan Pos Gerbang (LV):
|
||||
// Tampil jika karyawan memiliki riwayat perjalanan ATAU (memiliki hak akses employee.timesheet dan SIMPER LV)
|
||||
$canTrips = $hasTripRecords || ($user->can('employee.timesheet') && ($canLv || !$canHeavy));
|
||||
|
||||
// Hitung total catatan riwayat per kategori untuk badge tab
|
||||
$p2hCount = $employee ? P2hRecord::where('employee_id', $employee->id)->count() : 0;
|
||||
$timesheetCount = $employee ? UnitSupportTimesheet::where('operator_id', $employee->id)->count() : 0;
|
||||
$tripCount = $employee ? VehicleActivity::where('driver_id', $employee->id)->count() : 0;
|
||||
|
||||
// Tentukan tab aktif
|
||||
$availableTabs = [];
|
||||
if ($canP2h) {
|
||||
$availableTabs[] = 'p2h';
|
||||
}
|
||||
if ($canTimesheet) {
|
||||
$availableTabs[] = 'timesheet';
|
||||
}
|
||||
if ($canTrips) {
|
||||
$availableTabs[] = 'trips';
|
||||
}
|
||||
|
||||
$requestedTab = $request->query('tab');
|
||||
if ($requestedTab && in_array($requestedTab, $availableTabs, true)) {
|
||||
$activeTab = $requestedTab;
|
||||
} else {
|
||||
$activeTab = $availableTabs[0] ?? 'none';
|
||||
}
|
||||
|
||||
// Filter parameter
|
||||
$search = trim((string) $request->query('search', ''));
|
||||
$dateFrom = $request->query('date_from');
|
||||
$dateTo = $request->query('date_to');
|
||||
$status = $request->query('status');
|
||||
|
||||
$p2hRecords = collect();
|
||||
$timesheetRecords = collect();
|
||||
$tripRecords = collect();
|
||||
|
||||
// Query data khusus tab aktif
|
||||
if ($employee && $activeTab === 'p2h') {
|
||||
$query = P2hRecord::with(['vehicle', 'template', 'validator'])
|
||||
->where('employee_id', $employee->id);
|
||||
|
||||
if ($search !== '') {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('transaction_no', 'like', "%{$search}%")
|
||||
->orWhereHas('vehicle', function ($vq) use ($search) {
|
||||
$vq->where('code', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if ($dateFrom) {
|
||||
$query->whereDate('inspected_at', '>=', $dateFrom);
|
||||
}
|
||||
if ($dateTo) {
|
||||
$query->whereDate('inspected_at', '<=', $dateTo);
|
||||
}
|
||||
|
||||
if ($status) {
|
||||
if (in_array($status, ['pending', 'approved', 'rejected'], true)) {
|
||||
$query->where('validation_status', $status);
|
||||
} elseif (in_array($status, ['good', 'has_defect'], true)) {
|
||||
$query->where('summary_condition', $status);
|
||||
}
|
||||
}
|
||||
|
||||
$p2hRecords = $query->latest('inspected_at')
|
||||
->latest('id')
|
||||
->paginate(15)
|
||||
->withQueryString();
|
||||
} elseif ($employee && $activeTab === 'timesheet') {
|
||||
$query = UnitSupportTimesheet::with(['vehicle'])
|
||||
->where('operator_id', $employee->id);
|
||||
|
||||
if ($search !== '') {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('timesheet_no', 'like', "%{$search}%")
|
||||
->orWhere('location', 'like', "%{$search}%")
|
||||
->orWhere('task_description', 'like', "%{$search}%")
|
||||
->orWhereHas('vehicle', function ($vq) use ($search) {
|
||||
$vq->where('code', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if ($dateFrom) {
|
||||
$query->whereDate('date', '>=', $dateFrom);
|
||||
}
|
||||
if ($dateTo) {
|
||||
$query->whereDate('date', '<=', $dateTo);
|
||||
}
|
||||
|
||||
if ($status) {
|
||||
$query->where('status', $status);
|
||||
}
|
||||
|
||||
$timesheetRecords = $query->latest('date')
|
||||
->latest('id')
|
||||
->paginate(15)
|
||||
->withQueryString();
|
||||
} elseif ($employee && $activeTab === 'trips') {
|
||||
$query = VehicleActivity::with(['vehicle', 'gate', 'securityGuard'])
|
||||
->where('driver_id', $employee->id);
|
||||
|
||||
if ($search !== '') {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('transaction_no', 'like', "%{$search}%")
|
||||
->orWhere('purpose', 'like', "%{$search}%")
|
||||
->orWhereHas('vehicle', function ($vq) use ($search) {
|
||||
$vq->where('code', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%")
|
||||
->orWhere('license_plate', 'like', "%{$search}%");
|
||||
})
|
||||
->orWhereHas('gate', function ($gq) use ($search) {
|
||||
$gq->where('name', 'like', "%{$search}%");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if ($dateFrom) {
|
||||
$query->whereDate('recorded_at', '>=', $dateFrom);
|
||||
}
|
||||
if ($dateTo) {
|
||||
$query->whereDate('recorded_at', '<=', $dateTo);
|
||||
}
|
||||
|
||||
if ($status) {
|
||||
$query->where('validation_status', $status);
|
||||
}
|
||||
|
||||
$tripRecords = $query->latest('recorded_at')
|
||||
->latest('id')
|
||||
->paginate(15)
|
||||
->withQueryString();
|
||||
}
|
||||
|
||||
// Ringkasan KPI pribadi karyawan
|
||||
$stats = [
|
||||
'p2h_total' => $p2hCount,
|
||||
'p2h_good' => $employee ? P2hRecord::where('employee_id', $employee->id)->where('summary_condition', 'good')->count() : 0,
|
||||
'p2h_defects' => $employee ? P2hRecord::where('employee_id', $employee->id)->where('summary_condition', 'has_defect')->count() : 0,
|
||||
'timesheet_total' => $timesheetCount,
|
||||
'timesheet_hours' => $employee ? (float) UnitSupportTimesheet::where('operator_id', $employee->id)->sum('operating_hours') : 0.0,
|
||||
'trip_total' => $tripCount,
|
||||
'trip_distance' => $employee ? (float) VehicleActivity::where('driver_id', $employee->id)->sum('distance') : 0.0,
|
||||
];
|
||||
|
||||
return view('employee.history', compact(
|
||||
'employee',
|
||||
'canP2h',
|
||||
'canTimesheet',
|
||||
'canTrips',
|
||||
'p2hCount',
|
||||
'timesheetCount',
|
||||
'tripCount',
|
||||
'activeTab',
|
||||
'p2hRecords',
|
||||
'timesheetRecords',
|
||||
'tripRecords',
|
||||
'stats',
|
||||
'search',
|
||||
'dateFrom',
|
||||
'dateTo',
|
||||
'status'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Detail checklist P2H pribadi karyawan (Format JSON untuk modal inspeksi).
|
||||
*/
|
||||
public function p2hDetail(int $id): JsonResponse
|
||||
{
|
||||
$user = auth()->user();
|
||||
$employee = $user->getOrCreateEmployee();
|
||||
|
||||
$record = P2hRecord::with(['vehicle', 'employee', 'template', 'validator', 'items'])
|
||||
->findOrFail($id);
|
||||
|
||||
if (!$user->isSuperAdmin() && (!$employee || $record->employee_id !== $employee->id)) {
|
||||
abort(403, 'Aksi Ditolak: Anda hanya dapat melihat lembar pemeriksaan P2H milik Anda sendiri.');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'id' => $record->id,
|
||||
'transaction_no' => $record->transaction_no,
|
||||
'vehicle_code' => $record->vehicle?->code ?? '-',
|
||||
'vehicle_name' => $record->vehicle?->brand_type ?? '-',
|
||||
'template_name' => $record->template?->name ?? 'P2H Checksheet',
|
||||
'shift' => $record->shift,
|
||||
'start_hm' => $record->start_hm,
|
||||
'start_km' => $record->start_km,
|
||||
'summary_condition' => $record->summary_condition,
|
||||
'defect_count' => $record->defect_count,
|
||||
'general_notes' => $record->general_notes,
|
||||
'validation_status' => $record->validation_status,
|
||||
'validator_name' => $record->validator?->name,
|
||||
'validation_notes' => $record->validation_notes,
|
||||
'validated_at' => $record->validated_at ? $record->validated_at->format('d/m/Y H:i') : null,
|
||||
'inspected_at' => $record->inspected_at ? $record->inspected_at->format('d/m/Y H:i') : null,
|
||||
'items' => $record->items->map(function ($item) {
|
||||
return [
|
||||
'id' => $item->id,
|
||||
'item_name' => $item->title,
|
||||
'section' => $item->section,
|
||||
'condition' => $item->condition_status,
|
||||
'notes' => $item->notes,
|
||||
];
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download / Cetak PDF lembar pemeriksaan P2H pribadi milik karyawan.
|
||||
*/
|
||||
public function p2hPdf(int $id): Response
|
||||
{
|
||||
$user = auth()->user();
|
||||
$employee = $user->getOrCreateEmployee();
|
||||
|
||||
$record = P2hRecord::with(['vehicle', 'employee', 'template', 'validator', 'items'])
|
||||
->findOrFail($id);
|
||||
|
||||
if (!$user->isSuperAdmin() && (!$employee || $record->employee_id !== $employee->id)) {
|
||||
abort(403, 'Aksi Ditolak: Anda hanya dapat mengunduh lembar pemeriksaan P2H milik Anda sendiri.');
|
||||
}
|
||||
|
||||
$pdfBinary = P2hInspectionPdfExporter::generate($record);
|
||||
$fileName = 'Lembar_P2H_' . ($record->vehicle->code ?? 'Unit') . '_' . $record->transaction_no . '.pdf';
|
||||
|
||||
return response($pdfBinary, 200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'inline; filename="' . $fileName . '"',
|
||||
'Content-Length' => strlen($pdfBinary),
|
||||
'Cache-Control' => 'private, max-age=0, must-revalidate',
|
||||
'Pragma' => 'public',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,6 +718,23 @@ class EmployeeController extends Controller
|
||||
$user->update(['photo_path' => $photoPath]);
|
||||
}
|
||||
|
||||
$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'],
|
||||
@@ -641,6 +747,7 @@ class EmployeeController extends Controller
|
||||
'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,55 +888,41 @@ 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;
|
||||
$photoPath = $employee->photo_path;
|
||||
|
||||
DB::transaction(function () use ($employee, $photoPath) {
|
||||
DB::transaction(function () use ($employee) {
|
||||
$user = $employee->user ?: User::where('username', $employee->nik)->first();
|
||||
|
||||
// Hapus berkas foto profil jika tersimpan secara lokal di storage
|
||||
if ($photoPath) {
|
||||
ImageCompressionService::deleteIfExists($photoPath);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -812,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;
|
||||
}
|
||||
|
||||
@@ -823,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) {
|
||||
@@ -845,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]);
|
||||
} 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',
|
||||
]);
|
||||
}
|
||||
} elseif ($fallbackDate) {
|
||||
// Fallback untuk form sederhana / pengujian yang mengirimkan 1 tanggal simper_expired_at
|
||||
} else {
|
||||
// Jika belum ada SIMPER sama sekali, buatkan SIMPER-LV default
|
||||
$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' => $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 pengujian sederhana yang mengirimkan 1 tanggal simper_expired_at
|
||||
$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' => $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;
|
||||
@@ -150,7 +151,7 @@ class GateInspectionController extends Controller
|
||||
'count' => $pendingActivities->count(),
|
||||
'items' => $items,
|
||||
'html' => view('pg.partials.queue_cards', compact('pendingActivities', 'currentGuard', 'guards'))->render(),
|
||||
]);
|
||||
])->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -159,23 +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) {
|
||||
$fallbackGuard = SecurityGuard::where('is_active', true)->first() ?? SecurityGuard::first();
|
||||
if ($fallbackGuard) {
|
||||
$guardId = $fallbackGuard->id;
|
||||
} else {
|
||||
$request->validate([
|
||||
'security_guard_id' => ['required', 'exists:security_guards,id'],
|
||||
], [
|
||||
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam yang melakukan pemeriksaan.',
|
||||
]);
|
||||
$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') {
|
||||
@@ -183,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) {
|
||||
@@ -241,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') {
|
||||
@@ -272,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.");
|
||||
@@ -767,4 +770,20 @@ class P2hInspectionController extends Controller
|
||||
|
||||
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} DITOLAK. Status unit diubah ke Breakdown.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus pemeriksaan P2H Heavy Equipment (Soft Delete).
|
||||
* Data yang dihapus akan dipindahkan ke Tong Sampah dan dapat dipulihkan sewaktu-waktu.
|
||||
*/
|
||||
public function destroy(int $id): RedirectResponse
|
||||
{
|
||||
$record = P2hRecord::findOrFail($id);
|
||||
$trxNo = $record->transaction_no;
|
||||
|
||||
// Cascade soft delete record items
|
||||
$record->items()->delete();
|
||||
$record->delete();
|
||||
|
||||
return redirect()->route('qma.p2h.index')->with('success', "Data pemeriksaan P2H [{$trxNo}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,19 +134,29 @@ 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');
|
||||
})
|
||||
->with(['parent.requiredSimperType', 'requiredSimperType'])
|
||||
->orderBy('code')
|
||||
->get();
|
||||
|
||||
@@ -154,9 +164,50 @@ class SupportTimesheetController extends Controller
|
||||
->orderBy('name')
|
||||
->get(['id', 'nik', 'name', 'position', 'is_operator', 'employee_type', 'simper_expired_at']);
|
||||
|
||||
// Pemetaan kualifikasi SIMPER: Unit ID => Daftar Operator ID yang memiliki izin SIMPER sah
|
||||
$unitOperatorsMap = [];
|
||||
foreach ($unitSupports as $u) {
|
||||
$eligibleIds = [];
|
||||
foreach ($operators as $op) {
|
||||
if ($op->hasValidSimperForVehicle($u)) {
|
||||
$eligibleIds[] = $op->id;
|
||||
}
|
||||
}
|
||||
$unitOperatorsMap[$u->id] = $eligibleIds;
|
||||
}
|
||||
|
||||
$shifts = self::SHIFTS;
|
||||
$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';
|
||||
@@ -178,6 +229,7 @@ class SupportTimesheetController extends Controller
|
||||
'breakdownCount',
|
||||
'unitSupports',
|
||||
'operators',
|
||||
'unitOperatorsMap',
|
||||
'shifts',
|
||||
'activityTypes',
|
||||
'locationSuggestions',
|
||||
@@ -254,30 +306,58 @@ class SupportTimesheetController extends Controller
|
||||
'activity_type.required' => 'Kategori pekerjaan wajib diisi.',
|
||||
]);
|
||||
|
||||
$vehicle = Vehicle::findOrFail($validated['vehicle_id']);
|
||||
$operator = Employee::findOrFail($validated['operator_id']);
|
||||
$vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
|
||||
$operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
|
||||
|
||||
if (!$operator->hasValidSimperForVehicle($vehicle)) {
|
||||
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
|
||||
return back()
|
||||
->withInput()
|
||||
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
|
||||
}
|
||||
|
||||
$startMeter = (float) $validated['start_meter'];
|
||||
$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;
|
||||
$shift = $validated['shift'] ?: 'Shift Siang';
|
||||
|
||||
$timesheetNo = UnitSupportTimesheet::generateTimesheetNo(Carbon::parse($validated['date']));
|
||||
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;
|
||||
|
||||
DB::transaction(function () use (
|
||||
$validated,
|
||||
$vehicle,
|
||||
$operator,
|
||||
$timesheetNo,
|
||||
$startMeter,
|
||||
$endMeter,
|
||||
$operatingHours,
|
||||
$shift,
|
||||
$updaterName
|
||||
$updaterName,
|
||||
&$timesheetNo
|
||||
) {
|
||||
// Generate nomor timesheet unik di dalam transaksi untuk meminimalkan bentrokan
|
||||
$timesheetNo = UnitSupportTimesheet::generateTimesheetNo(Carbon::parse($validated['date']));
|
||||
|
||||
// 1. Simpan Data Timesheet Heavy Equipment
|
||||
$timesheet = UnitSupportTimesheet::create([
|
||||
'timesheet_no' => $timesheetNo,
|
||||
@@ -302,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'],
|
||||
@@ -332,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -401,6 +505,18 @@ class SupportTimesheetController extends Controller
|
||||
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
|
||||
$shift = $validated['shift'] ?: 'Shift Siang';
|
||||
|
||||
$vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
|
||||
$operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
|
||||
|
||||
if ((int) $timesheet->operator_id !== (int) $operator->id || (int) $timesheet->vehicle_id !== (int) $vehicle->id) {
|
||||
if (!$operator->hasValidSimperForVehicle($vehicle)) {
|
||||
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
|
||||
return back()
|
||||
->withInput()
|
||||
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
|
||||
}
|
||||
}
|
||||
|
||||
$timesheet->update([
|
||||
'vehicle_id' => $validated['vehicle_id'],
|
||||
'operator_id' => $validated['operator_id'],
|
||||
@@ -422,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -476,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,
|
||||
@@ -488,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,
|
||||
@@ -571,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') : '-',
|
||||
@@ -579,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,15 +260,26 @@ 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
|
||||
$transporterDriverName = !empty($validated['transporter_driver_name']) ? trim($validated['transporter_driver_name']) : null;
|
||||
@@ -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}"
|
||||
@@ -323,6 +378,7 @@ class UnitTransferController extends Controller
|
||||
$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);
|
||||
@@ -1187,12 +1639,9 @@ class VehicleController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
foreach ($vehicle->units as $u) {
|
||||
ImageCompressionService::deleteIfExists($u->photo_path);
|
||||
}
|
||||
}
|
||||
ImageCompressionService::deleteIfExists($vehicle->photo_path);
|
||||
// Berkas fisik foto tidak dihapus di sini karena data masuk ke Tong Sampah (Soft Delete).
|
||||
// Berkas foto akan tetap aman sehingga jika dipulihkan (restore), foto unit tetap ada.
|
||||
// Berkas fisik baru dihapus permanen ketika dieksekusi 'Hapus Permanen' di TrashService.
|
||||
|
||||
$code = $vehicle->code;
|
||||
$vehicle->delete();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -67,6 +67,20 @@ class StoreVehicleActivityRequest extends FormRequest
|
||||
// 1. Validasi SIMPER Pengemudi (BR-01 & BR-02)
|
||||
$driver = Employee::find($this->input('driver_id'));
|
||||
if ($driver) {
|
||||
// Proteksi IDOR: Karyawan biasa tidak boleh memalsukan perjalanan atas nama karyawan lain yang memiliki akun sendiri
|
||||
$user = $this->user();
|
||||
if ($user) {
|
||||
$userEmployee = $user->getOrCreateEmployee();
|
||||
$isStaffAdmin = $user->isSuperAdmin() || $user->isPgAdmin() || $user->isGateOfficer() || $user->isHseAdmin() || $user->isQmaAdmin();
|
||||
if (!$isStaffAdmin && $userEmployee && $driver->id !== $userEmployee->id && !empty($driver->user_id) && $driver->user_id !== $user->id) {
|
||||
$validator->errors()->add(
|
||||
'driver_id',
|
||||
"Akses Ditolak: Anda tidak diizinkan mencatatkan aktivitas kendaraan atas nama karyawan lain ({$driver->name}). Gunakan akun pribadi Anda."
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$driver->is_operator) {
|
||||
$validator->errors()->add(
|
||||
'driver_id',
|
||||
|
||||
+109
-8
@@ -140,11 +140,12 @@ class Employee extends Model
|
||||
return $this->hasValidSimper();
|
||||
}
|
||||
|
||||
// 1. Jika kendaraan mensyaratkan spesifik required_simper_type_id
|
||||
if ($vehicle->required_simper_type_id) {
|
||||
// 1. Jika kendaraan atau parent category kendaraan mensyaratkan spesifik required_simper_type_id
|
||||
$requiredTypeId = $vehicle->required_simper_type_id ?? $vehicle->parent?->required_simper_type_id;
|
||||
if ($requiredTypeId) {
|
||||
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->get();
|
||||
foreach ($simpers as $s) {
|
||||
if ($s->simper_type_id === $vehicle->required_simper_type_id && $s->isValid()) {
|
||||
if ($s->simper_type_id === $requiredTypeId && $s->isValid()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -159,23 +160,45 @@ class Employee extends Model
|
||||
}
|
||||
|
||||
if ($vehicle->isUnitSupport()) {
|
||||
$catName = $vehicle->unit_category ?: $vehicle->parent?->unit_category;
|
||||
$brandName = $vehicle->brand_type ?: $vehicle->parent?->brand_type;
|
||||
|
||||
// Cek apakah personil memiliki izin SIMPER dengan scope kategori alat berat ini (misal: 'Dump Truck', 'Excavator', dll.)
|
||||
if ($vehicle->unit_category && $this->hasValidSimperForScope($vehicle->unit_category)) {
|
||||
if ($catName && $this->hasValidSimperForScope($catName)) {
|
||||
return true;
|
||||
}
|
||||
if ($vehicle->brand_type && $this->hasValidSimperForScope($vehicle->brand_type)) {
|
||||
if ($brandName && $this->hasValidSimperForScope($brandName)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($vehicle->is_timesheet_mobile) {
|
||||
// Cek jika brand type mengandung kategori spesifik yang dimiliki SIMPER personil
|
||||
if ($brandName) {
|
||||
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->with('simperType')->get();
|
||||
foreach ($simpers as $s) {
|
||||
if ($s->isValid() && $s->simperType) {
|
||||
foreach ($s->simperType->scopes as $scope) {
|
||||
if (!in_array($scope, [SimperType::SCOPE_ALL, SimperType::SCOPE_LIGHT_VEHICLE, SimperType::SCOPE_UNIT_SUPPORT_MOBILE, SimperType::SCOPE_UNIT_SUPPORT_HEAVY], true)) {
|
||||
if (stripos($brandName, $scope) !== false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$isMobile = $vehicle->is_timesheet_mobile
|
||||
|| ($vehicle->parent && $vehicle->parent->is_timesheet_mobile)
|
||||
|| str_starts_with(strtoupper($vehicle->code), 'DT')
|
||||
|| (stripos($catName ?? '', 'Dump Truck') !== false);
|
||||
|
||||
if ($isMobile) {
|
||||
return $this->hasValidSimperForType('SIMPER-DT')
|
||||
|| $this->hasValidSimperForType('SIMPER-HEAVY')
|
||||
|| $this->hasValidSimperForScope('unit_support_mobile')
|
||||
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
|
||||
}
|
||||
|
||||
return $this->hasValidSimperForType('SIMPER-HEAVY')
|
||||
|| $this->hasValidSimperForType('SIMPER-DT')
|
||||
|| $this->hasValidSimperForScope('unit_support_heavy')
|
||||
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
|
||||
}
|
||||
@@ -183,6 +206,84 @@ class Employee extends Model
|
||||
return $this->hasValidSimper();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cek apakah personil memiliki izin SIMPER aktif yang mencakup Heavy Equipment / Unit Support (Alat Berat atau Dump Truck).
|
||||
*/
|
||||
public function canOperateHeavyEquipment(): bool
|
||||
{
|
||||
$hasAnySimper = $this->relationLoaded('simpers') ? $this->simpers->isNotEmpty() : $this->simpers()->exists();
|
||||
|
||||
if ($hasAnySimper) {
|
||||
$simpers = $this->relationLoaded('simpers')
|
||||
? $this->simpers
|
||||
: $this->simpers()->with('simperType')->get();
|
||||
|
||||
foreach ($simpers as $s) {
|
||||
if ($s->isValid() && $s->simperType) {
|
||||
$type = $s->simperType;
|
||||
// Cakupan Universal (Semua Armada)
|
||||
if ($type->coversScope(SimperType::SCOPE_ALL)) {
|
||||
return true;
|
||||
}
|
||||
// Cakupan Heavy Equipment atau Mobile Unit Support (Dump Truck)
|
||||
if ($type->coversScope(SimperType::SCOPE_UNIT_SUPPORT_HEAVY)
|
||||
|| $type->coversScope(SimperType::SCOPE_UNIT_SUPPORT_MOBILE)
|
||||
|| $type->code === 'SIMPER-HEAVY'
|
||||
|| $type->code === 'SIMPER-DT') {
|
||||
return true;
|
||||
}
|
||||
// Cakupan kategori spesifik (Excavator, Bulldozer, Crane, dll.)
|
||||
foreach ($type->scopes as $scope) {
|
||||
if ($scope !== SimperType::SCOPE_LIGHT_VEHICLE && $scope !== 'light_vehicle') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fallback untuk driver/operator legacy: jika belum multi-simper, hanya jika ditandai is_operator
|
||||
// dan posisinya mengandung kata 'operator', 'heavy', 'excavator', 'dt', dsb.
|
||||
if ($this->is_operator && $this->hasValidSimper()) {
|
||||
$pos = strtolower($this->position ?? '');
|
||||
if (str_contains($pos, 'operator') || str_contains($pos, 'alat berat') || str_contains($pos, 'excavator') || str_contains($pos, 'dt') || str_contains($pos, 'dump truck')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cek apakah personil memiliki izin SIMPER aktif untuk kendaraan ringan (Light Vehicle).
|
||||
*/
|
||||
public function canDriveLightVehicle(): bool
|
||||
{
|
||||
$hasAnySimper = $this->relationLoaded('simpers') ? $this->simpers->isNotEmpty() : $this->simpers()->exists();
|
||||
|
||||
if ($hasAnySimper) {
|
||||
$simpers = $this->relationLoaded('simpers')
|
||||
? $this->simpers
|
||||
: $this->simpers()->with('simperType')->get();
|
||||
|
||||
foreach ($simpers as $s) {
|
||||
if ($s->isValid() && $s->simperType) {
|
||||
if ($s->simperType->coversScope(SimperType::SCOPE_ALL)
|
||||
|| $s->simperType->coversScope(SimperType::SCOPE_LIGHT_VEHICLE)
|
||||
|| $s->simperType->code === 'SIMPER-LV') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->hasValidSimper();
|
||||
}
|
||||
|
||||
public function getPhotoUrlAttribute(): ?string
|
||||
{
|
||||
$path = $this->photo_path;
|
||||
|
||||
@@ -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,8 +65,56 @@ 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.
|
||||
*/
|
||||
public static function generateTimesheetNo(?Carbon $date = null): string
|
||||
{
|
||||
@@ -69,7 +122,8 @@ class UnitSupportTimesheet extends Model
|
||||
$dateStr = $d->format('Ymd');
|
||||
$prefix = "TS-US-{$dateStr}-";
|
||||
|
||||
$last = self::where('timesheet_no', 'like', "{$prefix}%")
|
||||
$last = self::withTrashed()
|
||||
->where('timesheet_no', 'like', "{$prefix}%")
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
@@ -78,6 +132,14 @@ class UnitSupportTimesheet extends Model
|
||||
$seq = ((int) $matches[1]) + 1;
|
||||
}
|
||||
|
||||
return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
|
||||
$candidate = $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
|
||||
|
||||
// Mitigasi bentrokan concurrency: cek apakah candidate sudah pernah digunakan (termasuk soft deletes)
|
||||
while (self::withTrashed()->where('timesheet_no', $candidate)->exists()) {
|
||||
$seq++;
|
||||
$candidate = $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
return $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+17
-8
@@ -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();
|
||||
$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.");
|
||||
}
|
||||
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.");
|
||||
} 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
|
||||
|
||||
@@ -23,6 +23,11 @@ class AppServiceProvider extends ServiceProvider
|
||||
\Carbon\Carbon::setLocale('id');
|
||||
date_default_timezone_set(config('app.timezone', 'Asia/Jakarta'));
|
||||
|
||||
// Deteksi HTTPS dari Cloudflare Reverse Proxy / Tunnel
|
||||
if (request()->header('x-forwarded-proto') === 'https' || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') || str_starts_with(config('app.url'), 'https://')) {
|
||||
\Illuminate\Support\Facades\URL::forceScheme('https');
|
||||
}
|
||||
|
||||
// Super Admin bypass: secara otomatis memiliki izin untuk semua ability
|
||||
Gate::before(function ($user, $ability) {
|
||||
if (in_array($user->role, ['super_admin', 'superadmin', 'admin'])) {
|
||||
|
||||
@@ -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.');
|
||||
@@ -242,8 +242,8 @@ class DatabaseBackupService
|
||||
*/
|
||||
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
|
||||
@@ -674,37 +674,37 @@ 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());
|
||||
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, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
|
||||
|
||||
$rowCount = count($rows);
|
||||
$i = 0;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$i++;
|
||||
$values = [];
|
||||
|
||||
foreach ((array) $row as $val) {
|
||||
foreach ($row as $val) {
|
||||
if (is_null($val)) {
|
||||
$values[] = 'NULL';
|
||||
} elseif (is_int($val) || is_float($val)) {
|
||||
@@ -716,14 +716,26 @@ class DatabaseBackupService
|
||||
}
|
||||
}
|
||||
|
||||
$line = ' (' . implode(', ', $values) . ')';
|
||||
$line .= ($i === $rowCount) ? ";\n" : ",\n";
|
||||
fwrite($handle, $line);
|
||||
}
|
||||
});
|
||||
$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");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format byte ke satuan yang mudah dibaca (KB, MB, GB).
|
||||
|
||||
@@ -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>';
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ class SimpleXlsxImporter
|
||||
$sharedStrings = [];
|
||||
$sharedXmlContent = $zip->getFromName('xl/sharedStrings.xml');
|
||||
if ($sharedXmlContent) {
|
||||
$xml = @simplexml_load_string($sharedXmlContent);
|
||||
$xml = @simplexml_load_string($sharedXmlContent, 'SimpleXMLElement', LIBXML_NONET);
|
||||
if ($xml && isset($xml->si)) {
|
||||
foreach ($xml->si as $si) {
|
||||
if (isset($si->t)) {
|
||||
@@ -112,7 +112,7 @@ class SimpleXlsxImporter
|
||||
return $rows;
|
||||
}
|
||||
|
||||
$xml = @simplexml_load_string($sheetXmlContent);
|
||||
$xml = @simplexml_load_string($sheetXmlContent, 'SimpleXMLElement', LIBXML_NONET);
|
||||
$zip->close();
|
||||
|
||||
if (!$xml || !isset($xml->sheetData->row)) {
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\UnitTransfer;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use App\Services\ImageCompressionService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -377,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) {
|
||||
@@ -421,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();
|
||||
@@ -432,6 +468,32 @@ class TrashService
|
||||
->forceDelete();
|
||||
}
|
||||
|
||||
// Hapus berkas fisik saat benar-benar dihapus permanen dari tong sampah
|
||||
if ($item instanceof Vehicle) {
|
||||
ImageCompressionService::deleteIfExists($item->photo_path);
|
||||
if (method_exists($item, 'isSupportCategory') && $item->isSupportCategory()) {
|
||||
foreach ($item->units as $u) {
|
||||
ImageCompressionService::deleteIfExists($u->photo_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($item instanceof Employee) {
|
||||
ImageCompressionService::deleteIfExists($item->photo_path);
|
||||
}
|
||||
|
||||
if ($item instanceof User) {
|
||||
$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);
|
||||
}
|
||||
|
||||
$item->forceDelete();
|
||||
});
|
||||
|
||||
@@ -450,8 +512,12 @@ class TrashService
|
||||
$model = $categories[$category]['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
try {
|
||||
$this->forceDeleteItem($category, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
return $totalDeleted;
|
||||
}
|
||||
@@ -461,8 +527,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,8 +561,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
|
||||
foreach ($expiredItems as $item) {
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$prunedCount++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -11,6 +11,8 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->trustProxies(at: '*');
|
||||
|
||||
$middleware->alias([
|
||||
'role' => \App\Http\Middleware\CheckRole::class,
|
||||
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
|
||||
@@ -18,5 +20,9 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
]);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
//
|
||||
$exceptions->render(function (\Illuminate\Http\Exceptions\PostTooLargeException $e, $request) {
|
||||
$postMax = ini_get('post_max_size') ?: '256M';
|
||||
$uploadMax = ini_get('upload_max_filesize') ?: '256M';
|
||||
return back()->with('error', "Ukuran file yang Anda kirim terlalu besar dan melebihi batas konfigurasi server PHP (post_max_size: {$postMax}, upload_max_filesize: {$uploadMax}). Harap naikkan batas konfigurasi php.ini atau gunakan file yang lebih kecil.");
|
||||
});
|
||||
})->create();
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
@@ -11,29 +10,36 @@ return new class extends Migration
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$guardUsers = User::where('role', 'gate_officer')->get();
|
||||
$guardUsers = DB::table('users')->where('role', 'gate_officer')->get();
|
||||
foreach ($guardUsers as $user) {
|
||||
$emp = Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
$emp = DB::table('employees')
|
||||
->where('user_id', $user->id)
|
||||
->orWhere('nik', $user->username)
|
||||
->first();
|
||||
|
||||
if ($emp) {
|
||||
$emp->update([
|
||||
DB::table('employees')->where('id', $emp->id)->update([
|
||||
'user_id' => $user->id,
|
||||
'name' => $user->name,
|
||||
'unit_kerja' => $emp->unit_kerja ?: 'Private Guard',
|
||||
'division' => ($emp->division && $emp->division !== '-') ? $emp->division : 'Private Guard',
|
||||
'position' => ($emp->position && $emp->position !== '-') ? $emp->position : 'Anggota',
|
||||
'employee_type' => $emp->employee_type ?: 'Karyawan',
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
} else {
|
||||
Employee::create([
|
||||
DB::table('employees')->insert([
|
||||
'user_id' => $user->id,
|
||||
'nik' => $user->username,
|
||||
'name' => $user->name,
|
||||
'photo_path' => $user->photo_path,
|
||||
'photo_path' => $user->photo_path ?? null,
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
'is_operator' => false,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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).");
|
||||
|
||||
@@ -22,6 +22,7 @@ services:
|
||||
volumes:
|
||||
- rkm_storage:/var/www/storage
|
||||
- rkm_bootstrap_cache:/var/www/bootstrap/cache
|
||||
- ./docker/php/local.ini:/usr/local/etc/php/conf.d/local.ini:ro
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
# =============================================================================
|
||||
# NGINX CONFIGURATION FOR RKM SISTEM (PORT 80 - CLOUDFLARE TUNNEL READY)
|
||||
# =============================================================================
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
server_name localhost rkm.kmhindonesia.com _;
|
||||
root /var/www/public;
|
||||
index index.php index.html;
|
||||
|
||||
client_max_body_size 40M;
|
||||
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;
|
||||
@@ -48,10 +57,12 @@ server {
|
||||
fastcgi_pass app:9000;
|
||||
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
|
||||
include fastcgi_params;
|
||||
fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;
|
||||
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 = 40M
|
||||
post_max_size = 40M
|
||||
memory_limit = 512M
|
||||
max_execution_time = 300
|
||||
max_input_time = 300
|
||||
upload_max_filesize = 500M
|
||||
post_max_size = 500M
|
||||
memory_limit = 1024M
|
||||
max_execution_time = 3600
|
||||
max_input_time = 3600
|
||||
date.timezone = Asia/Jakarta
|
||||
expose_php = Off
|
||||
|
||||
+14
-14
@@ -18,19 +18,19 @@
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
||||
<env name="CACHE_STORE" value="array"/>
|
||||
<env name="DB_CONNECTION" value="sqlite"/>
|
||||
<env name="DB_DATABASE" value=":memory:"/>
|
||||
<env name="DB_URL" value=""/>
|
||||
<env name="MAIL_MAILER" value="array"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||
<env name="SESSION_DRIVER" value="array"/>
|
||||
<env name="PULSE_ENABLED" value="false"/>
|
||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
||||
<env name="NIGHTWATCH_ENABLED" value="false"/>
|
||||
<env name="APP_ENV" value="testing" force="true"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file" force="true"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4" force="true"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null" force="true"/>
|
||||
<env name="CACHE_STORE" value="array" force="true"/>
|
||||
<env name="DB_CONNECTION" value="sqlite" force="true"/>
|
||||
<env name="DB_DATABASE" value=":memory:" force="true"/>
|
||||
<env name="DB_URL" value="" force="true"/>
|
||||
<env name="MAIL_MAILER" value="array" force="true"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync" force="true"/>
|
||||
<env name="SESSION_DRIVER" value="array" force="true"/>
|
||||
<env name="PULSE_ENABLED" value="false" force="true"/>
|
||||
<env name="TELESCOPE_ENABLED" value="false" force="true"/>
|
||||
<env name="NIGHTWATCH_ENABLED" value="false" force="true"/>
|
||||
</php>
|
||||
</phpunit>
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"resources/css/app.css": {
|
||||
"file": "assets/app-CSwKW6_z.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
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
@section('content')
|
||||
<div class="space-y-6">
|
||||
<!-- Header Halaman (Clean Minimalist) -->
|
||||
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-2 border-b border-slate-100">
|
||||
<div>
|
||||
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 pb-4 border-b border-slate-100">
|
||||
<div class="min-w-0 flex-1">
|
||||
<h1 class="text-xl font-bold text-slate-900 tracking-tight">
|
||||
Backup & Restore Sistem
|
||||
</h1>
|
||||
@@ -14,15 +14,20 @@
|
||||
Pencadangan terenkripsi berformat <code>.kmh</code> khusus untuk sistem RKM-KMH. Langsung unduh ke komputer lokal dan hemat kapasitas disk VPS server.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<div class="flex items-center gap-2.5 shrink-0 self-start md:self-auto">
|
||||
<button type="button"
|
||||
onclick="openConverterModal()"
|
||||
class="whitespace-nowrap px-4 py-2.5 rounded-xl border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-emerald-900 text-xs font-semibold transition shadow-2xs inline-flex items-center gap-1.5">
|
||||
Konversi Berkas .kmh
|
||||
</button>
|
||||
<button type="button"
|
||||
onclick="openDirectRestoreModal()"
|
||||
class="px-3.5 py-2 rounded-xl border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 text-xs font-semibold transition shadow-2xs">
|
||||
class="whitespace-nowrap px-4 py-2.5 rounded-xl border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 text-xs font-semibold transition shadow-2xs inline-flex items-center gap-1.5">
|
||||
Pulihkan dari File .kmh
|
||||
</button>
|
||||
<button type="button"
|
||||
onclick="openCreateBackupModal()"
|
||||
class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs">
|
||||
class="whitespace-nowrap px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs inline-flex items-center gap-1.5">
|
||||
Buat Backup Baru
|
||||
</button>
|
||||
</div>
|
||||
@@ -230,6 +235,13 @@
|
||||
Unduh
|
||||
</a>
|
||||
|
||||
<button type="button"
|
||||
onclick="openServerConverterModal('{{ $log->filename }}')"
|
||||
title="Konversi langsung berkas arsip ini ke Excel / CSV / SQL tanpa perlu upload ulang dari PC"
|
||||
class="px-2.5 py-1 rounded-lg border border-indigo-200 bg-indigo-50 hover:bg-indigo-100 text-indigo-800 font-semibold text-[11px] transition">
|
||||
Konversi
|
||||
</button>
|
||||
|
||||
<button type="button"
|
||||
onclick="openRestoreModal('{{ $log->filename }}', '{{ $log->scope_label }}', '{{ $log->file_size_human }}')"
|
||||
class="px-2.5 py-1 rounded-lg border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 font-semibold text-[11px] transition">
|
||||
@@ -428,8 +440,13 @@
|
||||
<strong>Perhatian:</strong> Proses ini akan menggantikan dan menyinkronkan data sistem saat ini dengan arsip <code>.kmh</code> yang Anda pulihkan.
|
||||
</div>
|
||||
|
||||
<!-- Error Banner Direct Restore -->
|
||||
<div id="directRestoreError" class="hidden p-3 bg-rose-50 border border-rose-200 rounded-xl text-xs text-rose-800 font-medium">
|
||||
<span id="directRestoreErrorMessage"></span>
|
||||
</div>
|
||||
|
||||
<!-- Dropzone Area Interaktif dengan Drag & Drop -->
|
||||
<div>
|
||||
<div id="directRestoreDropzoneContainer">
|
||||
<label class="block text-xs font-semibold text-slate-700 mb-1.5">Pilih atau Drag & Drop File .kmh</label>
|
||||
<div id="directRestoreDropzone"
|
||||
class="border-2 border-dashed border-slate-300 hover:border-amber-500 rounded-2xl p-6 text-center bg-slate-50 hover:bg-white transition cursor-pointer select-none"
|
||||
@@ -444,7 +461,7 @@
|
||||
</div>
|
||||
<p class="text-xs font-bold text-slate-800" id="directRestoreFileName">Tarik & Letakkan file .kmh di sini</p>
|
||||
<p class="text-[11px] text-slate-400 mt-1">atau <span class="text-amber-700 font-semibold underline">klik untuk memilih dari komputer Anda</span></p>
|
||||
<p class="text-[10px] text-slate-400 mt-1.5">Format didukung: .kmh terenkripsi (Maks. 200 MB)</p>
|
||||
<p class="text-[10px] text-slate-400 mt-1.5">Format didukung: .kmh terenkripsi (Batas upload server: {{ $maxUploadHuman ?? '256 MB' }})</p>
|
||||
</div>
|
||||
|
||||
<div id="directRestoreFileDisplay" class="hidden mt-1 p-3 rounded-xl bg-amber-50 border border-amber-200 text-left">
|
||||
@@ -469,6 +486,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Real-time Upload Progress Bar untuk Direct Restore -->
|
||||
<div id="directRestoreLoading" class="hidden py-4 space-y-3">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="font-bold text-slate-800 flex items-center gap-2">
|
||||
<span class="w-2 h-2 rounded-full bg-amber-500 animate-pulse"></span>
|
||||
<span id="directRestoreLoadingText">Mengunggah berkas backup ke server...</span>
|
||||
</span>
|
||||
<span id="directRestoreUploadPercentText" class="font-mono font-bold text-amber-700">0%</span>
|
||||
</div>
|
||||
<!-- Progress Bar Track -->
|
||||
<div class="w-full bg-slate-100 rounded-full h-3 overflow-hidden border border-slate-200">
|
||||
<div id="directRestoreProgressBar" class="bg-gradient-to-r from-amber-500 to-orange-500 h-3 rounded-full transition-all duration-150 ease-out" style="width: 0%"></div>
|
||||
</div>
|
||||
<div class="flex items-center justify-between text-[11px] text-slate-400">
|
||||
<span id="directRestoreUploadByteText">0 MB / 0 MB</span>
|
||||
<span id="directRestoreUploadSubText">Mohon tunggu, koneksi sedang mengirim data...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Konfirmasi Keamanan -->
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-800 mb-1">
|
||||
@@ -632,6 +668,185 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========================================================================= -->
|
||||
<!-- MODAL: KONVERTER ARSIP BERKAS .KMH KE EXCEL / CSV / SQL -->
|
||||
<!-- ========================================================================= -->
|
||||
<div id="kmhConverterModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
|
||||
<div class="bg-white rounded-2xl max-w-3xl w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100 my-8">
|
||||
<!-- Header Modal -->
|
||||
<div class="px-6 py-4 bg-slate-50 border-b border-slate-200/80 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||
KMH CONVERTER
|
||||
</span>
|
||||
<div>
|
||||
<h3 class="text-base font-bold text-slate-900">Konversi Berkas .kmh ke Excel / CSV / SQL</h3>
|
||||
<p class="text-xs text-slate-500 mt-0.5">Unggah berkas .kmh dari komputer untuk dikonversi menjadi format siap olah tanpa menyentuh database aktif.</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onclick="closeConverterModal()" class="text-slate-400 hover:text-slate-600 text-xl p-1 leading-none">×</button>
|
||||
</div>
|
||||
|
||||
<div class="p-6 space-y-5">
|
||||
<!-- Alert Zero Retention & Database Safety -->
|
||||
<div class="p-3 bg-emerald-50/70 border border-emerald-200/80 rounded-xl text-xs text-emerald-950 flex items-start gap-2.5">
|
||||
<span class="inline-block w-2 h-2 rounded-full bg-emerald-600 mt-1 shrink-0"></span>
|
||||
<div>
|
||||
<strong class="font-semibold text-emerald-900">Keamanan Total & Bebas Kapasitas Server:</strong>
|
||||
Proses konversi bersifat <em>read-only</em> dan <strong>sama sekali tidak menyentuh database aktif MySQL</strong>. Berkas yang diunggah hanya diproses sementara di memori dan langsung dihapus otomatis seketika setelah unduhan dimulai (0 Byte tertinggal di VPS).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Banner -->
|
||||
<div id="converterError" class="hidden p-3 bg-rose-50 border border-rose-200 rounded-xl text-xs text-rose-800 font-medium">
|
||||
<span id="converterErrorMessage"></span>
|
||||
</div>
|
||||
|
||||
<!-- Step 1: Area Dropzone Upload dari PC -->
|
||||
<div id="panelConverterUpload" class="space-y-3">
|
||||
<div id="converterDropzone"
|
||||
class="border-2 border-dashed border-slate-300 hover:border-emerald-500 rounded-2xl p-7 text-center bg-slate-50 hover:bg-emerald-50/20 transition cursor-pointer select-none"
|
||||
onclick="document.getElementById('converterFileInput').click()"
|
||||
ondragover="handleDropzoneDragOver(event, this)"
|
||||
ondragleave="handleDropzoneDragLeave(event, this)"
|
||||
ondrop="handleConverterFileDrop(event, this)">
|
||||
<p class="text-xs font-bold text-slate-800" id="converterDropzonePrompt">Tarik & Letakkan berkas .kmh di sini</p>
|
||||
<p class="text-[11px] text-slate-400 mt-1">atau <span class="text-emerald-600 font-semibold underline">klik untuk memilih dari komputer Anda</span></p>
|
||||
<p class="text-[10px] text-slate-400 mt-2">Mendukung berkas arsip .kmh terenkripsi (Maks. 500 MB)</p>
|
||||
<input type="file" id="converterFileInput" accept=".kmh" class="hidden" onchange="handleConverterFileInput(this)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading & Real-time Upload Progress Bar -->
|
||||
<div id="converterLoading" class="hidden py-6 space-y-3">
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span class="font-bold text-slate-800 flex items-center gap-2">
|
||||
<span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
|
||||
<span id="converterLoadingText">Mengunggah berkas .kmh ke server...</span>
|
||||
</span>
|
||||
<span id="converterUploadPercentText" class="font-mono font-bold text-emerald-600">0%</span>
|
||||
</div>
|
||||
<!-- Progress Bar Track -->
|
||||
<div class="w-full bg-slate-100 rounded-full h-3 overflow-hidden border border-slate-200">
|
||||
<div id="converterProgressBar" class="bg-gradient-to-r from-emerald-500 to-teal-600 h-3 rounded-full transition-all duration-150 ease-out" style="width: 0%"></div>
|
||||
</div>
|
||||
<div class="flex items-center justify-between text-[11px] text-slate-400">
|
||||
<span id="converterUploadByteText">0 MB / 0 MB</span>
|
||||
<span id="converterUploadSubText">Mohon tunggu, koneksi sedang mengirim data...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Konfigurasi Format & Pilihan Tabel (Muncul setelah inspect sukses) -->
|
||||
<div id="panelConverterConfig" class="hidden space-y-5">
|
||||
<!-- Metadata Strip -->
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-2.5 p-3.5 bg-slate-50 border border-slate-200/80 rounded-xl text-xs">
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Nama Berkas</span>
|
||||
<span class="font-mono font-semibold text-slate-800 truncate block mt-0.5" id="convFilename">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Ukuran Arsip</span>
|
||||
<span class="font-semibold text-slate-800 block mt-0.5" id="convFileSize">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Tanggal Dibuat</span>
|
||||
<span class="font-semibold text-slate-800 block mt-0.5" id="convCreatedAt">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Database Asal</span>
|
||||
<span class="font-mono font-semibold text-slate-800 block mt-0.5" id="convDatabase">-</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Pilihan Format Keluaran -->
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-slate-800 block">Pilih Format Hasil Konversi:</label>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="xlsx" checked class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">Microsoft Excel (.xlsx)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">File spreadsheet siap buka di Excel dengan filter header.</span>
|
||||
</label>
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="csv" class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">Kumpulan CSV (.zip)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">File .csv per tabel di dalam paket zip, sangat ringan.</span>
|
||||
</label>
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="sql" class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">SQL Mentah (.sql)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">Dump DDL & data bersih siap impor ke MySQL/HeidiSQL.</span>
|
||||
</label>
|
||||
<label id="convMediaFormatCard" class="hidden relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30 col-span-full">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="media" class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-emerald-950">Unduh Folder Media / Foto Fisik (.zip)</span>
|
||||
</div>
|
||||
<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800">Media Terdeteksi</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">Ekstrak seluruh berkas gambar foto asli (.jpg/.png) kendaraan, karyawan, dan gerbang ke dalam satu paket zip.</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Pemilihan Tabel (Checklist) -->
|
||||
<div class="bg-white rounded-xl border border-slate-200 p-4 space-y-3">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-2.5 pb-2.5 border-b border-slate-100">
|
||||
<div>
|
||||
<span class="text-xs font-bold text-slate-800 block">
|
||||
Pilih Tabel yang Ingin Dikonversi:
|
||||
</span>
|
||||
<span class="text-[11px] text-slate-500">
|
||||
Terpilih: <strong id="convSelectedCount" class="text-emerald-700 font-bold">0</strong> dari <span id="convTotalTableCount">0</span> tabel
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="text" id="convTableFilterInput" oninput="filterConverterTables(this.value)" placeholder="Cari nama tabel..." class="text-[11px] px-2.5 py-1.5 rounded-lg border border-slate-200 focus:outline-none focus:border-emerald-500 w-full sm:w-44">
|
||||
<button type="button" onclick="toggleSelectAllConverterTables(true)" class="whitespace-nowrap px-2.5 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 text-[11px] font-semibold transition">
|
||||
Pilih Semua
|
||||
</button>
|
||||
<button type="button" onclick="toggleSelectAllConverterTables(false)" class="whitespace-nowrap px-2.5 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 text-[11px] font-semibold transition">
|
||||
Bersihkan
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Checklist Container -->
|
||||
<div id="convTableList" class="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-48 overflow-y-auto p-1.5 bg-slate-50/70 rounded-xl border border-slate-100">
|
||||
<!-- Checkboxes generated via JS -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Footer -->
|
||||
<div class="pt-3 border-t border-slate-100 flex flex-wrap items-center justify-between gap-3">
|
||||
<button type="button" onclick="resetConverterToUpload()" class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-xs transition">
|
||||
Ganti Berkas .kmh
|
||||
</button>
|
||||
<button type="button"
|
||||
id="btnExecuteConvert"
|
||||
onclick="executeConverterDownload()"
|
||||
class="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs transition shadow-xs inline-flex items-center gap-2">
|
||||
<span id="btnExecuteConvertText">Mulai Konversi & Unduh</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-6 py-3 bg-slate-50 border-t border-slate-100 flex items-center justify-end">
|
||||
<button type="button" onclick="closeConverterModal()" class="px-4 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-xs transition">
|
||||
Tutup
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auto-Download Script jika ada sesi auto_download -->
|
||||
@if(session('auto_download'))
|
||||
<script>
|
||||
@@ -752,6 +967,14 @@
|
||||
function handleDirectRestoreFileChange(input) {
|
||||
if (input.files && input.files[0]) {
|
||||
const file = input.files[0];
|
||||
const maxBytes = {{ $maxUploadBytes ?? 268435456 }};
|
||||
if (file.size > maxBytes) {
|
||||
const fileMb = (file.size / (1024 * 1024)).toFixed(1);
|
||||
const limitMb = (maxBytes / (1024 * 1024)).toFixed(0);
|
||||
alert(`Peringatan: Ukuran file (${fileMb} MB) melebihi batas upload PHP server (${limitMb} MB). Mohon sesuaikan pengaturan php.ini server Anda.`);
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
const sizeHuman = (file.size / (1024 * 1024)).toFixed(2) + ' MB';
|
||||
document.getElementById('directRestorePillName').textContent = file.name;
|
||||
document.getElementById('directRestorePillSize').textContent = sizeHuman;
|
||||
@@ -767,13 +990,112 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
const confInput = document.getElementById('directRestoreConfirmationInput');
|
||||
if (!confInput.value.trim()) {
|
||||
alert('Silakan ketik "PULIHKAN" atau masukkan password Super Admin Anda.');
|
||||
confInput.focus();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tampilkan Progress Bar
|
||||
const errorDiv = document.getElementById('directRestoreError');
|
||||
if (errorDiv) errorDiv.classList.add('hidden');
|
||||
document.getElementById('directRestoreDropzoneContainer').classList.add('hidden');
|
||||
const loading = document.getElementById('directRestoreLoading');
|
||||
loading.classList.remove('hidden');
|
||||
|
||||
const btn = document.getElementById('directRestoreSubmitBtn');
|
||||
const text = document.getElementById('directRestoreBtnText');
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
btn.classList.add('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
if (text) text.textContent = 'Memvalidasi & Memulihkan Sistem...';
|
||||
if (text) text.textContent = 'Mengunggah & Memulihkan...';
|
||||
|
||||
const file = fileInput.files[0];
|
||||
const totalMb = (file.size / (1024 * 1024)).toFixed(1);
|
||||
|
||||
const formData = new FormData(form);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', form.action, true);
|
||||
xhr.timeout = 3600000; // 1 Jam timeout untuk berkas backup besar
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
|
||||
xhr.upload.onprogress = function(e) {
|
||||
if (e.lengthComputable) {
|
||||
const percent = Math.min(100, Math.round((e.loaded / e.total) * 100));
|
||||
const loadedMb = (e.loaded / (1024 * 1024)).toFixed(1);
|
||||
|
||||
document.getElementById('directRestoreProgressBar').style.width = percent + '%';
|
||||
document.getElementById('directRestoreUploadPercentText').textContent = percent + '%';
|
||||
document.getElementById('directRestoreUploadByteText').textContent = `${loadedMb} MB / ${totalMb} MB`;
|
||||
|
||||
if (percent >= 100) {
|
||||
document.getElementById('directRestoreLoadingText').textContent = 'Mengunggah Selesai! Memulihkan database & media di server...';
|
||||
document.getElementById('directRestoreUploadSubText').textContent = 'Sedang mengeksekusi DDL & menyinkronkan media. Mohon jangan menutup halaman ini...';
|
||||
} else {
|
||||
document.getElementById('directRestoreLoadingText').textContent = `Mengunggah berkas backup: ${percent}%...`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = function() {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const res = JSON.parse(xhr.responseText);
|
||||
if (res.success) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
} catch (err) {}
|
||||
window.location.reload();
|
||||
} else {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('directRestoreDropzoneContainer').classList.remove('hidden');
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
if (text) text.textContent = 'Mulai Pemulihan Sistem';
|
||||
|
||||
let errMsg = 'Terjadi kesalahan saat memulihkan sistem.';
|
||||
try {
|
||||
const res = JSON.parse(xhr.responseText);
|
||||
if (res.message) errMsg = res.message;
|
||||
} catch (e) {}
|
||||
|
||||
document.getElementById('directRestoreErrorMessage').textContent = errMsg;
|
||||
document.getElementById('directRestoreError').classList.remove('hidden');
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('directRestoreDropzoneContainer').classList.remove('hidden');
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
if (text) text.textContent = 'Mulai Pemulihan Sistem';
|
||||
document.getElementById('directRestoreErrorMessage').textContent = 'Koneksi jaringan terputus saat mengunggah berkas.';
|
||||
document.getElementById('directRestoreError').classList.remove('hidden');
|
||||
};
|
||||
|
||||
xhr.ontimeout = function() {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('directRestoreDropzoneContainer').classList.remove('hidden');
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
if (text) text.textContent = 'Mulai Pemulihan Sistem';
|
||||
document.getElementById('directRestoreErrorMessage').textContent = 'Waktu pengunggahan habis (Timeout 1 Jam). Silakan periksa kestabilan jaringan internet Anda.';
|
||||
document.getElementById('directRestoreError').classList.remove('hidden');
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Drag and Drop Handlers (Universal) */
|
||||
@@ -855,5 +1177,391 @@
|
||||
document.getElementById('deleteBackupModal').classList.add('hidden');
|
||||
document.documentElement.classList.remove('modal-open');
|
||||
}
|
||||
|
||||
/* ========================================================================= */
|
||||
/* LOGIKA JAVASCRIPT: KONVERTER ARSIP .KMH (MURNI UPLOAD DARI PC) */
|
||||
/* ========================================================================= */
|
||||
let currentConverterFile = null;
|
||||
let currentConverterToken = null;
|
||||
let currentConverterTables = [];
|
||||
|
||||
function openConverterModal() {
|
||||
document.getElementById('kmhConverterModal').classList.remove('hidden');
|
||||
document.documentElement.classList.add('modal-open');
|
||||
resetConverterToUpload();
|
||||
}
|
||||
|
||||
function closeConverterModal() {
|
||||
document.getElementById('kmhConverterModal').classList.add('hidden');
|
||||
document.documentElement.classList.remove('modal-open');
|
||||
}
|
||||
|
||||
function resetConverterToUpload() {
|
||||
document.getElementById('converterLoading').classList.add('hidden');
|
||||
document.getElementById('converterError').classList.add('hidden');
|
||||
document.getElementById('panelConverterConfig').classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
const fileInput = document.getElementById('converterFileInput');
|
||||
if (fileInput) fileInput.value = '';
|
||||
currentConverterFile = null;
|
||||
currentConverterToken = null;
|
||||
currentConverterTables = [];
|
||||
}
|
||||
|
||||
function showConverterError(msg) {
|
||||
const errorDiv = document.getElementById('converterError');
|
||||
document.getElementById('converterErrorMessage').textContent = msg;
|
||||
errorDiv.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function handleConverterFileInput(input) {
|
||||
if (input.files && input.files[0]) {
|
||||
inspectConverterFile(input.files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function handleConverterFileDrop(e, dropzone) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dropzone.classList.remove('border-emerald-500', 'bg-emerald-50/20');
|
||||
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||
inspectConverterFile(e.dataTransfer.files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function openServerConverterModal(filename) {
|
||||
openConverterModal();
|
||||
|
||||
// Sembunyikan panel upload dan tampilkan status loading membaca arsip server
|
||||
document.getElementById('converterError').classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.add('hidden');
|
||||
document.getElementById('panelConverterConfig').classList.add('hidden');
|
||||
|
||||
const loading = document.getElementById('converterLoading');
|
||||
const progressBar = document.getElementById('converterProgressBar');
|
||||
const percentText = document.getElementById('converterUploadPercentText');
|
||||
const byteText = document.getElementById('converterUploadByteText');
|
||||
const statusText = document.getElementById('converterLoadingText');
|
||||
const subText = document.getElementById('converterUploadSubText');
|
||||
|
||||
progressBar.style.width = '100%';
|
||||
percentText.textContent = '100%';
|
||||
byteText.textContent = 'Arsip Server';
|
||||
statusText.textContent = `Membaca arsip server "${filename}"...`;
|
||||
subText.textContent = 'Membaca manifest & struktur tabel langsung dari VPS (Tanpa upload)...';
|
||||
loading.classList.remove('hidden');
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('server_filename', filename);
|
||||
formData.append('_token', '{{ csrf_token() }}');
|
||||
|
||||
fetch(`{{ route('admin.backups.converter.inspect') }}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
})
|
||||
.then(async response => {
|
||||
loading.classList.add('hidden');
|
||||
const res = await response.json().catch(() => ({}));
|
||||
if (response.ok && res.success && res.data) {
|
||||
currentConverterFile = null;
|
||||
currentConverterToken = res.data.token || null;
|
||||
currentConverterTables = res.data.tables || [];
|
||||
|
||||
document.getElementById('convFilename').textContent = res.data.filename;
|
||||
document.getElementById('convFileSize').textContent = res.data.size_human;
|
||||
document.getElementById('convCreatedAt').textContent = res.data.created_at_human;
|
||||
document.getElementById('convDatabase').textContent = res.data.database;
|
||||
|
||||
const mediaCard = document.getElementById('convMediaFormatCard');
|
||||
if (mediaCard) {
|
||||
if (res.data.has_media) {
|
||||
mediaCard.classList.remove('hidden');
|
||||
} else {
|
||||
mediaCard.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
const filterInput = document.getElementById('convTableFilterInput');
|
||||
if (filterInput) filterInput.value = '';
|
||||
|
||||
renderConverterTableChecklist('');
|
||||
document.getElementById('panelConverterConfig').classList.remove('hidden');
|
||||
} else {
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError(res.message || 'Gagal membaca berkas arsip .kmh dari server.');
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError(err.message || 'Terjadi kesalahan saat memeriksa berkas server.');
|
||||
});
|
||||
}
|
||||
|
||||
function inspectConverterFile(file) {
|
||||
if (!file.name.toLowerCase().endsWith('.kmh')) {
|
||||
alert('File yang dipilih harus berekstensi .kmh!');
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('converterError').classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.add('hidden');
|
||||
|
||||
const loading = document.getElementById('converterLoading');
|
||||
const progressBar = document.getElementById('converterProgressBar');
|
||||
const percentText = document.getElementById('converterUploadPercentText');
|
||||
const byteText = document.getElementById('converterUploadByteText');
|
||||
const statusText = document.getElementById('converterLoadingText');
|
||||
const subText = document.getElementById('converterUploadSubText');
|
||||
|
||||
progressBar.style.width = '0%';
|
||||
percentText.textContent = '0%';
|
||||
const totalMb = (file.size / (1024 * 1024)).toFixed(1);
|
||||
byteText.textContent = `0 MB / ${totalMb} MB`;
|
||||
statusText.textContent = `Mengunggah "${file.name}" ke server...`;
|
||||
subText.textContent = 'Mohon tunggu, koneksi sedang mengirim data...';
|
||||
loading.classList.remove('hidden');
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('backup_file', file);
|
||||
formData.append('_token', '{{ csrf_token() }}');
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', `{{ route('admin.backups.converter.inspect') }}`, true);
|
||||
xhr.timeout = 3600000; // 1 Jam timeout
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
xhr.setRequestHeader('Accept', 'application/json');
|
||||
|
||||
xhr.upload.onprogress = function(e) {
|
||||
if (e.lengthComputable) {
|
||||
const percent = Math.min(100, Math.round((e.loaded / e.total) * 100));
|
||||
const loadedMb = (e.loaded / (1024 * 1024)).toFixed(1);
|
||||
|
||||
progressBar.style.width = percent + '%';
|
||||
percentText.textContent = percent + '%';
|
||||
byteText.textContent = `${loadedMb} MB / ${totalMb} MB`;
|
||||
|
||||
if (percent >= 100) {
|
||||
statusText.textContent = 'Mengunggah Selesai! Memeriksa integritas & manifest di server...';
|
||||
subText.textContent = 'Verifikasi tanda tangan HMAC SHA-256 & membaca daftar tabel';
|
||||
} else {
|
||||
statusText.textContent = `Mengunggah "${file.name}": ${percent}%...`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = function() {
|
||||
loading.classList.add('hidden');
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const res = JSON.parse(xhr.responseText);
|
||||
if (res.success && res.data) {
|
||||
currentConverterFile = file;
|
||||
currentConverterToken = res.data.token || null;
|
||||
currentConverterTables = res.data.tables || [];
|
||||
|
||||
document.getElementById('convFilename').textContent = res.data.filename;
|
||||
document.getElementById('convFileSize').textContent = res.data.size_human;
|
||||
document.getElementById('convCreatedAt').textContent = res.data.created_at_human;
|
||||
document.getElementById('convDatabase').textContent = res.data.database;
|
||||
|
||||
// Tampilkan opsi unduh media jika berkas memiliki folder foto
|
||||
const mediaCard = document.getElementById('convMediaFormatCard');
|
||||
if (mediaCard) {
|
||||
if (res.data.has_media) {
|
||||
mediaCard.classList.remove('hidden');
|
||||
} else {
|
||||
mediaCard.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
const filterInput = document.getElementById('convTableFilterInput');
|
||||
if (filterInput) filterInput.value = '';
|
||||
|
||||
renderConverterTableChecklist('');
|
||||
document.getElementById('panelConverterConfig').classList.remove('hidden');
|
||||
return;
|
||||
} else {
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError(res.message || 'Gagal membaca berkas arsip .kmh.');
|
||||
return;
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
let errMsg = 'Gagal membaca berkas arsip .kmh.';
|
||||
try {
|
||||
const res = JSON.parse(xhr.responseText);
|
||||
if (res.message) errMsg = res.message;
|
||||
} catch (e) {}
|
||||
showConverterError(errMsg);
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError('Koneksi terputus saat mengunggah berkas.');
|
||||
};
|
||||
|
||||
xhr.ontimeout = function() {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError('Waktu pengunggahan habis (Timeout 1 Jam). Silakan periksa kestabilan jaringan internet Anda.');
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
function renderConverterTableChecklist(filter = '') {
|
||||
const container = document.getElementById('convTableList');
|
||||
container.innerHTML = '';
|
||||
|
||||
const filtered = filter
|
||||
? currentConverterTables.filter(t => t.toLowerCase().includes(filter.toLowerCase()))
|
||||
: currentConverterTables;
|
||||
|
||||
document.getElementById('convTotalTableCount').textContent = currentConverterTables.length;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = '<span class="col-span-full text-xs text-slate-400 italic p-2">Tidak ada tabel yang cocok dengan pencarian.</span>';
|
||||
updateConverterSelectedCount();
|
||||
return;
|
||||
}
|
||||
|
||||
filtered.forEach(tbl => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'flex items-center gap-2 p-2 rounded-lg bg-white border border-slate-200 hover:border-emerald-400 hover:bg-emerald-50/20 transition cursor-pointer select-none';
|
||||
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.name = 'convSelectedTables';
|
||||
checkbox.value = tbl;
|
||||
checkbox.checked = true; // Terpilih secara default
|
||||
checkbox.className = 'conv-table-checkbox rounded text-emerald-600 focus:ring-emerald-500 w-3.5 h-3.5';
|
||||
checkbox.onchange = updateConverterSelectedCount;
|
||||
|
||||
const span = document.createElement('span');
|
||||
span.className = 'text-xs font-mono font-medium text-slate-800 truncate';
|
||||
span.textContent = tbl;
|
||||
span.title = tbl;
|
||||
|
||||
label.appendChild(checkbox);
|
||||
label.appendChild(span);
|
||||
container.appendChild(label);
|
||||
});
|
||||
|
||||
updateConverterSelectedCount();
|
||||
}
|
||||
|
||||
function filterConverterTables(query) {
|
||||
renderConverterTableChecklist(query);
|
||||
}
|
||||
|
||||
function toggleSelectAllConverterTables(selectAll) {
|
||||
const checkboxes = document.querySelectorAll('.conv-table-checkbox');
|
||||
checkboxes.forEach(cb => {
|
||||
cb.checked = selectAll;
|
||||
});
|
||||
updateConverterSelectedCount();
|
||||
}
|
||||
|
||||
function updateConverterSelectedCount() {
|
||||
const allCheckboxes = document.querySelectorAll('.conv-table-checkbox');
|
||||
let checkedCount = 0;
|
||||
allCheckboxes.forEach(cb => {
|
||||
if (cb.checked) checkedCount++;
|
||||
});
|
||||
document.getElementById('convSelectedCount').textContent = checkedCount;
|
||||
}
|
||||
|
||||
function executeConverterDownload() {
|
||||
if (!currentConverterToken && !currentConverterFile) {
|
||||
alert('Silakan pilih berkas .kmh terlebih dahulu.');
|
||||
return;
|
||||
}
|
||||
|
||||
const formatRadio = document.querySelector('input[name="convFormat"]:checked');
|
||||
const format = formatRadio ? formatRadio.value : 'xlsx';
|
||||
|
||||
const selectedTables = [];
|
||||
document.querySelectorAll('.conv-table-checkbox:checked').forEach(cb => {
|
||||
selectedTables.push(cb.value);
|
||||
});
|
||||
|
||||
if (format !== 'media' && selectedTables.length === 0) {
|
||||
alert('Silakan pilih minimal satu tabel untuk dikonversi.');
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.getElementById('btnExecuteConvert');
|
||||
const btnText = document.getElementById('btnExecuteConvertText');
|
||||
btn.disabled = true;
|
||||
btn.classList.add('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Menyiapkan Unduhan Langsung...';
|
||||
|
||||
const formData = new FormData();
|
||||
if (currentConverterToken) {
|
||||
formData.append('token', currentConverterToken);
|
||||
} else if (currentConverterFile) {
|
||||
formData.append('backup_file', currentConverterFile);
|
||||
}
|
||||
formData.append('format', format);
|
||||
formData.append('_token', '{{ csrf_token() }}');
|
||||
selectedTables.forEach(t => {
|
||||
formData.append('tables[]', t);
|
||||
});
|
||||
|
||||
fetch(`{{ route('admin.backups.converter.execute') }}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
}
|
||||
})
|
||||
.then(async response => {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Mulai Konversi & Unduh';
|
||||
|
||||
if (!response.ok) {
|
||||
const errData = await response.json().catch(() => ({}));
|
||||
throw new Error(errData.message || 'Terjadi kesalahan pada server saat mengonversi berkas.');
|
||||
}
|
||||
|
||||
// Dapatkan nama file dari header Content-Disposition
|
||||
let filename = `hasil_konversi_${format}.${format === 'csv' || format === 'media' ? 'zip' : (format === 'sql' ? 'sql' : 'xlsx')}`;
|
||||
const disposition = response.headers.get('Content-Disposition');
|
||||
if (disposition && disposition.indexOf('filename=') !== -1) {
|
||||
const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
|
||||
if (matches != null && matches[1]) {
|
||||
filename = matches[1].replace(/['"]/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
return response.blob().then(blob => ({ blob, filename }));
|
||||
})
|
||||
.then(({ blob, filename }) => {
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.style.display = 'none';
|
||||
a.href = blobUrl;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
a.remove();
|
||||
})
|
||||
.catch(err => {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Mulai Konversi & Unduh';
|
||||
showConverterError(err.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
@endsection
|
||||
|
||||
@@ -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,158 +75,258 @@
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- Ringkasan Role Cards -->
|
||||
<!-- 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']);
|
||||
$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'
|
||||
$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
|
||||
<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"
|
||||
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>
|
||||
</button>
|
||||
</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">{{ str_replace('_', ' ', $role->name) }}</h2>
|
||||
<p class="text-[10px] text-slate-400 mt-0.5 font-mono">{{ $role->name }}</p>
|
||||
<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.5 border-t border-slate-100 flex items-center justify-between text-[11px]">
|
||||
<span class="text-slate-500">Jumlah Hak Akses:</span>
|
||||
|
||||
<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')
|
||||
<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 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>
|
||||
<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 class="font-bold text-indigo-700 role-perm-badge-count" data-role-id="{{ $role->id }}">
|
||||
{{ $role->permissions->count() }} Izin
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
<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>
|
||||
<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.
|
||||
@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
|
||||
</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>
|
||||
<div class="absolute -top-1 left-4 w-2 h-2 bg-slate-900 rotate-45"></div>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</h2>
|
||||
<p class="text-[11px] text-slate-400">Atur centang hak akses menu yang diizinkan untuk peran pengguna ini.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if($role->name !== 'super_admin')
|
||||
<!-- 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-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">
|
||||
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 Hak Akses</span>
|
||||
<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>
|
||||
@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>
|
||||
<h3 class="text-xs font-bold text-slate-800 leading-snug">
|
||||
{{ $module['name'] }}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<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 = $role->name === 'super_admin' || in_array($permKey, $rolePermNames);
|
||||
$isChecked = $isSuperAdmin || 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">
|
||||
<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' : '' }}
|
||||
{{ $role->name === 'super_admin' ? 'disabled' : '' }}
|
||||
class="mt-1 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 transition">
|
||||
<div>
|
||||
{{ $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-[10px] text-slate-400 mt-1 block">
|
||||
<span class="font-mono text-[9px] text-slate-400 mt-0.5 block truncate">
|
||||
{{ $permKey }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -234,8 +334,35 @@
|
||||
@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');
|
||||
|
||||
@@ -312,9 +312,16 @@
|
||||
<p class="text-xs text-slate-500">Catatan mobilisasi kendaraan yang pernah Anda isi di sistem.</p>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-xs font-semibold text-slate-400 self-start sm:self-center">
|
||||
<div class="flex items-center gap-3 self-start sm:self-center">
|
||||
<span class="text-xs font-semibold text-slate-400">
|
||||
{{ $myRecentActivities->count() }} Perjalanan Terbaru
|
||||
</span>
|
||||
<a href="{{ route('employee.history') }}"
|
||||
class="inline-flex items-center text-xs font-bold text-[#1b5e20] hover:underline">
|
||||
<span>Lihat Seluruh Riwayat</span>
|
||||
<i class="fa-solid fa-arrow-right text-[10px] ml-1"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto -mx-5 sm:mx-0">
|
||||
@@ -411,6 +418,11 @@
|
||||
<p class="text-[11px] text-slate-400 mt-1 max-w-sm mx-auto">
|
||||
Catatan mobilisasi unit kendaraan ringan (LV) yang Anda kendarai akan otomatis muncul di sini setelah Anda mengisi formulir perjalanan.
|
||||
</p>
|
||||
<div class="mt-3">
|
||||
<a href="{{ route('employee.history') }}" class="text-xs font-bold text-[#1b5e20] hover:underline">
|
||||
Buka Halaman Riwayat Saya →
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@@ -1150,10 +1162,11 @@
|
||||
|
||||
isPollingInProgress = true;
|
||||
try {
|
||||
const response = await fetch(`{{ route('employee.activity.status_polling') }}?activity_id=${activityId}`, {
|
||||
const response = await fetch(`{{ route('employee.activity.status_polling', [], false) }}?activity_id=${activityId}&_t=${Date.now()}`, {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Cache-Control': 'no-cache'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,637 @@
|
||||
@extends('layouts.app')
|
||||
|
||||
@section('title', 'Riwayat Aktivitas - Sistem RKM | PT Kerinci Merangin Hidro')
|
||||
|
||||
@section('content')
|
||||
<div class="w-full space-y-6">
|
||||
|
||||
<!-- Header Halaman Bersih & Minimalis -->
|
||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-slate-200">
|
||||
<div>
|
||||
<div class="flex items-center space-x-2 text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">
|
||||
<span>Portal Karyawan</span>
|
||||
<span>•</span>
|
||||
<span class="text-[#1b5e20] font-bold">Catatan Operasional</span>
|
||||
</div>
|
||||
<h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
|
||||
Riwayat Aktivitas Saya
|
||||
</h1>
|
||||
<p class="text-xs sm:text-sm text-slate-500 mt-1">
|
||||
Rekap seluruh aktivitas pemeriksaan kelaikan P2H, timesheet alat berat, dan mobilisasi kendaraan Anda.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 self-start sm:self-center">
|
||||
<a href="{{ route('employee.dashboard') }}"
|
||||
class="px-3.5 py-2 text-xs font-bold text-slate-700 bg-white border border-slate-300 rounded-xl hover:bg-slate-50 transition shadow-2xs">
|
||||
← Kembali ke Dashboard
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ringkasan KPI Pribadi Karyawan (Tanpa Ikon Berlebih, Tipografi Bersih) -->
|
||||
<div class="grid grid-cols-1 {{ ($canP2h && $canTimesheet && $canTrips) ? 'sm:grid-cols-3' : (($canP2h || $canTimesheet) && ($canTrips || ($canP2h && $canTimesheet)) ? 'sm:grid-cols-2' : 'sm:grid-cols-1') }} gap-4">
|
||||
@if($canP2h)
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">P2H Heavy Equipment</p>
|
||||
<div class="mt-2 flex items-baseline justify-between">
|
||||
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['p2h_total']) }}</span>
|
||||
<span class="text-xs font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200">
|
||||
{{ $stats['p2h_good'] }} Layak
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-xs text-slate-500 mt-2">
|
||||
{{ $stats['p2h_defects'] }} catatan memiliki temuan kerusakan
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if($canTimesheet)
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Timesheet Alat Berat</p>
|
||||
<div class="mt-2 flex items-baseline justify-between">
|
||||
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['timesheet_hours'], 1, ',', '.') }} Jam</span>
|
||||
<span class="text-xs font-semibold text-slate-700 bg-slate-100 px-2 py-0.5 rounded border border-slate-200">
|
||||
{{ number_format($stats['timesheet_total']) }} Sesi
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-xs text-slate-500 mt-2">
|
||||
Total akumulasi jam operasi alat berat
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if($canTrips)
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-4 shadow-2xs">
|
||||
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Perjalanan Gerbang (LV)</p>
|
||||
<div class="mt-2 flex items-baseline justify-between">
|
||||
<span class="text-2xl font-black text-slate-900">{{ number_format($stats['trip_distance'], 0, ',', '.') }} KM</span>
|
||||
<span class="text-xs font-semibold text-blue-700 bg-blue-50 px-2 py-0.5 rounded border border-blue-200">
|
||||
{{ number_format($stats['trip_total']) }} Trip
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-xs text-slate-500 mt-2">
|
||||
Jarak kumulatif mobilisasi kendaraan dinas
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<!-- Tab Navigasi Dinamis Berdasarkan Hak Akses & Riwayat -->
|
||||
<div class="bg-white border border-slate-200 rounded-2xl shadow-2xs overflow-hidden">
|
||||
|
||||
<!-- Header Tab -->
|
||||
<div class="border-b border-slate-200 px-5 pt-3 bg-slate-50/50">
|
||||
<div class="flex space-x-6 overflow-x-auto no-scrollbar">
|
||||
@if($canP2h)
|
||||
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'p2h'])) }}"
|
||||
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'p2h' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
|
||||
<span>P2H Heavy Equipment</span>
|
||||
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'p2h' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
|
||||
{{ $p2hCount }}
|
||||
</span>
|
||||
</a>
|
||||
@endif
|
||||
|
||||
@if($canTimesheet)
|
||||
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'timesheet'])) }}"
|
||||
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'timesheet' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
|
||||
<span>Timesheet Heavy Equipment</span>
|
||||
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'timesheet' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
|
||||
{{ $timesheetCount }}
|
||||
</span>
|
||||
</a>
|
||||
@endif
|
||||
|
||||
@if($canTrips)
|
||||
<a href="{{ route('employee.history', array_merge(request()->except(['page', 'p2h_page', 'ts_page', 'trip_page']), ['tab' => 'trips'])) }}"
|
||||
class="pb-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap transition flex items-center gap-2 {{ $activeTab === 'trips' ? 'border-[#1b5e20] text-[#1b5e20]' : 'border-transparent text-slate-500 hover:text-slate-800' }}">
|
||||
<span>Mobilisasi & Pos Gerbang (LV)</span>
|
||||
<span class="px-2 py-0.5 text-[11px] rounded-full {{ $activeTab === 'trips' ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-200/80 text-slate-600' }}">
|
||||
{{ $tripCount }}
|
||||
</span>
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Filter Bar Bersih -->
|
||||
<div class="p-5 border-b border-slate-100 bg-white">
|
||||
<form method="GET" action="{{ route('employee.history') }}" class="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-3">
|
||||
<input type="hidden" name="tab" value="{{ $activeTab }}">
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2.5 flex-1">
|
||||
<!-- Kata Kunci Pencarian -->
|
||||
<div class="sm:col-span-2 md:col-span-1">
|
||||
<input type="text"
|
||||
name="search"
|
||||
value="{{ $search }}"
|
||||
placeholder="Cari transaksi, kode unit..."
|
||||
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition">
|
||||
</div>
|
||||
|
||||
<!-- Dari Tanggal -->
|
||||
<div>
|
||||
<input type="date"
|
||||
name="date_from"
|
||||
value="{{ $dateFrom }}"
|
||||
title="Dari Tanggal"
|
||||
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
|
||||
</div>
|
||||
|
||||
<!-- Sampai Tanggal -->
|
||||
<div>
|
||||
<input type="date"
|
||||
name="date_to"
|
||||
value="{{ $dateTo }}"
|
||||
title="Sampai Tanggal"
|
||||
class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
|
||||
</div>
|
||||
|
||||
<!-- Filter Status Sesuai Tab Aktif -->
|
||||
<div>
|
||||
<select name="status" class="w-full text-xs px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition text-slate-600">
|
||||
<option value="">Semua Status</option>
|
||||
@if($activeTab === 'p2h')
|
||||
<option value="pending" {{ $status === 'pending' ? 'selected' : '' }}>Menunggu Approval QMA</option>
|
||||
<option value="approved" {{ $status === 'approved' ? 'selected' : '' }}>Disetujui</option>
|
||||
<option value="rejected" {{ $status === 'rejected' ? 'selected' : '' }}>Ditolak</option>
|
||||
<option value="good" {{ $status === 'good' ? 'selected' : '' }}>Kondisi: Layak Jalan</option>
|
||||
<option value="has_defect" {{ $status === 'has_defect' ? 'selected' : '' }}>Kondisi: Ada Temuan</option>
|
||||
@elseif($activeTab === 'timesheet')
|
||||
<option value="completed" {{ $status === 'completed' ? 'selected' : '' }}>Selesai</option>
|
||||
<option value="running" {{ $status === 'running' ? 'selected' : '' }}>Sedang Berjalan</option>
|
||||
@elseif($activeTab === 'trips')
|
||||
<option value="approved" {{ $status === 'approved' ? 'selected' : '' }}>Disetujui Satpam</option>
|
||||
<option value="pending" {{ $status === 'pending' ? 'selected' : '' }}>Menunggu Validasi</option>
|
||||
<option value="rejected" {{ $status === 'rejected' ? 'selected' : '' }}>Ditolak Satpam</option>
|
||||
<option value="cancelled" {{ $status === 'cancelled' ? 'selected' : '' }}>Dibatalkan</option>
|
||||
@endif
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tombol Filter & Reset -->
|
||||
<div class="flex items-center gap-2 flex-shrink-0">
|
||||
<button type="submit"
|
||||
class="px-4 py-2 bg-[#1b5e20] hover:bg-[#144918] text-white font-bold text-xs rounded-xl shadow-2xs transition">
|
||||
Terapkan Filter
|
||||
</button>
|
||||
@if($search || $dateFrom || $dateTo || $status)
|
||||
<a href="{{ route('employee.history', ['tab' => $activeTab]) }}"
|
||||
class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-semibold rounded-xl transition">
|
||||
Reset
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- ========================================================== -->
|
||||
<!-- TAB 1: RIWAYAT P2H HEAVY EQUIPMENT -->
|
||||
<!-- ========================================================== -->
|
||||
@if($activeTab === 'p2h')
|
||||
@if(isset($p2hRecords) && $p2hRecords->isNotEmpty())
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-xs text-left min-w-[760px]">
|
||||
<thead>
|
||||
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
|
||||
<th class="py-3 px-4">Waktu Inspeksi</th>
|
||||
<th class="py-3 px-4">No. Transaksi</th>
|
||||
<th class="py-3 px-4">Unit Alat Berat</th>
|
||||
<th class="py-3 px-4">Shift & Odometer</th>
|
||||
<th class="py-3 px-4 text-center">Kelaikan Operasi</th>
|
||||
<th class="py-3 px-4 text-center">Status QMA</th>
|
||||
<th class="py-3 px-4 text-right">Aksi</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100 text-slate-700">
|
||||
@foreach($p2hRecords as $rec)
|
||||
<tr class="hover:bg-slate-50/60 transition">
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-slate-900 block">{{ $rec->inspected_at ? $rec->inspected_at->format('d/m/Y') : '-' }}</span>
|
||||
<span class="text-[11px] text-slate-400 block">{{ $rec->inspected_at ? $rec->inspected_at->format('H:i') . ' WIB' : '-' }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
|
||||
{{ $rec->transaction_no }}
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $rec->vehicle->code ?? '-' }}</span>
|
||||
<span class="text-[11px] text-slate-500 block truncate max-w-[160px]">{{ $rec->vehicle->brand_type ?? '-' }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-medium text-slate-800 block">Shift {{ $rec->shift }}</span>
|
||||
<span class="text-[11px] font-mono text-slate-500 block">HM: {{ number_format($rec->start_hm, 1) }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-center whitespace-nowrap">
|
||||
@if($rec->summary_condition === 'good')
|
||||
<span class="inline-block px-2.5 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
Layak Jalan
|
||||
</span>
|
||||
@else
|
||||
<span class="inline-block px-2.5 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200" title="{{ $rec->defect_count }} temuan kerusakan">
|
||||
Ada Temuan ({{ $rec->defect_count }})
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="py-3 px-4 text-center whitespace-nowrap">
|
||||
@if($rec->validation_status === 'approved')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200" title="Disetujui oleh: {{ $rec->validator->name ?? 'Admin QMA' }}">
|
||||
Disetujui
|
||||
</span>
|
||||
@elseif($rec->validation_status === 'rejected')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-rose-50 text-rose-700 border border-rose-200" title="Alasan: {{ $rec->validation_notes }}">
|
||||
Ditolak
|
||||
</span>
|
||||
@else
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
|
||||
Menunggu QMA
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right whitespace-nowrap space-x-1">
|
||||
<button type="button"
|
||||
onclick="viewP2hDetail({{ $rec->id }})"
|
||||
class="px-2.5 py-1 text-[11px] font-semibold text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition cursor-pointer">
|
||||
Detail
|
||||
</button>
|
||||
<a href="{{ route('employee.history.p2h_pdf', $rec->id) }}"
|
||||
target="_blank"
|
||||
class="px-2.5 py-1 text-[11px] font-semibold text-rose-700 bg-rose-50 border border-rose-200 rounded-lg hover:bg-rose-100 transition">
|
||||
PDF
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination Links -->
|
||||
<div class="p-4 border-t border-slate-100 bg-white">
|
||||
{{ $p2hRecords->links() }}
|
||||
</div>
|
||||
@else
|
||||
<div class="py-12 px-4 text-center">
|
||||
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat P2H Heavy Equipment</p>
|
||||
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
|
||||
Data pemeriksaan kelaikan unit yang pernah Anda kerjakan akan otomatis tampil di tabel ini.
|
||||
</p>
|
||||
@can('employee.p2h')
|
||||
<div class="mt-4">
|
||||
<a href="{{ route('p2h.index') }}" class="px-4 py-2 bg-[#1b5e20] text-white text-xs font-bold rounded-xl hover:bg-[#144918] transition inline-block">
|
||||
Mulai Pemeriksaan P2H Sekarang
|
||||
</a>
|
||||
</div>
|
||||
@endcan
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- ========================================================== -->
|
||||
<!-- TAB 2: RIWAYAT TIMESHEET ALAT BERAT -->
|
||||
<!-- ========================================================== -->
|
||||
@elseif($activeTab === 'timesheet')
|
||||
@if(isset($timesheetRecords) && $timesheetRecords->isNotEmpty())
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-xs text-left min-w-[760px]">
|
||||
<thead>
|
||||
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
|
||||
<th class="py-3 px-4">Tanggal & Shift</th>
|
||||
<th class="py-3 px-4">No. Timesheet</th>
|
||||
<th class="py-3 px-4">Unit Alat Berat</th>
|
||||
<th class="py-3 px-4 text-right">Odometer (HM / KM)</th>
|
||||
<th class="py-3 px-4 text-right">Jam Operasi</th>
|
||||
<th class="py-3 px-4">Lokasi & Aktivitas</th>
|
||||
<th class="py-3 px-4 text-center">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100 text-slate-700">
|
||||
@foreach($timesheetRecords as $ts)
|
||||
<tr class="hover:bg-slate-50/60 transition">
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-slate-900 block">{{ $ts->date ? $ts->date->format('d/m/Y') : '-' }}</span>
|
||||
<span class="text-[11px] text-slate-500 block font-medium">Shift {{ $ts->shift }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
|
||||
{{ $ts->timesheet_no }}
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $ts->vehicle->code ?? '-' }}</span>
|
||||
<span class="text-[11px] text-slate-500 block truncate max-w-[150px]">{{ $ts->vehicle->brand_type ?? '-' }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
|
||||
<span class="text-slate-900 font-semibold block">{{ number_format($ts->start_meter, 1) }} → {{ number_format($ts->end_meter, 1) }}</span>
|
||||
<span class="text-[10px] text-slate-400 block">{{ strtoupper($ts->meter_type ?? 'HM') }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
|
||||
<span class="font-bold text-slate-900 block">{{ number_format($ts->operating_hours, 1) }} Jam</span>
|
||||
@if($ts->standby_hours > 0 || $ts->breakdown_hours > 0)
|
||||
<span class="text-[10px] text-slate-400 block">
|
||||
Stb: {{ number_format($ts->standby_hours, 1) }} | BD: {{ number_format($ts->breakdown_hours, 1) }}
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span class="font-bold text-slate-800 block truncate max-w-[180px]">{{ $ts->location ?? '-' }}</span>
|
||||
<span class="text-[11px] text-slate-500 block truncate max-w-[200px]">{{ $ts->task_description ?? '-' }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-center whitespace-nowrap">
|
||||
@if($ts->status === 'completed')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
Selesai
|
||||
</span>
|
||||
@else
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-blue-50 text-blue-700 border border-blue-200">
|
||||
Berjalan
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination Links -->
|
||||
<div class="p-4 border-t border-slate-100 bg-white">
|
||||
{{ $timesheetRecords->links() }}
|
||||
</div>
|
||||
@else
|
||||
<div class="py-12 px-4 text-center">
|
||||
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat Timesheet Alat Berat</p>
|
||||
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
|
||||
Data jam kerja dan catatan operasional operator heavy equipment akan tampil di sini setelah dicatat.
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- ========================================================== -->
|
||||
<!-- TAB 3: RIWAYAT MOBILISASI & POS GERBANG (LV) -->
|
||||
<!-- ========================================================== -->
|
||||
@elseif($activeTab === 'trips')
|
||||
@if(isset($tripRecords) && $tripRecords->isNotEmpty())
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-xs text-left min-w-[760px]">
|
||||
<thead>
|
||||
<tr class="bg-slate-50 text-slate-500 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
|
||||
<th class="py-3 px-4">Waktu</th>
|
||||
<th class="py-3 px-4">No. Transaksi</th>
|
||||
<th class="py-3 px-4">Unit Kendaraan</th>
|
||||
<th class="py-3 px-4">Pos Gerbang & Arah</th>
|
||||
<th class="py-3 px-4 text-right">Odometer & Jarak</th>
|
||||
<th class="py-3 px-4">Keperluan</th>
|
||||
<th class="py-3 px-4 text-center">Status Satpam</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100 text-slate-700">
|
||||
@foreach($tripRecords as $act)
|
||||
<tr class="hover:bg-slate-50/60 transition">
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-slate-900 block">{{ $act->recorded_at ? $act->recorded_at->format('d/m/Y') : '-' }}</span>
|
||||
<span class="text-[11px] text-slate-400 block">{{ $act->recorded_at ? $act->recorded_at->format('H:i') . ' WIB' : '-' }}</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap font-mono font-bold text-slate-800">
|
||||
{{ $act->transaction_no }}
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-[#1b5e20] font-mono text-xs block">{{ $act->vehicle->code ?? '-' }}</span>
|
||||
<span class="text-[11px] text-slate-500 block truncate max-w-[160px]">
|
||||
{{ $act->vehicle->brand_type ?? '-' }} • {{ $act->vehicle->license_plate ?? 'Tanpa Plat' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span class="font-bold text-slate-800 block">{{ $act->gate->name ?? 'Pos Gerbang' }}</span>
|
||||
@if($act->direction === 'in')
|
||||
<span class="inline-block mt-0.5 px-1.5 py-0.2 rounded text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
MASUK
|
||||
</span>
|
||||
@else
|
||||
<span class="inline-block mt-0.5 px-1.5 py-0.2 rounded text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200">
|
||||
KELUAR
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right whitespace-nowrap font-mono">
|
||||
<span class="font-bold text-slate-900 block">{{ number_format($act->current_km, 0, ',', '.') }} KM</span>
|
||||
<span class="text-[11px] text-emerald-700 font-semibold block">+{{ number_format($act->distance, 0, ',', '.') }} KM</span>
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span class="text-slate-700 block truncate max-w-[180px]" title="{{ $act->purpose }}">
|
||||
{{ $act->purpose ?: '-' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-center whitespace-nowrap">
|
||||
@if($act->validation_status === 'approved')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200" title="Divalidasi oleh: {{ $act->securityGuard->name ?? 'Satpam' }}">
|
||||
Disetujui
|
||||
</span>
|
||||
@elseif($act->validation_status === 'cancelled')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-slate-100 text-slate-700 border border-slate-200" title="{{ $act->rejection_note }}">
|
||||
Dibatalkan
|
||||
</span>
|
||||
@elseif($act->validation_status === 'rejected')
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-rose-50 text-rose-700 border border-rose-200" title="Alasan: {{ $act->rejection_note }}">
|
||||
Ditolak
|
||||
</span>
|
||||
@else
|
||||
<span class="inline-block px-2 py-0.5 rounded text-[11px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
|
||||
Menunggu Satpam
|
||||
</span>
|
||||
@endif
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination Links -->
|
||||
<div class="p-4 border-t border-slate-100 bg-white">
|
||||
{{ $tripRecords->links() }}
|
||||
</div>
|
||||
@else
|
||||
<div class="py-12 px-4 text-center">
|
||||
<p class="text-sm font-bold text-slate-700">Belum Ada Riwayat Perjalanan Pos Gerbang</p>
|
||||
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
|
||||
Catatan mobilisasi kendaraan ringan (LV) Anda yang melewati pos penjagaan satpam akan dicatat di sini.
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@else
|
||||
<div class="py-12 px-4 text-center">
|
||||
<p class="text-sm font-bold text-slate-700">Tidak Ada Modul Riwayat yang Tersedia</p>
|
||||
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
|
||||
Akun Anda saat ini belum memiliki hak akses operasional yang aktif.
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- ========================================================== -->
|
||||
<!-- MODAL DETAIL INSPEKSI P2H (DESAIN BERSIH TANPA IKON BERLEBIH) -->
|
||||
<!-- ========================================================== -->
|
||||
<div id="p2hDetailModal" class="fixed inset-0 z-50 hidden overflow-y-auto bg-slate-900/40 backdrop-blur-xs flex items-center justify-center p-4">
|
||||
<div class="bg-white rounded-2xl shadow-xl border border-slate-200 w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh]">
|
||||
<!-- Modal Header -->
|
||||
<div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
|
||||
<div>
|
||||
<h3 class="text-base font-bold text-slate-900" id="modalTrxNo">Detail Lembar P2H</h3>
|
||||
<p class="text-xs text-slate-500 mt-0.5" id="modalSubTitle">Hasil pemeriksaan kelaikan unit alat berat</p>
|
||||
</div>
|
||||
<button type="button"
|
||||
onclick="closeP2hDetailModal()"
|
||||
class="text-slate-400 hover:text-slate-700 text-lg font-bold p-1 cursor-pointer">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Modal Body Scrollable -->
|
||||
<div class="p-6 overflow-y-auto space-y-4 text-xs">
|
||||
<!-- Metadata Grid -->
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3 p-3 bg-slate-50 rounded-xl border border-slate-100">
|
||||
<div>
|
||||
<span class="text-[10px] text-slate-400 uppercase font-bold block">Unit Alat Berat</span>
|
||||
<span class="font-bold text-[#1b5e20] text-xs font-mono" id="modalUnitCode">-</span>
|
||||
<span class="text-[11px] text-slate-600 block truncate" id="modalUnitName">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] text-slate-400 uppercase font-bold block">Shift & Odometer</span>
|
||||
<span class="font-bold text-slate-800 text-xs block" id="modalShift">-</span>
|
||||
<span class="text-[11px] font-mono text-slate-600 block" id="modalHm">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] text-slate-400 uppercase font-bold block">Waktu Inspeksi</span>
|
||||
<span class="font-semibold text-slate-800 text-xs block" id="modalTime">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] text-slate-400 uppercase font-bold block">Status Approval</span>
|
||||
<span class="inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded" id="modalStatusBadge">-</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Catatan Umum -->
|
||||
<div id="modalGeneralNotesContainer" class="p-3 bg-amber-50/60 rounded-xl border border-amber-200/60 hidden">
|
||||
<span class="text-[11px] font-bold text-amber-900 block mb-0.5">Catatan Operator:</span>
|
||||
<p class="text-xs text-amber-800" id="modalGeneralNotes"></p>
|
||||
</div>
|
||||
|
||||
<!-- Tabel Checklist Items -->
|
||||
<div>
|
||||
<p class="font-bold text-slate-800 mb-2 uppercase text-[10px] tracking-wider text-slate-400">Daftar Pemeriksaan Komponen:</p>
|
||||
<div class="border border-slate-200 rounded-xl overflow-hidden">
|
||||
<table class="w-full text-left text-xs">
|
||||
<thead>
|
||||
<tr class="bg-slate-50 text-slate-600 font-bold uppercase tracking-wider text-[10px] border-b border-slate-200">
|
||||
<th class="py-2.5 px-3">Bagian</th>
|
||||
<th class="py-2.5 px-3">Komponen / Item</th>
|
||||
<th class="py-2.5 px-3 text-center">Kondisi</th>
|
||||
<th class="py-2.5 px-3">Catatan Temuan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="modalItemsTableBody" class="divide-y divide-slate-100">
|
||||
<!-- Injected via JavaScript -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Footer -->
|
||||
<div class="px-6 py-3 border-t border-slate-100 bg-slate-50/50 flex items-center justify-between">
|
||||
<a id="modalDownloadPdfBtn" href="#" target="_blank" class="px-3.5 py-1.5 bg-rose-600 hover:bg-rose-700 text-white font-bold text-xs rounded-xl transition shadow-2xs">
|
||||
Cetak Lembar PDF
|
||||
</a>
|
||||
<button type="button"
|
||||
onclick="closeP2hDetailModal()"
|
||||
class="px-4 py-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-semibold rounded-xl transition cursor-pointer">
|
||||
Tutup
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function viewP2hDetail(recordId) {
|
||||
const modal = document.getElementById('p2hDetailModal');
|
||||
const pdfBtn = document.getElementById('modalDownloadPdfBtn');
|
||||
const tableBody = document.getElementById('modalItemsTableBody');
|
||||
|
||||
pdfBtn.href = "{{ url('/karyawan/riwayat/p2h', [], false) }}/" + recordId + "/pdf";
|
||||
tableBody.innerHTML = '<tr><td colspan="4" class="py-4 text-center text-slate-400">Memuat data...</td></tr>';
|
||||
modal.classList.remove('hidden');
|
||||
|
||||
fetch("{{ url('/karyawan/riwayat/p2h', [], false) }}/" + recordId)
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error('Gagal memuat detail data.');
|
||||
return res.json();
|
||||
})
|
||||
.then(data => {
|
||||
document.getElementById('modalTrxNo').textContent = 'P2H: ' + data.transaction_no;
|
||||
document.getElementById('modalSubTitle').textContent = data.template_name;
|
||||
document.getElementById('modalUnitCode').textContent = data.vehicle_code;
|
||||
document.getElementById('modalUnitName').textContent = data.vehicle_name;
|
||||
document.getElementById('modalShift').textContent = 'Shift ' + data.shift;
|
||||
document.getElementById('modalHm').textContent = 'HM: ' + (data.start_hm || '0');
|
||||
document.getElementById('modalTime').textContent = data.inspected_at || '-';
|
||||
|
||||
const badge = document.getElementById('modalStatusBadge');
|
||||
if (data.validation_status === 'approved') {
|
||||
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-emerald-50 text-emerald-700 border border-emerald-200';
|
||||
badge.textContent = 'Disetujui';
|
||||
} else if (data.validation_status === 'rejected') {
|
||||
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-rose-50 text-rose-700 border border-rose-200';
|
||||
badge.textContent = 'Ditolak';
|
||||
} else {
|
||||
badge.className = 'inline-block mt-0.5 px-2 py-0.5 text-[10px] font-bold rounded bg-amber-50 text-amber-800 border border-amber-200';
|
||||
badge.textContent = 'Menunggu QMA';
|
||||
}
|
||||
|
||||
const notesContainer = document.getElementById('modalGeneralNotesContainer');
|
||||
if (data.general_notes && data.general_notes.trim() !== '') {
|
||||
notesContainer.classList.remove('hidden');
|
||||
document.getElementById('modalGeneralNotes').textContent = data.general_notes;
|
||||
} else {
|
||||
notesContainer.classList.add('hidden');
|
||||
}
|
||||
|
||||
if (data.items && data.items.length > 0) {
|
||||
tableBody.innerHTML = data.items.map(item => {
|
||||
const isGood = item.condition === 'baik' || item.condition === 'good' || item.condition === 'ok';
|
||||
const condBadge = isGood
|
||||
? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">Baik (OK)</span>'
|
||||
: '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-50 text-rose-700 border border-rose-200">Rusak (Defect)</span>';
|
||||
|
||||
return `
|
||||
<tr class="hover:bg-slate-50/50">
|
||||
<td class="py-2.5 px-3 text-slate-500 font-medium">${item.section || '-'}</td>
|
||||
<td class="py-2.5 px-3 font-semibold text-slate-800">${item.item_name || '-'}</td>
|
||||
<td class="py-2.5 px-3 text-center">${condBadge}</td>
|
||||
<td class="py-2.5 px-3 text-slate-600">${item.notes || '-'}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
} else {
|
||||
tableBody.innerHTML = '<tr><td colspan="4" class="py-3 text-center text-slate-400">Tidak ada komponen checklist tercatat.</td></tr>';
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
tableBody.innerHTML = '<tr><td colspan="4" class="py-4 text-center text-rose-500">' + err.message + '</td></tr>';
|
||||
});
|
||||
}
|
||||
|
||||
function closeP2hDetailModal() {
|
||||
document.getElementById('p2hDetailModal').classList.add('hidden');
|
||||
}
|
||||
|
||||
// Tutup modal jika klik di luar box
|
||||
document.getElementById('p2hDetailModal').addEventListener('click', function(e) {
|
||||
if (e.target === this) {
|
||||
closeP2hDetailModal();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@endsection
|
||||
@@ -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="pt-6 border-t border-slate-100 flex items-center justify-end space-x-3 mt-6">
|
||||
<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>
|
||||
|
||||
<!-- 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;
|
||||
const allMasterSimperTypes = @json($availableSimperTypes ?? []);
|
||||
let currentRenewEmployee = null;
|
||||
|
||||
// Cek status driver untuk mengunci/membuka input SIMPER
|
||||
toggleSimperInput('renew');
|
||||
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;
|
||||
|
||||
document.getElementById('renewForm').action = `/hse/employees/${id}`;
|
||||
// 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');
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
<nav class="space-y-1">
|
||||
@if(auth()->user()->isSuperAdmin())
|
||||
<a href="{{ route('admin.dashboard') }}"
|
||||
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
<svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="7" height="7" rx="2"></rect>
|
||||
<rect x="14" y="3" width="7" height="7" rx="2"></rect>
|
||||
@@ -501,6 +501,12 @@
|
||||
<span>Timesheet</span>
|
||||
</a>
|
||||
@endcan
|
||||
|
||||
<a href="{{ route('employee.history') }}"
|
||||
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('employee.history*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
<i class="fa-solid fa-clock-rotate-left text-base w-5 text-center"></i>
|
||||
<span>Riwayat Saya</span>
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
@endif
|
||||
@@ -569,7 +575,7 @@
|
||||
<div>
|
||||
<nav class="space-y-1">
|
||||
@if(auth()->user()->isSuperAdmin())
|
||||
<a href="{{ route('admin.dashboard') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
<a href="{{ route('admin.dashboard') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.dashboard') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
<svg class="w-5 h-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="7" height="7" rx="2"></rect>
|
||||
<rect x="14" y="3" width="7" height="7" rx="2"></rect>
|
||||
@@ -881,6 +887,11 @@
|
||||
<span>Timesheet</span>
|
||||
</a>
|
||||
@endcan
|
||||
|
||||
<a href="{{ route('employee.history') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('employee.history*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
|
||||
<i class="fa-solid fa-clock-rotate-left w-5 text-center"></i>
|
||||
<span>Riwayat Saya</span>
|
||||
</a>
|
||||
</nav>
|
||||
</div>
|
||||
@endif
|
||||
@@ -929,7 +940,7 @@
|
||||
<i class="fa-solid fa-bars text-base"></i>
|
||||
</button>
|
||||
<h1 class="text-lg sm:text-xl font-bold text-slate-900 tracking-tight">
|
||||
@if(request()->routeIs('admin.dashboard') || request()->routeIs('superadmin.dashboard'))
|
||||
@if(request()->routeIs('admin.dashboard'))
|
||||
Dashboard Admin
|
||||
@elseif(request()->routeIs('admin.users.*'))
|
||||
Kelola Pengguna
|
||||
@@ -987,6 +998,8 @@
|
||||
Log Verifikasi Gerbang
|
||||
@elseif(request()->routeIs('employee.dashboard'))
|
||||
Dashboard Karyawan
|
||||
@elseif(request()->routeIs('employee.history*'))
|
||||
Riwayat Aktivitas
|
||||
@elseif(request()->routeIs('p2h.*'))
|
||||
Pemeriksaan P2H
|
||||
@elseif(request()->routeIs('timesheet.*') || request()->routeIs('mobilisasi.*'))
|
||||
|
||||
@@ -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,18 +333,28 @@
|
||||
|
||||
<!-- 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">
|
||||
<!-- 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>
|
||||
|
||||
<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">
|
||||
@@ -343,26 +362,34 @@
|
||||
<span>Kirim Formulir P2H ke QMA</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@endsection
|
||||
|
||||
@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
|
||||
|
||||
@@ -344,10 +344,11 @@
|
||||
isSyncing = true;
|
||||
|
||||
try {
|
||||
const response = await fetch("{{ route('pg.gate.live_queue') }}?gate_id={{ $gate ? $gate->id : '' }}", {
|
||||
const response = await fetch("{{ route('pg.gate.live_queue', [], false) }}?gate_id={{ $gate ? $gate->id : '' }}&_t=" + Date.now(), {
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'application/json'
|
||||
'Accept': 'application/json',
|
||||
'Cache-Control': 'no-cache'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -404,7 +405,7 @@
|
||||
|
||||
// 3. Update Daftar Kartu Antrean Secara Halus (Hanya Jika Ada Perubahan)
|
||||
const listContainer = document.getElementById('queueListContainer');
|
||||
if (listContainer && lastQueueHtml !== null && lastQueueHtml !== data.html) {
|
||||
if (listContainer && data.html && lastQueueHtml !== data.html) {
|
||||
listContainer.innerHTML = data.html;
|
||||
}
|
||||
|
||||
@@ -470,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 -->
|
||||
@@ -580,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,15 +113,25 @@
|
||||
</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>
|
||||
|
||||
<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>
|
||||
@endcan
|
||||
|
||||
@can('gate.approve')
|
||||
<form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-full sm:w-auto m-0">
|
||||
<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 }}">
|
||||
@@ -136,10 +146,9 @@
|
||||
<span>Verifikasi</span>
|
||||
</button>
|
||||
</form>
|
||||
@else
|
||||
<span class="text-xs text-slate-400 italic">Tidak memiliki izin verifikasi</span>
|
||||
@endcan
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@empty
|
||||
|
||||
@@ -658,7 +658,6 @@
|
||||
}, 500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Panduan Halaman Modal
|
||||
function openGuideModal() {
|
||||
|
||||
@@ -205,6 +205,12 @@
|
||||
<a href="{{ route('qma.p2h.export_single_excel', $rec->id) }}" class="w-7 h-7 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 flex items-center justify-center transition border border-emerald-200 shadow-2xs" title="Download Lembar P2H (Excel)">
|
||||
<i class="fa-solid fa-file-excel text-xs"></i>
|
||||
</a>
|
||||
<button type="button"
|
||||
onclick="openDeleteP2hModal({{ $rec->id }}, '{{ $rec->transaction_no }}', '{{ $rec->vehicle->code ?? '' }}')"
|
||||
class="w-7 h-7 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-600 flex items-center justify-center transition border border-rose-200 shadow-2xs cursor-pointer"
|
||||
title="Hapus Pemeriksaan P2H">
|
||||
<i class="fa-regular fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -312,12 +318,64 @@ function closeGuideModal() {
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') {
|
||||
closeGuideModal();
|
||||
closeDeleteP2hModal();
|
||||
const exportMenu = document.getElementById('exportMenuP2h');
|
||||
if (exportMenu) exportMenu.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
function openDeleteP2hModal(id, trxNo, unitCode) {
|
||||
document.getElementById('deleteP2hForm').action = `/qma/p2h-records/${id}`;
|
||||
document.getElementById('deleteP2hTxNo').textContent = trxNo;
|
||||
document.getElementById('deleteP2hUnitCode').textContent = unitCode || '-';
|
||||
const modal = document.getElementById('deleteP2hModal');
|
||||
if (modal) {
|
||||
modal.classList.remove('hidden');
|
||||
modal.style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
function closeDeleteP2hModal() {
|
||||
const modal = document.getElementById('deleteP2hModal');
|
||||
if (modal) {
|
||||
modal.classList.add('hidden');
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- ========================================================================= -->
|
||||
<!-- MODAL POPUP: HAPUS PEMERIKSAAN P2H -->
|
||||
<!-- ========================================================================= -->
|
||||
<div id="deleteP2hModal" class="hidden fixed inset-0 z-50 overflow-y-auto" style="display: none;">
|
||||
<div class="fixed inset-0 bg-slate-900/60 backdrop-blur-xs transition-opacity" onclick="closeDeleteP2hModal()"></div>
|
||||
|
||||
<div class="flex min-h-full items-center justify-center p-4">
|
||||
<div class="relative w-full max-w-md bg-white rounded-2xl shadow-xl border border-slate-100 p-6 text-center transform transition-all">
|
||||
<div class="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100">
|
||||
<i class="fa-solid fa-triangle-exclamation text-xl"></i>
|
||||
</div>
|
||||
<h3 class="text-sm font-bold text-slate-900 mb-1">Hapus Data Pemeriksaan P2H?</h3>
|
||||
<p class="text-xs text-slate-500 mb-4 leading-relaxed">
|
||||
Apakah Anda yakin ingin menghapus inspeksi P2H <span id="deleteP2hTxNo" class="font-mono font-bold text-rose-600">-</span> untuk unit <span id="deleteP2hUnitCode" class="font-bold text-slate-800">-</span>? Data akan dipindahkan ke <strong>Tong Sampah</strong> dan dapat dipulihkan sewaktu-waktu.
|
||||
</p>
|
||||
|
||||
<form id="deleteP2hForm" method="POST" action="">
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<div class="flex items-center justify-center space-x-3">
|
||||
<button type="button" onclick="closeDeleteP2hModal()" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-semibold transition cursor-pointer">
|
||||
Batal
|
||||
</button>
|
||||
<button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl text-xs font-bold transition shadow-xs cursor-pointer">
|
||||
Ya, Hapus
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========================================================================= -->
|
||||
<!-- MODAL POPUP: PANDUAN HALAMAN (LOG P2H HEAVY EQUIPMENT) -->
|
||||
<!-- ========================================================================= -->
|
||||
|
||||
@@ -25,6 +25,15 @@
|
||||
<span>Ekspor Excel (.xlsx)</span>
|
||||
</a>
|
||||
|
||||
<!-- Tombol Hapus P2H -->
|
||||
<button type="button"
|
||||
onclick="openDeleteP2hModal({{ $record->id }}, '{{ $record->transaction_no }}', '{{ $record->vehicle->code ?? '' }}')"
|
||||
class="inline-flex items-center space-x-1.5 text-xs font-bold text-rose-700 bg-rose-50 hover:bg-rose-100 border border-rose-200 px-3 py-1.5 rounded-xl transition shadow-xs cursor-pointer"
|
||||
title="Hapus Pemeriksaan P2H">
|
||||
<i class="fa-regular fa-trash-can text-[13px] text-rose-600"></i>
|
||||
<span>Hapus P2H</span>
|
||||
</button>
|
||||
|
||||
<!-- Badge Status Validasi -->
|
||||
<div>
|
||||
@if($record->isPending())
|
||||
@@ -230,6 +239,63 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL POPUP: HAPUS PEMERIKSAAN P2H -->
|
||||
<div id="deleteP2hModal" class="hidden fixed inset-0 z-50 overflow-y-auto" style="display: none;">
|
||||
<div class="fixed inset-0 bg-slate-900/60 backdrop-blur-xs transition-opacity" onclick="closeDeleteP2hModal()"></div>
|
||||
|
||||
<div class="flex min-h-full items-center justify-center p-4">
|
||||
<div class="relative w-full max-w-md bg-white rounded-2xl shadow-xl border border-slate-100 p-6 text-center transform transition-all">
|
||||
<div class="w-12 h-12 rounded-full bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100">
|
||||
<i class="fa-solid fa-triangle-exclamation text-xl"></i>
|
||||
</div>
|
||||
<h3 class="text-sm font-bold text-slate-900 mb-1">Hapus Data Pemeriksaan P2H?</h3>
|
||||
<p class="text-xs text-slate-500 mb-4 leading-relaxed">
|
||||
Apakah Anda yakin ingin menghapus inspeksi P2H <span id="deleteP2hTxNo" class="font-mono font-bold text-rose-600">-</span> untuk unit <span id="deleteP2hUnitCode" class="font-bold text-slate-800">-</span>? Data akan dipindahkan ke <strong>Tong Sampah</strong> dan dapat dipulihkan sewaktu-waktu.
|
||||
</p>
|
||||
|
||||
<form id="deleteP2hForm" method="POST" action="">
|
||||
@csrf
|
||||
@method('DELETE')
|
||||
<div class="flex items-center justify-center space-x-3">
|
||||
<button type="button" onclick="closeDeleteP2hModal()" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-semibold transition cursor-pointer">
|
||||
Batal
|
||||
</button>
|
||||
<button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl text-xs font-bold transition shadow-xs cursor-pointer">
|
||||
Ya, Hapus
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function openDeleteP2hModal(id, trxNo, unitCode) {
|
||||
document.getElementById('deleteP2hForm').action = `/qma/p2h-records/${id}`;
|
||||
document.getElementById('deleteP2hTxNo').textContent = trxNo;
|
||||
document.getElementById('deleteP2hUnitCode').textContent = unitCode || '-';
|
||||
const modal = document.getElementById('deleteP2hModal');
|
||||
if (modal) {
|
||||
modal.classList.remove('hidden');
|
||||
modal.style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
function closeDeleteP2hModal() {
|
||||
const modal = document.getElementById('deleteP2hModal');
|
||||
if (modal) {
|
||||
modal.classList.add('hidden');
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') {
|
||||
closeDeleteP2hModal();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@media print {
|
||||
.no-print, header, nav, aside, #mobileDrawer, #topNavbar, .sidebar-container {
|
||||
|
||||
@@ -100,32 +100,26 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Kotak Pencarian & Filter Status Timesheet (Tanpa Card Wrapper, Format Persis HSE Employees) -->
|
||||
<form method="GET" action="{{ url()->current() }}" id="timesheetFilterForm" class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2.5 sm:gap-3">
|
||||
<!-- Pencarian Cepat di Kiri dengan Tombol Cari -->
|
||||
<div class="relative w-full sm:max-w-md flex items-center">
|
||||
<span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400 z-10">
|
||||
<!-- Kotak Pencarian & Filter Status Timesheet -->
|
||||
<form method="GET" action="{{ url()->current() }}" id="timesheetFilterForm" class="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-2.5 sm:gap-3 flex-wrap">
|
||||
<!-- Pencarian Cepat di Kiri -->
|
||||
<div class="relative w-full lg:w-72 xl:w-80 flex-shrink-0">
|
||||
<span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
|
||||
<i class="fa-solid fa-magnifying-glass text-xs"></i>
|
||||
</span>
|
||||
<input type="text"
|
||||
name="search"
|
||||
id="timesheetSearchInput"
|
||||
value="{{ request('search') }}"
|
||||
placeholder="Cari No. TS, nama/NIK operator, atau lokasi..."
|
||||
placeholder="Cari No. TS, nama/NIK operator, lokasi..."
|
||||
autocomplete="off"
|
||||
class="w-full text-xs pl-10 pr-20 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition">
|
||||
<button type="submit"
|
||||
id="timesheetSearchBtn"
|
||||
class="absolute right-1.5 inset-y-1.5 px-3 bg-[#1b5e20] hover:bg-[#144918] active:scale-95 text-white font-bold text-xs rounded-lg flex items-center gap-1.5 transition shadow-sm cursor-pointer z-10">
|
||||
<span>Cari</span>
|
||||
</button>
|
||||
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 di Kanan (Pada Mobile: Sejajar Grid di Bawah Search Bar) -->
|
||||
<div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-2 sm:gap-2.5 w-full sm:w-auto">
|
||||
<div class="grid grid-cols-2 sm:flex sm:items-center sm:gap-2.5 w-full sm:w-auto">
|
||||
<!-- Filter di Kanan -->
|
||||
<div class="flex flex-wrap items-center justify-start lg:justify-end gap-2 sm:gap-2.5 w-full lg:w-auto">
|
||||
<!-- Filter Rentang Tanggal Compact -->
|
||||
<div class="col-span-2 sm:col-auto flex items-center gap-1.5 bg-white border border-slate-200 rounded-xl px-2.5 py-2 shadow-sm">
|
||||
<div class="flex items-center gap-1.5 bg-white border border-slate-200 rounded-xl px-2.5 py-2 shadow-sm">
|
||||
<i class="fa-regular fa-calendar text-slate-400 text-xs flex-shrink-0"></i>
|
||||
<input type="date"
|
||||
name="start_date"
|
||||
@@ -145,7 +139,7 @@
|
||||
<!-- Filter Heavy Equipment -->
|
||||
<select name="vehicle_id"
|
||||
onchange="this.form.submit()"
|
||||
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate max-w-[200px]">
|
||||
<option value="">Semua Heavy Equipment</option>
|
||||
@foreach($unitSupports as $u)
|
||||
<option value="{{ $u->id }}" {{ request('vehicle_id') == $u->id ? 'selected' : '' }}>
|
||||
@@ -157,7 +151,7 @@
|
||||
<!-- Filter Shift -->
|
||||
<select name="shift"
|
||||
onchange="this.form.submit()"
|
||||
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
<option value="">Semua Shift</option>
|
||||
@foreach($shifts as $s)
|
||||
<option value="{{ $s }}" {{ request('shift') === $s ? 'selected' : '' }}>{{ $s }}</option>
|
||||
@@ -167,7 +161,7 @@
|
||||
<!-- Filter Jenis Operator (Karyawan / Sukon) -->
|
||||
<select name="operator_type"
|
||||
onchange="this.form.submit()"
|
||||
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
<option value="">Semua Personil</option>
|
||||
<option value="Karyawan" {{ request('operator_type') === 'Karyawan' ? 'selected' : '' }}>Karyawan</option>
|
||||
<option value="Sukon" {{ request('operator_type') === 'Sukon' ? 'selected' : '' }}>Sukon</option>
|
||||
@@ -176,19 +170,18 @@
|
||||
<!-- Filter Tampilan Per Halaman -->
|
||||
<select name="per_page"
|
||||
onchange="this.form.submit()"
|
||||
class="w-full sm:w-auto text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
class="text-xs rounded-xl border border-slate-200 bg-white px-2.5 sm:px-3 py-2.5 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition truncate">
|
||||
<option value="15" {{ request('per_page', '15') == '15' ? 'selected' : '' }}>15 / Hal</option>
|
||||
<option value="50" {{ request('per_page', '50') == '50' ? 'selected' : '' }}>50 / Hal</option>
|
||||
<option value="100" {{ request('per_page', '100') == '100' ? 'selected' : '' }}>Semua (100)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Tombol Reset Filter -->
|
||||
<div id="timesheetResetContainer">
|
||||
@if(request()->anyFilled(['search', 'vehicle_id', 'shift', 'operator_type', 'per_page']) || (request('start_date') && request('start_date') !== now()->toDateString()) || (request('end_date') && request('end_date') !== now()->toDateString()))
|
||||
<a href="{{ url()->current() }}"
|
||||
id="timesheetResetBtn"
|
||||
class="text-xs text-rose-600 hover:text-rose-700 font-semibold flex items-center justify-center sm:justify-start space-x-1.5 transition whitespace-nowrap py-1 sm:py-0 sm:ml-2">
|
||||
class="text-xs text-rose-600 hover:text-rose-700 font-semibold flex items-center justify-center sm:justify-start space-x-1.5 transition whitespace-nowrap py-1 sm:py-0 sm:ml-1">
|
||||
<i class="fa-solid fa-rotate-left text-[11px]"></i>
|
||||
<span>Reset Filter</span>
|
||||
</a>
|
||||
@@ -308,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 -->
|
||||
@@ -368,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, ',', '.') : '-',
|
||||
@@ -486,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"
|
||||
<div class="relative">
|
||||
<input type="text"
|
||||
id="addLocationInput"
|
||||
name="location"
|
||||
list="addLocationsDatalist"
|
||||
required
|
||||
onchange="onTimesheetLocationChanged(this.value, 'add')"
|
||||
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">
|
||||
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
|
||||
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
|
||||
<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
|
||||
@if(isset($otherLocations) && count($otherLocations))
|
||||
<optgroup label="Lokasi Lainnya di Site">
|
||||
@foreach($otherLocations as $otherLoc)
|
||||
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
|
||||
@endforeach
|
||||
</optgroup>
|
||||
@foreach($locationSuggestions as $suggLoc)
|
||||
@if(!isset($unitLocations[$suggLoc]))
|
||||
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
|
||||
@endif
|
||||
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
|
||||
</select>
|
||||
<div id="addCustomLocationWrapper" class="hidden mt-2">
|
||||
<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]">
|
||||
@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>
|
||||
@@ -524,6 +529,19 @@
|
||||
<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>
|
||||
<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
|
||||
@@ -531,6 +549,7 @@
|
||||
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>
|
||||
@@ -571,7 +590,7 @@
|
||||
id="addOperatorSelect"
|
||||
required
|
||||
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
|
||||
<option value="">-- Pilih Operator --</option>
|
||||
<option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
|
||||
@foreach($operators as $op)
|
||||
@php
|
||||
$opType = $op->employee_type ?: 'Karyawan';
|
||||
@@ -587,7 +606,7 @@
|
||||
@endforeach
|
||||
</select>
|
||||
<p id="addOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
|
||||
<span>Total personil: {{ count($operators) }}</span>
|
||||
<span>Total personil: - (Pilih unit terlebih dahulu)</span>
|
||||
<span class="text-emerald-700 font-semibold" id="addOperatorCurrentFilterText">Filter: Semua</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -633,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">
|
||||
@@ -651,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>
|
||||
@@ -660,10 +701,7 @@
|
||||
<option value="KM">KM (Odometer)</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>
|
||||
@@ -675,6 +713,9 @@
|
||||
<option value="Maintenance">Maintenance (Servis Rutin)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<input type="hidden" name="shift" value="Shift Siang">
|
||||
|
||||
<!-- Baris 6: Rincian Tugas & Catatan -->
|
||||
<div>
|
||||
@@ -818,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"
|
||||
<div class="relative">
|
||||
<input type="text"
|
||||
id="editLocationInput"
|
||||
name="location"
|
||||
list="editLocationsDatalist"
|
||||
required
|
||||
onchange="onTimesheetLocationChanged(this.value, 'edit')"
|
||||
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">
|
||||
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
|
||||
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
|
||||
<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
|
||||
@if(isset($otherLocations) && count($otherLocations))
|
||||
<optgroup label="Lokasi Lainnya di Site">
|
||||
@foreach($otherLocations as $otherLoc)
|
||||
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
|
||||
@endforeach
|
||||
</optgroup>
|
||||
@foreach($locationSuggestions as $suggLoc)
|
||||
@if(!isset($unitLocations[$suggLoc]))
|
||||
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
|
||||
@endif
|
||||
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
|
||||
</select>
|
||||
<div id="editCustomLocationWrapper" class="hidden mt-2">
|
||||
<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]">
|
||||
@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>
|
||||
@@ -856,6 +897,19 @@
|
||||
<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>
|
||||
<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
|
||||
@@ -863,6 +917,7 @@
|
||||
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>
|
||||
@@ -903,7 +958,7 @@
|
||||
id="editOperatorSelect"
|
||||
required
|
||||
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
|
||||
<option value="">-- Pilih Operator --</option>
|
||||
<option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
|
||||
@foreach($operators as $op)
|
||||
@php
|
||||
$opType = $op->employee_type ?: 'Karyawan';
|
||||
@@ -919,7 +974,7 @@
|
||||
@endforeach
|
||||
</select>
|
||||
<p id="editOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
|
||||
<span>Total personil: {{ count($operators) }}</span>
|
||||
<span>Total personil: - (Pilih unit terlebih dahulu)</span>
|
||||
<span class="text-emerald-700 font-semibold" id="editOperatorCurrentFilterText">Filter: Semua</span>
|
||||
</p>
|
||||
</div>
|
||||
@@ -963,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">
|
||||
@@ -981,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>
|
||||
@@ -990,10 +1067,7 @@
|
||||
<option value="KM">KM (Odometer)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Baris 5: Status Akhir Unit (Shift disimpan secara 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>
|
||||
@@ -1005,6 +1079,10 @@
|
||||
<option value="Maintenance">Maintenance (Servis Rutin)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Baris 5: Shift (disimpan otomatis) -->
|
||||
<input type="hidden" name="shift" id="editShift" value="Shift Siang">
|
||||
|
||||
<!-- Baris 6: Deskripsi & Catatan -->
|
||||
<div>
|
||||
@@ -1175,13 +1253,17 @@
|
||||
<script>
|
||||
window.unitSupportsData = @json($unitSupports);
|
||||
window.allOperatorsData = @json($operators);
|
||||
window.unitOperatorsMap = @json($unitOperatorsMap);
|
||||
|
||||
// Filter Segmented Operator (Semua / Karyawan / Sukon)
|
||||
// Filter Segmented Operator (Semua / Karyawan / Sukon) & Sinkronisasi Kualifikasi SIMPER Alat Berat
|
||||
function filterOperatorSelect(type, mode, preserveSelectedId) {
|
||||
const selectId = mode === 'edit' ? 'editOperatorSelect' : 'addOperatorSelect';
|
||||
const select = document.getElementById(selectId);
|
||||
if (!select) return;
|
||||
|
||||
type = type || 'all';
|
||||
select.setAttribute('data-active-filter', type);
|
||||
|
||||
// Update button states
|
||||
const types = ['all', 'Karyawan', 'Sukon'];
|
||||
types.forEach(t => {
|
||||
@@ -1201,36 +1283,91 @@
|
||||
filterText.textContent = `Filter: ${type === 'all' ? 'Semua' : type}`;
|
||||
}
|
||||
|
||||
const vehSelect = document.getElementById(`${mode}VehicleSelect`);
|
||||
const selectedVehicleId = vehSelect ? vehSelect.value : null;
|
||||
|
||||
const currentVal = preserveSelectedId !== undefined ? String(preserveSelectedId) : select.value;
|
||||
const options = select.querySelectorAll('option');
|
||||
let visibleCount = 0;
|
||||
|
||||
// 1. Jika belum ada unit Heavy Equipment yang dipilih
|
||||
if (!selectedVehicleId) {
|
||||
options.forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.textContent = '-- Pilih Heavy Equipment Terlebih Dahulu --';
|
||||
opt.hidden = false;
|
||||
} else {
|
||||
opt.hidden = true;
|
||||
}
|
||||
});
|
||||
select.value = '';
|
||||
|
||||
const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
|
||||
if (countHelp) {
|
||||
const spanFirst = countHelp.querySelector('span:first-child');
|
||||
if (spanFirst) {
|
||||
spanFirst.textContent = 'Total personil: - (Pilih unit terlebih dahulu)';
|
||||
spanFirst.className = 'text-slate-400';
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Dapatkan daftar ID operator yang kualifikasi SIMPER-nya aktif untuk unit ini
|
||||
const eligibleMap = window.unitOperatorsMap || {};
|
||||
const eligibleIds = eligibleMap[selectedVehicleId] || [];
|
||||
const eligibleSet = new Set(eligibleIds.map(String));
|
||||
|
||||
if (preserveSelectedId !== undefined && preserveSelectedId !== null && preserveSelectedId !== '') {
|
||||
eligibleSet.add(String(preserveSelectedId));
|
||||
}
|
||||
|
||||
const hasEligible = eligibleSet.size > 0;
|
||||
|
||||
options.forEach(opt => {
|
||||
if (!opt.value) {
|
||||
if (!hasEligible) {
|
||||
opt.textContent = '-- Tidak ada operator dengan SIMPER untuk unit ini --';
|
||||
} else {
|
||||
opt.textContent = `-- Pilih Operator (${eligibleSet.size} Memenuhi SIMPER) --`;
|
||||
}
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const opId = String(opt.value);
|
||||
const isEligible = eligibleSet.has(opId);
|
||||
const optType = opt.getAttribute('data-type') || 'Karyawan';
|
||||
let match = false;
|
||||
|
||||
let typeMatch = false;
|
||||
if (type === 'all') {
|
||||
match = true;
|
||||
typeMatch = true;
|
||||
} else if (type === 'Karyawan') {
|
||||
match = optType === 'Karyawan';
|
||||
typeMatch = optType === 'Karyawan';
|
||||
} else if (type === 'Sukon') {
|
||||
match = optType === 'Sukon';
|
||||
typeMatch = optType === 'Sukon';
|
||||
} else {
|
||||
match = optType.toLowerCase() === type.toLowerCase();
|
||||
typeMatch = optType.toLowerCase() === type.toLowerCase();
|
||||
}
|
||||
|
||||
const match = isEligible && typeMatch;
|
||||
opt.hidden = !match;
|
||||
if (match) visibleCount++;
|
||||
});
|
||||
|
||||
// Update total count
|
||||
// Update total count & status
|
||||
const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
|
||||
if (countHelp) {
|
||||
const spanFirst = countHelp.querySelector('span:first-child');
|
||||
if (spanFirst) spanFirst.textContent = `Total personil: ${visibleCount}`;
|
||||
if (spanFirst) {
|
||||
if (!hasEligible) {
|
||||
spanFirst.textContent = 'Total personil: 0 (Tidak ada SIMPER yang cocok)';
|
||||
spanFirst.className = 'text-rose-600 font-semibold';
|
||||
} else {
|
||||
spanFirst.textContent = `Total personil: ${visibleCount} dari ${eligibleSet.size} operator SIMPER aktif`;
|
||||
spanFirst.className = 'text-slate-500';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore or reset selection
|
||||
@@ -1241,6 +1378,8 @@
|
||||
} else if (preserveSelectedId === undefined) {
|
||||
select.value = '';
|
||||
}
|
||||
} else {
|
||||
select.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1264,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 = '';
|
||||
@@ -1370,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';
|
||||
@@ -1433,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';
|
||||
@@ -1466,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`);
|
||||
@@ -1477,38 +1596,28 @@
|
||||
|
||||
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;
|
||||
}
|
||||
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');
|
||||
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
|
||||
// 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) {
|
||||
@@ -1516,17 +1625,18 @@
|
||||
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`;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 = '';
|
||||
@@ -1535,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;
|
||||
@@ -1566,6 +1676,7 @@
|
||||
} else {
|
||||
defaultPrompt.selected = true;
|
||||
if (previewEl) previewEl.classList.add('hidden');
|
||||
filterOperatorSelect('all', prefix);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1577,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];
|
||||
@@ -1614,12 +1777,20 @@
|
||||
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;
|
||||
}
|
||||
|
||||
// Otomatis filter operator sesuai izin SIMPER aktif untuk alat berat ini
|
||||
const opSelect = document.getElementById(`${prefix}OperatorSelect`);
|
||||
const currentOpFilter = opSelect ? (opSelect.getAttribute('data-active-filter') || 'all') : 'all';
|
||||
filterOperatorSelect(currentOpFilter, prefix);
|
||||
}
|
||||
|
||||
function updateMeterUnitLabels(prefix) {
|
||||
@@ -1629,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,8 +68,21 @@
|
||||
<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="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"
|
||||
@@ -90,7 +103,8 @@
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
<p class="text-[10px] text-slate-400 mt-1">Memilih lokasi awal akan memfilter unit alat berat yang berada di titik tersebut.</p>
|
||||
</div>
|
||||
<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,6 +113,19 @@
|
||||
<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>
|
||||
<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
|
||||
@@ -120,6 +147,7 @@
|
||||
</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,51 +367,66 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Grid 2 Kolom: Pilih Mobil Pengangkut & Nama Pengangkut -->
|
||||
<!-- ============================================== -->
|
||||
<!-- 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">
|
||||
<!-- Pilih Mobil dari Unit Kita -->
|
||||
<!-- KIRI: PILIH LOKASI ASAL PENGANGKUT (INTERNAL) -->
|
||||
<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 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>
|
||||
<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' }}]
|
||||
<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>
|
||||
|
||||
<!-- Input / Snapshot Nama Armada Pengangkut -->
|
||||
<!-- KANAN: PILIH KENDARAAN PENGANGKUT (INPUT KETIKAN TERFILTER) -->
|
||||
<div>
|
||||
<label for="transporter_unit_name" class="block text-xs font-bold text-slate-700 mb-1.5">
|
||||
Identitas / Keterangan Kendaraan Pengangkut
|
||||
<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 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<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"
|
||||
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">
|
||||
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">Otomatis terisi jika memilih armada internal, atau ketik nama vendor/unit rekanan luar.</p>
|
||||
<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 -->
|
||||
<div class="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center space-x-3">
|
||||
<!-- 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"
|
||||
@@ -350,9 +437,58 @@
|
||||
Perbarui juga posisi terkini truk pengangkut ke lokasi tujuan setelah proses pemindahan selesai
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ============================================== -->
|
||||
<!-- 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) {
|
||||
if (!banner || !text) return;
|
||||
|
||||
const originLoc = originSelect && originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
|
||||
const destLoc = destinationInput && destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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]';
|
||||
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 {
|
||||
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');
|
||||
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>.`;
|
||||
} 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>.`;
|
||||
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,53 +82,76 @@
|
||||
</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>
|
||||
<!-- 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, 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">
|
||||
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">
|
||||
<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' : '' }}>
|
||||
@@ -148,124 +159,107 @@
|
||||
</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- 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">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<!-- 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 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>
|
||||
</div>
|
||||
|
||||
<!-- Tabel Riwayat Transfer Unit dengan Header Biru Tua Navy (Pada Mobile: Format Kotak Tanpa Border Radius) -->
|
||||
<!-- Tabel Riwayat Transfer Unit -->
|
||||
<div class="bg-white rounded-none sm:rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
|
||||
<div class="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]">
|
||||
<!-- 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)
|
||||
<div class="font-bold text-slate-900 leading-tight font-mono text-xs">
|
||||
<span class="font-bold text-slate-900 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>
|
||||
</span>
|
||||
@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">
|
||||
<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>
|
||||
<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 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>
|
||||
|
||||
<!-- 4. Unit Alat Berat -->
|
||||
<td class="py-3.5 px-3.5 whitespace-nowrap">
|
||||
<div class="flex items-center space-x-2.5">
|
||||
<!-- 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-9 h-9 rounded-xl object-cover border border-slate-200 shrink-0">
|
||||
<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-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>
|
||||
<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');
|
||||
|
||||
@@ -12,3 +12,8 @@ Artisan::command('inspire', function () {
|
||||
// Jadwalkan pembatalan otomatis tiket perjalanan pending yang melewati 5 jam
|
||||
Schedule::command(ExpirePendingActivitiesCommand::class)->hourly();
|
||||
|
||||
// Jadwalkan pembersihan otomatis tong sampah sesuai retensi sistem setiap malam
|
||||
Schedule::command('trash:prune')->daily();
|
||||
|
||||
// Catatan: Backup sistem dijalankan secara manual oleh Super Admin via menu web untuk menghemat kapasitas storage VPS.
|
||||
|
||||
|
||||
+11
-11
@@ -48,13 +48,6 @@ Route::prefix('gate-activity')->name('vehicle.activity.')->group(function () {
|
||||
// Group Terproteksi Autentikasi Sistem
|
||||
Route::middleware('auth')->group(function () {
|
||||
|
||||
// Backward Compatibility: Rute Super Admin Legacy -> Admin Dashboard Baru
|
||||
Route::prefix('superadmin')->name('superadmin.')->middleware('role:super_admin')->group(function () {
|
||||
Route::get('/', fn() => redirect()->route('admin.dashboard'));
|
||||
Route::get('/dashboard', fn() => redirect()->route('admin.dashboard'))->name('dashboard');
|
||||
Route::get('/roles', fn() => redirect()->route('admin.roles.index'))->name('roles.index');
|
||||
});
|
||||
|
||||
// 2. Modul HSE: Admin HSE - Kelola Karyawan & SIMPER
|
||||
Route::prefix('hse')->name('hse.')->group(function () {
|
||||
Route::get('/dashboard', [EmployeeController::class, 'dashboard'])->name('dashboard')->middleware('permission:hse.employees.view');
|
||||
@@ -95,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');
|
||||
@@ -146,6 +139,7 @@ Route::middleware('auth')->group(function () {
|
||||
Route::get('/p2h-records/{id}/export-excel', [P2hInspectionController::class, 'exportSingleExcel'])->name('p2h.export_single_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view');
|
||||
Route::post('/p2h-records/{id}/approve', [P2hInspectionController::class, 'approve'])->name('p2h.approve')->middleware('permission:qma.p2h.approve|qma.vehicles.edit');
|
||||
Route::post('/p2h-records/{id}/reject', [P2hInspectionController::class, 'reject'])->name('p2h.reject')->middleware('permission:qma.p2h.approve|qma.vehicles.edit');
|
||||
Route::delete('/p2h-records/{id}', [P2hInspectionController::class, 'destroy'])->name('p2h.destroy')->middleware('permission:qma.vehicles.delete|qma.p2h.approve|qma.vehicles.edit');
|
||||
|
||||
// Master 28 Template Checksheet P2H & Kelola Pertanyaan
|
||||
Route::get('/p2h-templates', [P2hTemplateController::class, 'index'])->name('p2h.templates')->middleware('permission:qma.p2h.templates|qma.vehicles.view');
|
||||
@@ -187,8 +181,11 @@ Route::middleware('auth')->group(function () {
|
||||
Route::post('/{code}', [P2hFormController::class, 'store'])->middleware('throttle:30,1')->name('store');
|
||||
});
|
||||
|
||||
// 6. Modul Karyawan (Dashboard, P2H, Timesheet)
|
||||
// 6. Modul Karyawan (Dashboard, Riwayat Aktivitas, P2H, Timesheet)
|
||||
Route::get('/karyawan/dashboard', [\App\Http\Controllers\Employee\DashboardController::class, 'index'])->name('employee.dashboard');
|
||||
Route::get('/karyawan/riwayat', [\App\Http\Controllers\Employee\DashboardController::class, 'history'])->name('employee.history');
|
||||
Route::get('/karyawan/riwayat/p2h/{id}', [\App\Http\Controllers\Employee\DashboardController::class, 'p2hDetail'])->name('employee.history.p2h_detail');
|
||||
Route::get('/karyawan/riwayat/p2h/{id}/pdf', [\App\Http\Controllers\Employee\DashboardController::class, 'p2hPdf'])->name('employee.history.p2h_pdf');
|
||||
Route::get('/karyawan/aktivitas/status-polling', [\App\Http\Controllers\Employee\DashboardController::class, 'activeTripStatus'])->name('employee.activity.status_polling');
|
||||
Route::post('/karyawan/aktivitas/{id}/update-km', [\App\Http\Controllers\Employee\DashboardController::class, 'updateKm'])->name('employee.activity.update_km');
|
||||
Route::post('/karyawan/aktivitas/{id}/cancel', [\App\Http\Controllers\Employee\DashboardController::class, 'cancelActivity'])->name('employee.activity.cancel');
|
||||
@@ -217,14 +214,17 @@ 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/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file');
|
||||
Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1');
|
||||
Route::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');
|
||||
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1');
|
||||
Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy');
|
||||
|
||||
// Tong Sampah / Recycle Bin & Retensi Otomatis
|
||||
|
||||
@@ -310,4 +310,33 @@ class BackupAndRestoreTest extends TestCase
|
||||
'target_name' => 'backup_dari_pc.kmh',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_inspect_and_convert_server_backup_file(): void
|
||||
{
|
||||
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, 'test_server_conv.kmh');
|
||||
|
||||
// 1. Inspect server file via AJAX
|
||||
$inspectResponse = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'server_filename' => $filename,
|
||||
]);
|
||||
|
||||
$inspectResponse->assertStatus(200);
|
||||
$inspectResponse->assertJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$token = $inspectResponse->json('data.token');
|
||||
$this->assertNotEmpty($token);
|
||||
|
||||
// 2. Convert using token to SQL
|
||||
$convResponse = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'token' => $token,
|
||||
'tables' => ['users'],
|
||||
'format' => 'sql',
|
||||
]);
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\P2hRecord;
|
||||
use App\Models\P2hRecordItem;
|
||||
use App\Models\P2hTemplate;
|
||||
use App\Models\UnitSupportTimesheet;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use Carbon\Carbon;
|
||||
use Database\Seeders\RolePermissionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Tests\TestCase;
|
||||
|
||||
class EmployeeHistoryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected User $userA;
|
||||
protected Employee $empA;
|
||||
protected User $userB;
|
||||
protected Employee $empB;
|
||||
protected Vehicle $heavyEquipment;
|
||||
protected Vehicle $lightVehicle;
|
||||
protected Gate $gate;
|
||||
protected P2hTemplate $template;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed(RolePermissionSeeder::class);
|
||||
|
||||
// Karyawan / Operator A
|
||||
$this->userA = User::create([
|
||||
'name' => 'Operator Alex Test',
|
||||
'username' => 'operator_alex',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password123'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$this->userA->givePermissionTo(['employee.dashboard', 'employee.p2h', 'employee.timesheet']);
|
||||
$this->empA = $this->userA->getOrCreateEmployee();
|
||||
$this->empA->update(['is_operator' => true]);
|
||||
|
||||
// Karyawan / Operator B
|
||||
$this->userB = User::create([
|
||||
'name' => 'Operator Budi Test',
|
||||
'username' => 'operator_budi',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password123'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$this->userB->givePermissionTo(['employee.dashboard', 'employee.p2h', 'employee.timesheet']);
|
||||
$this->empB = $this->userB->getOrCreateEmployee();
|
||||
$this->empB->update(['is_operator' => true]);
|
||||
|
||||
// Unit Heavy Equipment
|
||||
$this->heavyEquipment = Vehicle::create([
|
||||
'code' => 'EXC-HIST-01',
|
||||
'brand_type' => 'Komatsu PC200 History Test',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Excavator',
|
||||
'status' => 'Operation',
|
||||
]);
|
||||
|
||||
// Unit Light Vehicle
|
||||
$this->lightVehicle = Vehicle::create([
|
||||
'code' => 'LV-HIST-01',
|
||||
'brand_type' => 'Toyota Hilux 4x4',
|
||||
'category' => 'light_vehicle',
|
||||
'license_plate' => 'BH 1234 XY',
|
||||
'status' => 'Operation',
|
||||
]);
|
||||
|
||||
// Pos Gerbang
|
||||
$this->gate = Gate::create([
|
||||
'name' => 'Pos Gerbang Utama PLTA',
|
||||
'code' => 'PG-01',
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
// Template P2H
|
||||
$this->template = P2hTemplate::firstOrCreate(
|
||||
['code' => 'EXD4RP'],
|
||||
[
|
||||
'name' => 'Excavator Checksheet Test',
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
// Berikan SIMPER Heavy Equipment untuk Operator A & B
|
||||
$simperHeavy = \App\Models\SimperType::firstOrCreate(
|
||||
['code' => 'SIMPER-HEAVY'],
|
||||
[
|
||||
'name' => 'Heavy Equipment',
|
||||
'scopes' => ['unit_support_heavy', 'Excavator'],
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
\App\Models\EmployeeSimper::create([
|
||||
'employee_id' => $this->empA->id,
|
||||
'simper_type_id' => $simperHeavy->id,
|
||||
'status' => 'active',
|
||||
'expired_at' => Carbon::now()->addMonths(6),
|
||||
]);
|
||||
|
||||
\App\Models\EmployeeSimper::create([
|
||||
'employee_id' => $this->empB->id,
|
||||
'simper_type_id' => $simperHeavy->id,
|
||||
'status' => 'active',
|
||||
'expired_at' => Carbon::now()->addMonths(6),
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_guest_is_redirected_to_login(): void
|
||||
{
|
||||
$response = $this->get(route('employee.history'));
|
||||
$response->assertRedirect(route('login'));
|
||||
}
|
||||
|
||||
public function test_employee_can_access_history_page(): void
|
||||
{
|
||||
$response = $this->actingAs($this->userA)->get(route('employee.history'));
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('Riwayat Aktivitas Saya');
|
||||
$response->assertSee('P2H Heavy Equipment');
|
||||
}
|
||||
|
||||
public function test_employee_only_sees_their_own_p2h_records(): void
|
||||
{
|
||||
// P2H milik A
|
||||
$recordA = P2hRecord::create([
|
||||
'transaction_no' => 'P2H-ALEX-001',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'employee_id' => $this->empA->id,
|
||||
'template_id' => $this->template->id,
|
||||
'shift' => '1',
|
||||
'start_hm' => 1250.5,
|
||||
'summary_condition' => 'good',
|
||||
'defect_count' => 0,
|
||||
'validation_status' => 'approved',
|
||||
'inspected_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
// P2H milik B
|
||||
$recordB = P2hRecord::create([
|
||||
'transaction_no' => 'P2H-BUDI-999',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'employee_id' => $this->empB->id,
|
||||
'template_id' => $this->template->id,
|
||||
'shift' => '2',
|
||||
'start_hm' => 2400.0,
|
||||
'summary_condition' => 'has_defect',
|
||||
'defect_count' => 1,
|
||||
'validation_status' => 'pending',
|
||||
'inspected_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
// Acting as User A
|
||||
$responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'p2h']));
|
||||
$responseA->assertStatus(200);
|
||||
$responseA->assertSee('P2H-ALEX-001');
|
||||
$responseA->assertDontSee('P2H-BUDI-999');
|
||||
|
||||
// Acting as User B
|
||||
$responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'p2h']));
|
||||
$responseB->assertStatus(200);
|
||||
$responseB->assertSee('P2H-BUDI-999');
|
||||
$responseB->assertDontSee('P2H-ALEX-001');
|
||||
}
|
||||
|
||||
public function test_employee_only_sees_their_own_timesheets(): void
|
||||
{
|
||||
// Timesheet milik Operator A
|
||||
UnitSupportTimesheet::create([
|
||||
'timesheet_no' => 'TS-ALEX-001',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'operator_id' => $this->empA->id,
|
||||
'date' => Carbon::today(),
|
||||
'shift' => '1',
|
||||
'meter_type' => 'hm',
|
||||
'start_meter' => 100,
|
||||
'end_meter' => 108,
|
||||
'operating_hours' => 8.0,
|
||||
'activity_type' => 'Operation',
|
||||
'location' => 'Incline Shaft Section 1',
|
||||
'task_description' => 'Mucking and clearing rocks',
|
||||
'status' => 'completed',
|
||||
]);
|
||||
|
||||
// Timesheet milik Operator B
|
||||
UnitSupportTimesheet::create([
|
||||
'timesheet_no' => 'TS-BUDI-999',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'operator_id' => $this->empB->id,
|
||||
'date' => Carbon::today(),
|
||||
'shift' => '2',
|
||||
'meter_type' => 'hm',
|
||||
'start_meter' => 200,
|
||||
'end_meter' => 206,
|
||||
'operating_hours' => 6.0,
|
||||
'activity_type' => 'Operation',
|
||||
'location' => 'Powerhouse Cavern',
|
||||
'task_description' => 'Excavation trench',
|
||||
'status' => 'completed',
|
||||
]);
|
||||
|
||||
// Acting as User A
|
||||
$responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'timesheet']));
|
||||
$responseA->assertStatus(200);
|
||||
$responseA->assertSee('TS-ALEX-001');
|
||||
$responseA->assertSee('Incline Shaft Section 1');
|
||||
$responseA->assertDontSee('TS-BUDI-999');
|
||||
$responseA->assertDontSee('Powerhouse Cavern');
|
||||
|
||||
// Acting as User B
|
||||
$responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'timesheet']));
|
||||
$responseB->assertStatus(200);
|
||||
$responseB->assertSee('TS-BUDI-999');
|
||||
$responseB->assertSee('Powerhouse Cavern');
|
||||
$responseB->assertDontSee('TS-ALEX-001');
|
||||
}
|
||||
|
||||
public function test_employee_only_sees_their_own_vehicle_activity_trips(): void
|
||||
{
|
||||
// Trip milik Driver A
|
||||
VehicleActivity::create([
|
||||
'transaction_no' => 'TRIP-ALEX-001',
|
||||
'vehicle_id' => $this->lightVehicle->id,
|
||||
'driver_id' => $this->empA->id,
|
||||
'gate_id' => $this->gate->id,
|
||||
'direction' => 'out',
|
||||
'previous_km' => 10000,
|
||||
'current_km' => 10035,
|
||||
'distance' => 35,
|
||||
'purpose' => 'Antar Logistik ke Camp Merangin Alex',
|
||||
'recorded_at' => Carbon::now(),
|
||||
'validation_status' => 'approved',
|
||||
]);
|
||||
|
||||
// Trip milik Driver B
|
||||
VehicleActivity::create([
|
||||
'transaction_no' => 'TRIP-BUDI-999',
|
||||
'vehicle_id' => $this->lightVehicle->id,
|
||||
'driver_id' => $this->empB->id,
|
||||
'gate_id' => $this->gate->id,
|
||||
'direction' => 'in',
|
||||
'previous_km' => 20000,
|
||||
'current_km' => 20050,
|
||||
'distance' => 50,
|
||||
'purpose' => 'Patroli Jalur Pipa Budi',
|
||||
'recorded_at' => Carbon::now(),
|
||||
'validation_status' => 'approved',
|
||||
]);
|
||||
|
||||
// Acting as User A
|
||||
$responseA = $this->actingAs($this->userA)->get(route('employee.history', ['tab' => 'trips']));
|
||||
$responseA->assertStatus(200);
|
||||
$responseA->assertSee('TRIP-ALEX-001');
|
||||
$responseA->assertSee('Antar Logistik ke Camp Merangin Alex');
|
||||
$responseA->assertDontSee('TRIP-BUDI-999');
|
||||
$responseA->assertDontSee('Patroli Jalur Pipa Budi');
|
||||
|
||||
// Acting as User B
|
||||
$responseB = $this->actingAs($this->userB)->get(route('employee.history', ['tab' => 'trips']));
|
||||
$responseB->assertStatus(200);
|
||||
$responseB->assertSee('TRIP-BUDI-999');
|
||||
$responseB->assertSee('Patroli Jalur Pipa Budi');
|
||||
$responseB->assertDontSee('TRIP-ALEX-001');
|
||||
}
|
||||
|
||||
public function test_tabs_adapt_according_to_employee_permissions_and_records(): void
|
||||
{
|
||||
// User C: Hanya punya akses Timesheet LV, tidak punya P2H dan bukan operator
|
||||
$userC = User::create([
|
||||
'name' => 'Driver Cici Test',
|
||||
'username' => 'driver_cici',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password123'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$userC->syncRoles([]);
|
||||
$userC->givePermissionTo(['employee.dashboard', 'employee.timesheet']);
|
||||
$empC = $userC->getOrCreateEmployee();
|
||||
$empC->update(['is_operator' => false]);
|
||||
|
||||
$response = $this->actingAs($userC)->get(route('employee.history'));
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('Mobilisasi');
|
||||
$response->assertSee('Pos Gerbang');
|
||||
$response->assertDontSee('P2H Heavy Equipment');
|
||||
$response->assertDontSee('Timesheet Heavy Equipment');
|
||||
}
|
||||
|
||||
public function test_employee_can_view_own_p2h_detail_and_pdf(): void
|
||||
{
|
||||
$recordA = P2hRecord::create([
|
||||
'transaction_no' => 'P2H-DETAIL-001',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'employee_id' => $this->empA->id,
|
||||
'template_id' => $this->template->id,
|
||||
'shift' => '1',
|
||||
'start_hm' => 1500,
|
||||
'summary_condition' => 'good',
|
||||
'defect_count' => 0,
|
||||
'validation_status' => 'approved',
|
||||
'inspected_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
P2hRecordItem::create([
|
||||
'p2h_record_id' => $recordA->id,
|
||||
'section' => 'Cabin Inspection',
|
||||
'title' => 'Kaca Spion & Wiper',
|
||||
'question_type' => 'choice',
|
||||
'condition_status' => 'baik',
|
||||
]);
|
||||
|
||||
// Detail JSON
|
||||
$resJson = $this->actingAs($this->userA)->get(route('employee.history.p2h_detail', $recordA->id));
|
||||
$resJson->assertStatus(200);
|
||||
$resJson->assertJsonFragment([
|
||||
'transaction_no' => 'P2H-DETAIL-001',
|
||||
'item_name' => 'Kaca Spion & Wiper',
|
||||
]);
|
||||
|
||||
// PDF stream
|
||||
$resPdf = $this->actingAs($this->userA)->get(route('employee.history.p2h_pdf', $recordA->id));
|
||||
$resPdf->assertStatus(200);
|
||||
$resPdf->assertHeader('Content-Type', 'application/pdf');
|
||||
}
|
||||
|
||||
public function test_employee_cannot_view_or_download_pdf_of_other_employee_p2h(): void
|
||||
{
|
||||
// Record milik B
|
||||
$recordB = P2hRecord::create([
|
||||
'transaction_no' => 'P2H-PRIVATE-BUDI',
|
||||
'vehicle_id' => $this->heavyEquipment->id,
|
||||
'employee_id' => $this->empB->id,
|
||||
'template_id' => $this->template->id,
|
||||
'shift' => '1',
|
||||
'start_hm' => 2000,
|
||||
'summary_condition' => 'good',
|
||||
'defect_count' => 0,
|
||||
'validation_status' => 'approved',
|
||||
'inspected_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
// User A mencoba melihat detail B -> 403 Forbidden
|
||||
$resDetail = $this->actingAs($this->userA)->get(route('employee.history.p2h_detail', $recordB->id));
|
||||
$resDetail->assertStatus(403);
|
||||
|
||||
// User A mencoba mengunduh PDF B -> 403 Forbidden
|
||||
$resPdf = $this->actingAs($this->userA)->get(route('employee.history.p2h_pdf', $recordB->id));
|
||||
$resPdf->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_employee_with_only_lv_simper_does_not_see_heavy_equipment(): void
|
||||
{
|
||||
$simperLv = \App\Models\SimperType::firstOrCreate(
|
||||
['code' => 'SIMPER-LV'],
|
||||
[
|
||||
'name' => 'Light Vehicle Only',
|
||||
'scopes' => ['light_vehicle'],
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$userDriver = User::create([
|
||||
'name' => 'Driver Doni LV Only',
|
||||
'username' => 'driver_doni',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password123'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$empDriver = $userDriver->getOrCreateEmployee();
|
||||
$empDriver->update(['is_operator' => true]);
|
||||
|
||||
\App\Models\EmployeeSimper::create([
|
||||
'employee_id' => $empDriver->id,
|
||||
'simper_type_id' => $simperLv->id,
|
||||
'status' => 'active',
|
||||
'expired_at' => Carbon::now()->addMonths(6),
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($userDriver)->get(route('employee.history'));
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('Mobilisasi');
|
||||
$response->assertSee('Pos Gerbang');
|
||||
$response->assertDontSee('P2H Heavy Equipment');
|
||||
$response->assertDontSee('Timesheet Heavy Equipment');
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
]);
|
||||
@@ -734,6 +736,45 @@ class P2hInspectionTest extends TestCase
|
||||
$this->assertCount(4, $itemsAfterDelete);
|
||||
$this->assertEquals([1, 2, 3, 4], $itemsAfterDelete->pluck('sequence')->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin QMA dapat menghapus data riwayat pemeriksaan P2H (Soft Delete ke Tong Sampah).
|
||||
*/
|
||||
public function test_qma_admin_can_soft_delete_p2h_record(): void
|
||||
{
|
||||
$record = P2hRecord::create([
|
||||
'transaction_no' => 'P2H-TEST-DEL-001',
|
||||
'vehicle_id' => $this->supportVehicle->id,
|
||||
'employee_id' => $this->operatorEmp->id,
|
||||
'template_id' => $this->template->id,
|
||||
'shift' => 'Shift Siang',
|
||||
'start_hm' => 1500.0,
|
||||
'summary_condition' => 'normal',
|
||||
'validation_status' => 'pending',
|
||||
'inspected_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
$item = \App\Models\P2hRecordItem::create([
|
||||
'p2h_record_id' => $record->id,
|
||||
'section' => 'Bagian A',
|
||||
'title' => 'Cek Oli Mesin',
|
||||
'question_type' => 'choice',
|
||||
'condition_status' => 'baik',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->qmaAdmin)
|
||||
->delete(route('qma.p2h.destroy', $record->id));
|
||||
|
||||
$response->assertRedirect(route('qma.p2h.index'));
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
$this->assertSoftDeleted('p2h_records', ['id' => $record->id]);
|
||||
$this->assertSoftDeleted('p2h_record_items', ['id' => $item->id]);
|
||||
|
||||
// Pastikan muncul di TrashService
|
||||
$trashItems = app(\App\Services\TrashService::class)->getTrashedItems('p2h_records');
|
||||
$this->assertTrue(collect($trashItems->items())->contains('id', $record->id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -139,6 +139,11 @@ class PhotoUploadAndCompressionTest extends TestCase
|
||||
$deleteResponse->assertRedirect();
|
||||
|
||||
$this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]);
|
||||
// Foto tetap dipertahankan saat soft delete agar dapat dipulihkan dari Trash/Recycle Bin
|
||||
Storage::disk('public')->assertExists($photoPath);
|
||||
|
||||
// Ketika dihapus permanen melalui TrashService, file fisik baru terhapus
|
||||
app(\App\Services\TrashService::class)->forceDeleteItem('vehicles', $vehicle->id);
|
||||
Storage::disk('public')->assertMissing($photoPath);
|
||||
}
|
||||
|
||||
|
||||
@@ -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',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\EmployeeSimper;
|
||||
use App\Models\SimperType;
|
||||
use App\Models\UnitSupportTimesheet;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
@@ -47,6 +49,7 @@ class QmaSupportTimesheetTest extends TestCase
|
||||
$this->supportUnit = Vehicle::create([
|
||||
'code' => 'EX01',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Excavator',
|
||||
'brand_type' => 'Komatsu PC200-8 Excavator',
|
||||
'status' => 'Operation',
|
||||
'site_status' => 'inside_site',
|
||||
@@ -61,6 +64,7 @@ class QmaSupportTimesheetTest extends TestCase
|
||||
'department' => 'Civil Construction',
|
||||
'is_operator' => true,
|
||||
'is_driver' => true,
|
||||
'simper_expired_at' => Carbon::now()->addYear(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -547,4 +551,185 @@ class QmaSupportTimesheetTest extends TestCase
|
||||
$responseKaryawan->assertSee('TS-KARYAWAN-001');
|
||||
$responseKaryawan->assertDontSee('TS-SUKON-001');
|
||||
}
|
||||
|
||||
/**
|
||||
* Index memuat peta kualifikasi operator per alat berat (unitOperatorsMap).
|
||||
*/
|
||||
public function test_index_passes_unit_operators_map_matching_equipment_simper(): void
|
||||
{
|
||||
$simperEx = SimperType::create([
|
||||
'code' => 'SIMPER-EXCAVATOR',
|
||||
'name' => 'SIMPER Alat Excavator',
|
||||
'category_scope' => 'Excavator',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$simperDt = SimperType::create([
|
||||
'code' => 'SIMPER-DT-ONLY',
|
||||
'name' => 'SIMPER Khusus DT',
|
||||
'category_scope' => 'unit_support_mobile',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$opEx = Employee::create([
|
||||
'nik' => 'OP-EX-001',
|
||||
'name' => 'Operator Khusus Excavator',
|
||||
'is_operator' => true,
|
||||
'simper_expired_at' => Carbon::now()->addYear(),
|
||||
]);
|
||||
EmployeeSimper::create([
|
||||
'employee_id' => $opEx->id,
|
||||
'simper_type_id' => $simperEx->id,
|
||||
'expired_at' => Carbon::now()->addYear(),
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$opDt = Employee::create([
|
||||
'nik' => 'OP-DT-001',
|
||||
'name' => 'Driver Khusus Dump Truck',
|
||||
'is_operator' => true,
|
||||
'simper_expired_at' => Carbon::now()->addYear(),
|
||||
]);
|
||||
EmployeeSimper::create([
|
||||
'employee_id' => $opDt->id,
|
||||
'simper_type_id' => $simperDt->id,
|
||||
'expired_at' => Carbon::now()->addYear(),
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$unitDumpTruck = Vehicle::create([
|
||||
'code' => 'DT99',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Dump Truck',
|
||||
'brand_type' => 'Mitsubishi Fuso 220PS',
|
||||
'is_timesheet_mobile' => true,
|
||||
'status' => 'Operation',
|
||||
'site_status' => 'inside_site',
|
||||
'location' => 'Adit 1',
|
||||
'current_km' => 500.0,
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->qmaAdmin)
|
||||
->get(route('qma.support_timesheet.index'));
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertViewHas('unitOperatorsMap');
|
||||
|
||||
$map = $response->viewData('unitOperatorsMap');
|
||||
$this->assertIsArray($map);
|
||||
|
||||
// Unit EX01 harus memuat $opEx dan TIDAK memuat $opDt
|
||||
$this->assertContains($opEx->id, $map[$this->supportUnit->id]);
|
||||
$this->assertNotContains($opDt->id, $map[$this->supportUnit->id]);
|
||||
|
||||
// Unit DT99 harus memuat $opDt dan TIDAK memuat $opEx
|
||||
$this->assertContains($opDt->id, $map[$unitDumpTruck->id]);
|
||||
$this->assertNotContains($opEx->id, $map[$unitDumpTruck->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Operator dengan SIMPER Dump Truck ditolak saat menginput timesheet alat berat Excavator.
|
||||
*/
|
||||
public function test_store_fails_when_dump_truck_operator_attempts_excavator_timesheet(): void
|
||||
{
|
||||
$simperDt = SimperType::create([
|
||||
'code' => 'SIMPER-DT-ONLY2',
|
||||
'name' => 'SIMPER Khusus DT 2',
|
||||
'category_scope' => 'unit_support_mobile',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$opDt = Employee::create([
|
||||
'nik' => 'OP-DT-002',
|
||||
'name' => 'Driver DT Saja',
|
||||
'is_operator' => true,
|
||||
'simper_expired_at' => Carbon::now()->addYear(),
|
||||
]);
|
||||
EmployeeSimper::create([
|
||||
'employee_id' => $opDt->id,
|
||||
'simper_type_id' => $simperDt->id,
|
||||
'expired_at' => Carbon::now()->addYear(),
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$data = [
|
||||
'vehicle_id' => $this->supportUnit->id, // Excavator
|
||||
'operator_id' => $opDt->id,
|
||||
'date' => Carbon::today()->toDateString(),
|
||||
'shift' => 'Shift Siang',
|
||||
'meter_type' => 'HM',
|
||||
'start_meter' => 1250.00,
|
||||
'end_meter' => 1258.00,
|
||||
'location' => 'Main Dam',
|
||||
'activity_type' => 'Galian Material',
|
||||
'status' => 'Operation',
|
||||
];
|
||||
|
||||
$response = $this->actingAs($this->qmaAdmin)
|
||||
->post(route('qma.support_timesheet.store'), $data);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('error');
|
||||
$this->assertDatabaseMissing('unit_support_timesheets', [
|
||||
'vehicle_id' => $this->supportUnit->id,
|
||||
'operator_id' => $opDt->id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -556,4 +556,112 @@ class SuperAdminRbacTest extends TestCase
|
||||
$this->assertEquals('Operator Turbin', $employee->position);
|
||||
$this->assertFalse((bool)$employee->is_operator);
|
||||
}
|
||||
|
||||
public function test_super_admin_cannot_delete_employee_core_role(): void
|
||||
{
|
||||
$superAdmin = User::where('username', 'superadmin')->first();
|
||||
$employeeRole = Role::where('name', 'employee')->first();
|
||||
$this->assertNotNull($employeeRole);
|
||||
|
||||
$response = $this->actingAs($superAdmin)->delete(route('admin.roles.destroy', $employeeRole->id));
|
||||
$response->assertRedirect(route('admin.roles.index'));
|
||||
$response->assertSessionHas('error');
|
||||
$this->assertDatabaseHas('roles', ['name' => 'employee']);
|
||||
}
|
||||
|
||||
public function test_unauthorized_employee_cannot_impersonate_another_employee_trip(): void
|
||||
{
|
||||
$gate = Gate::create([
|
||||
'code' => 'GT-01',
|
||||
'name' => 'Main Gate',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$vehicle = \App\Models\Vehicle::create([
|
||||
'code' => 'LV-SEC-01',
|
||||
'category' => 'light_vehicle',
|
||||
'brand_type' => 'Toyota Hilux',
|
||||
'license_plate' => 'BH 1111 XX',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 1000,
|
||||
]);
|
||||
|
||||
// User A (Karyawan A)
|
||||
$userA = User::factory()->create([
|
||||
'username' => 'EMP-AAA',
|
||||
'name' => 'Karyawan A',
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$userA->assignRole('employee');
|
||||
$empA = $userA->getOrCreateEmployee();
|
||||
|
||||
// User B (Karyawan B yang sah sebagai driver)
|
||||
$userB = User::factory()->create([
|
||||
'username' => 'EMP-BBB',
|
||||
'name' => 'Karyawan B',
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$userB->assignRole('employee');
|
||||
$empB = $userB->getOrCreateEmployee();
|
||||
|
||||
// Karyawan A mencoba submit atas nama Karyawan B
|
||||
$response = $this->actingAs($userA)->post(route('vehicle.activity.store', ['code' => $vehicle->code]), [
|
||||
'driver_id' => $empB->id,
|
||||
'gate_id' => $gate->id,
|
||||
'direction' => 'out',
|
||||
'current_km' => 1010,
|
||||
'purpose' => 'Test Tampering',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasErrors('driver_id');
|
||||
$this->assertDatabaseMissing('vehicle_activities', [
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $empB->id,
|
||||
'current_km' => 1010,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_timesheet_concurrency_generator_avoids_duplicate_numbers(): void
|
||||
{
|
||||
$today = now();
|
||||
$dateStr = $today->format('Ymd');
|
||||
$expectedNo1 = "TS-US-{$dateStr}-0001";
|
||||
|
||||
$no1 = \App\Models\UnitSupportTimesheet::generateTimesheetNo($today);
|
||||
$this->assertEquals($expectedNo1, $no1);
|
||||
|
||||
// Simulasikan ada record yang sudah dibuat dengan nomor tersebut
|
||||
$vehicle = \App\Models\Vehicle::create([
|
||||
'code' => 'HE-CONC-01',
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Excavator PC200',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 500,
|
||||
]);
|
||||
|
||||
$emp = \App\Models\Employee::create([
|
||||
'nik' => 'OP-CONC-01',
|
||||
'name' => 'Operator Concurrency',
|
||||
'is_operator' => true,
|
||||
]);
|
||||
|
||||
\App\Models\UnitSupportTimesheet::create([
|
||||
'timesheet_no' => $expectedNo1,
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'operator_id' => $emp->id,
|
||||
'date' => $today->toDateString(),
|
||||
'shift' => 'Shift Siang',
|
||||
'meter_type' => 'HM',
|
||||
'start_meter' => 100,
|
||||
'end_meter' => 108,
|
||||
'operating_hours' => 8,
|
||||
'location' => 'Pit A',
|
||||
'activity_type' => 'Galian',
|
||||
'status' => 'Operation',
|
||||
]);
|
||||
|
||||
// Generator harus mendeteksi nomor 0001 sudah ada dan otomatis menghasilkan 0002
|
||||
$no2 = \App\Models\UnitSupportTimesheet::generateTimesheetNo($today);
|
||||
$this->assertEquals("TS-US-{$dateStr}-0002", $no2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,4 +310,36 @@ class TrashAndAutoDeleteTest extends TestCase
|
||||
'id' => $freshActivity->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_vehicle_photo_preserved_on_soft_delete_and_restored(): void
|
||||
{
|
||||
$vehicle = Vehicle::create([
|
||||
'code' => 'LV-PHOTO-01',
|
||||
'category' => 'light_vehicle',
|
||||
'brand_type' => 'Hilux',
|
||||
'license_plate' => 'BH 9999 AA',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 500,
|
||||
'photo_path' => 'vehicles/dummy_photo.jpg',
|
||||
]);
|
||||
|
||||
// Simulasikan penghapusan kendaraan
|
||||
$this->actingAs($this->superAdmin)
|
||||
->delete(route('qma.vehicles.destroy', $vehicle->id));
|
||||
|
||||
$this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]);
|
||||
|
||||
// Verifikasi photo_path masih tersimpan di record
|
||||
$trashed = Vehicle::onlyTrashed()->find($vehicle->id);
|
||||
$this->assertNotNull($trashed);
|
||||
$this->assertEquals('vehicles/dummy_photo.jpg', $trashed->photo_path);
|
||||
|
||||
// Pulihkan dari tong sampah
|
||||
$this->actingAs($this->superAdmin)
|
||||
->post(route('admin.trash.restore', ['category' => 'vehicles', 'id' => $vehicle->id]));
|
||||
|
||||
$restored = Vehicle::find($vehicle->id);
|
||||
$this->assertNotNull($restored);
|
||||
$this->assertEquals('vehicles/dummy_photo.jpg', $restored->photo_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user