Compare commits

...
38 Commits
Author SHA1 Message Date
Ray1111-aa f655c3af1e feat(admin): add clear activity logs button and artisan clean-test-logs command 2026-11-03 15:14:07 +07:00
Ray1111-aa 29f878e0e7 feat(hse): smart selective update on employee import without wiping existing fields 2026-11-03 14:28:11 +07:00
Ray1111-aa dc069fe0ec fix(hse): allow employee import and guard creation to restore soft-deleted users and employees without duplicate key collision 2026-11-03 14:13:45 +07:00
Ray1111-aa a55ead4c5b perf(backup): extend backup restore and conversion timeout to 1 hour (3600s) 2026-11-03 13:34:07 +07:00
Ray1111-aa 61332f948b fix(pg): allow editing guard badge_id with user sync and fix verification logs filter js error 2026-11-03 13:07:14 +07:00
Ray1111-aa c1be96c2ba fix(pg,auth): prevent deactivated security guards from logging in and accessing pg module 2026-11-03 12:03:16 +07:00
Ray1111-aa 6e5c6eeeb8 perf(backup,converter): optimize sql dump streaming, add direct server file conversion, and extend timeout to 30m 2026-11-03 10:11:58 +07:00
Ray1111-aa ff3ab616e0 fix(user,trash): fix 500 server error when deleting user with operational history and protect audit integrity 2026-11-03 09:14:53 +07:00
Ray1111-aa 5a4969b467 fix(qma,pg): filterable inputs for unit transfer & timesheet, fix unit edit division, and auto guard rejection 2026-11-02 16:45:09 +07:00
Ray1111-aa 2fe265da37 fix(hse): auto sync security guard personnel into employee simper master upon seeding and importing 2026-11-02 15:25:11 +07:00
Ray1111-aa 008e5f6b9d fix(hse): allow soft deleting employee without losing operational history, fix simper checklist badge overflow, and enforce valid future expiry date 2026-11-02 14:35:24 +07:00
Ray1111-aa 23377631b3 fix(qma): track excel location file and make sync command resilient when file missing 2026-11-02 13:35:33 +07:00
Ray1111-aa b8fa1771b9 feat: implement 3-level heavy equipment drilldown and transporter options in unit transfer 2026-11-02 12:00:21 +07:00
Ray1111-aa 8a94e98ed9 fix(p2h): limit pdf signatures to 2 parties (operator and admin qma) and fix overlapping text coordinates 2026-11-02 08:43:43 +07:00
Ray1111-aa 6e84e6106f docs(p2h): clarify general notes label as optional in p2h form 2026-11-02 08:35:02 +07:00
Ray1111-aa bc2215d98e feat(p2h): add comprehensive submit protection to verify all checklist items before form submission 2026-11-02 08:31:36 +07:00
Ray1111-aa a09071f5ed fix(hse): remove syntax error in javascript and restore tambah, ekspor, and impor button functionality 2026-11-02 08:22:31 +07:00
Ray1111-aa e2054dcb8a feat: resolve audit items (multi-simper hse dashboard & export, soft-delete conflict handling, p2h blank initial state, qma breakdown recovery, and exclude lv from transporter) 2026-11-01 23:18:17 +07:00
Ray1111-aa aec6c36344 feat: enhance HSE SIMPER renewal modal to read existing user simpers, provide clear dropdown selection, and support sukon 2026-11-01 22:37:06 +07:00
Ray1111-aa 96178971fd feat: timesheet auto hm, sync excel vehicle locations, heavy equipment grouped by type, 2-party bast signature, and compact role permission ui 2026-11-01 22:28:12 +07:00
Ray1111-aa b83a8fa843 feat: fix HSE simper 500 error, enhance PG rejection, P2H wizard, simper renewal, QMA table UI, and nginx upload timeouts 2026-11-01 21:26:22 +07:00
Ray1111-aa bc6213d864 feat(backup): add real-time upload progress bar and single-upload token optimization for converter and direct restore 2026-10-30 15:15:52 +07:00
Ray1111-aa 14298cfff3 build: update compiled production assets in public/build 2026-10-30 14:11:23 +07:00
Ray1111-aa a32e996780 feat(backup): add standalone in-portal .kmh converter to Excel, CSV, and SQL with zero storage retention 2026-10-30 10:29:04 +07:00
Ray1111-aa 721abb56c2 refactor(backup): remove internal reader to keep main application completely clean and decoupled 2026-10-30 10:01:54 +07:00
Ray1111-aa 93baeac001 refactor(backup): streamline kmh reader purely to upload model and remove server file inspect tab 2026-10-30 09:47:14 +07:00
Ray1111-aa 433f07b505 feat(backup): clean icons in kmh reader and add interactive table data rows preview 2026-10-30 09:41:30 +07:00
Ray1111-aa 2addb8ed4f fix(testing): enforce in-memory sqlite with force=true to protect local mysql database 2026-10-30 09:21:12 +07:00
Ray1111-aa 18e4e6471e feat(backup): add dedicated .kmh archive reader with zero-storage file inspection and CLI command 2026-10-30 09:00:28 +07:00
Ray1111-aa 39a5ee67ef feat(config): increase upload limits to 500MB in php.ini and nginx for large backup files 2026-10-29 15:04:02 +07:00
Ray1111-aa b0469611d7 fix(polling): resolve mixed-content HTTP blocking and cache prevention for real-time polling 2026-10-29 14:40:11 +07:00
Ray1111-aa f7b92a1c71 refactor(docker): clean up port 443 and optimize Nginx purely for port 80 Cloudflare Tunnel 2026-10-29 13:50:45 +07:00
Ray1111-aa 2ced848e3a feat(docker): enable port 443 HTTPS with SSL certificate for Cloudflare Full mode support 2026-10-29 13:23:00 +07:00
Ray1111-aa 6ee58817ce fix(security): configure trustProxies for Cloudflare reverse proxy HTTPS support 2026-10-29 11:07:44 +07:00
Ray1111-aa e3414b39af chore(schedule): remove automated backup from scheduler to save VPS disk space (manual backup mode) 2026-10-29 08:44:56 +07:00
Ray1111-aa 19e5418f9a feat(schedule): register hourly expire pending, daily trash prune, and daily auto backup in console scheduler 2026-10-29 08:34:46 +07:00
Ray1111-aa 6603b710d7 fix(docker): sync compiled frontend assets directly from git and optimize docker build 2026-10-28 16:13:08 +07:00
Ray1111-aa 40767d2117 fix(migration): use DB query builder instead of User model in sync_security_guards to avoid missing deleted_at column 2026-10-28 16:05:31 +07:00
91 changed files with 8798 additions and 1528 deletions
+2 -1
View File
@@ -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
View File
@@ -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.");
}
}
+142 -1
View File
@@ -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
) {}
/**
@@ -376,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());
}
}
@@ -409,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);
}
}
}
+20 -16
View File
@@ -73,24 +73,28 @@ class TrashController extends Controller
*/
public function forceDelete(string $category, int $id): RedirectResponse
{
$success = $this->trashService->forceDeleteItem($category, $id);
try {
$success = $this->trashService->forceDeleteItem($category, $id);
if (!$success) {
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
if (!$success) {
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
}
$catDefinitions = TrashService::getCategoryDefinitions();
$label = $catDefinitions[$category]['label'] ?? $category;
AdminActivityLog::record(
actionType: 'delete',
module: 'Tong Sampah',
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
targetType: $category,
targetId: $id
);
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
} catch (\Throwable $e) {
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
}
$catDefinitions = TrashService::getCategoryDefinitions();
$label = $catDefinitions[$category]['label'] ?? $category;
AdminActivityLog::record(
actionType: 'delete',
module: 'Tong Sampah',
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
targetType: $category,
targetId: $id
);
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
}
/**
+60 -27
View File
@@ -11,6 +11,7 @@ use App\Services\ImageCompressionService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
@@ -74,8 +75,8 @@ class UserController extends Controller
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:50', 'unique:users,username'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
'username' => ['required', 'string', 'max:50', Rule::unique('users', 'username')->whereNull('deleted_at')],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->whereNull('deleted_at')],
'password' => ['required', 'string', 'min:6'],
'role' => ['required', 'string', 'exists:roles,name'],
'gate_id' => ['nullable', 'exists:gates,id'],
@@ -102,15 +103,38 @@ class UserController extends Controller
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
}
$user = User::create([
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
'role' => $validated['role'], // Simpan ke kolom legacy untuk backwards-compat
'gate_id' => $validated['gate_id'] ?? null,
'photo_path' => $photoPath,
]);
$user = User::withTrashed()
->where('username', $validated['username'])
->orWhere('email', $validated['email'])
->first();
if ($user) {
if ($user->trashed()) {
$user->restore();
}
$userData = [
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
'role' => $validated['role'],
'gate_id' => $validated['gate_id'] ?? null,
];
if ($photoPath) {
$userData['photo_path'] = $photoPath;
}
$user->update($userData);
} else {
$user = User::create([
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
'role' => $validated['role'], // Simpan ke kolom legacy untuk backwards-compat
'gate_id' => $validated['gate_id'] ?? null,
'photo_path' => $photoPath,
]);
}
// Assign Spatie Role
$user->assignRole($validated['role']);
@@ -141,7 +165,7 @@ class UserController extends Controller
$defaultDivision = ($isGateOfficer || $isPgAdmin) ? 'Private Guard' : '-';
$defaultPosition = $isGateOfficer ? 'Anggota' : ($isPgAdmin ? 'Admin PG' : ($isEmployeeRole ? 'Driver Operasional' : '-'));
$emp = Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
$emp = Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
$empData = [
'user_id' => $user->id,
'nik' => $user->username,
@@ -154,6 +178,9 @@ class UserController extends Controller
'photo_path' => $photoPath ?: $emp?->photo_path,
];
if ($emp) {
if ($emp->trashed()) {
$emp->restore();
}
$emp->update($empData);
} else {
Employee::create($empData);
@@ -393,23 +420,29 @@ class UserController extends Controller
$userRole = $user->role ?? '';
$userId = $user->id;
$user->syncRoles([]);
$user->delete();
try {
DB::transaction(function () use ($user) {
$user->delete();
});
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleTitle = $this->getFriendlyRoleName($userRole);
AdminActivityLog::record(
actionType: 'delete',
module: 'Manajemen Pengguna',
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
targetType: 'User',
targetId: $userId,
targetName: $name,
oldValues: $deletedSnapshot
);
// Rekam ke Log Riwayat Aktivitas Super Admin
$roleTitle = $this->getFriendlyRoleName($userRole);
AdminActivityLog::record(
actionType: 'delete',
module: 'Manajemen Pengguna',
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
targetType: 'User',
targetId: $userId,
targetName: $name,
oldValues: $deletedSnapshot
);
return redirect()->route('admin.users.index')
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
return redirect()->route('admin.users.index')
->with('success', "Akun pengguna [{$name}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
} catch (\Throwable $e) {
return redirect()->route('admin.users.index')
->with('error', 'Gagal menghapus pengguna: ' . $e->getMessage());
}
}
/**
@@ -47,6 +47,18 @@ class LoginController extends Controller
/** @var \App\Models\User $user */
$user = Auth::user();
// Proteksi: Cek apakah akun Petugas Satpam berstatus Nonaktif
$guard = $user->securityGuard ?: \App\Models\SecurityGuard::where('user_id', $user->id)->first();
if ($guard && ! $guard->is_active && ! $user->isSuperAdmin()) {
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return back()->withErrors([
'username' => 'Akun Petugas Satpam Anda berstatus Nonaktif. Silakan hubungi Administrator Pos Gerbang (PG) untuk mengaktifkan kembali.',
])->onlyInput('username');
}
if ($request->session()->has('url.intended')) {
return redirect()->intended()
->with('success', "Selamat datang kembali, {$user->name}!");
@@ -204,7 +204,7 @@ 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');
}
/**
+263 -73
View File
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Hse;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use App\Models\Employee;
use App\Models\EmployeeSimper;
use App\Models\SimperType;
@@ -17,6 +18,7 @@ use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
class EmployeeController extends Controller
@@ -42,9 +44,10 @@ class EmployeeController extends Controller
->take(5)
->get();
// 2. Monitoring Status & Masa Berlaku SIMPER (Prioritas Kedaluwarsa & Segera Habis)
// 2. Monitoring Status & Masa Berlaku SIMPER (Prioritas Kedaluwarsa & Segera Habis dengan Dukungan Multi-SIMPER)
$today = now()->toDateString();
$simperLogs = Employee::where('is_operator', true)
->with(['simpers.simperType'])
->orderByRaw("CASE
WHEN simper_expired_at IS NULL THEN 1
WHEN simper_expired_at < ? THEN 0
@@ -209,6 +212,7 @@ class EmployeeController extends Controller
'Unit Kerja' => 20,
'Divisi' => 20,
'Status Driver' => 16,
'Jenis Izin SIMPER' => 24,
'Masa Berlaku SIMPER' => 22,
'Status SIMPER' => 24,
];
@@ -221,6 +225,13 @@ class EmployeeController extends Controller
$isDriver = $emp->is_operator;
$expDate = $emp->simper_expired_at ? $emp->simper_expired_at->format('d/m/Y') : '-';
// Ambil rincian seluruh kode SIMPER yang dipegang
$simperList = $emp->simpers->map(function ($s) {
$code = $s->simperType?->code ?: 'SIMPER';
return str_replace('SIMPER-', '', $code);
})->filter()->unique()->values();
$simperTypesText = $simperList->isNotEmpty() ? $simperList->join(', ') : ($isDriver ? 'LV (Default)' : '-');
if (! $isDriver) {
$statusText = 'Bukan Driver';
} elseif (! $emp->simper_expired_at) {
@@ -242,6 +253,7 @@ class EmployeeController extends Controller
$emp->unit_kerja ?: '-',
$emp->division ?: '-',
$isDriver ? 'Driver' : 'Bukan Driver',
$simperTypesText,
$expDate,
$statusText,
];
@@ -256,6 +268,7 @@ class EmployeeController extends Controller
'left', // Unit Kerja
'left', // Divisi
'center', // Status Driver
'center', // Jenis Izin SIMPER
'center', // Masa Berlaku
'center', // Status SIMPER
];
@@ -496,48 +509,94 @@ class EmployeeController extends Controller
continue;
}
$unitKerja = trim((string) ($colMap['unit_kerja'] !== null ? ($row[$colMap['unit_kerja']] ?? 'Umum') : 'Umum'));
$division = trim((string) ($colMap['division'] !== null ? ($row[$colMap['division']] ?? '-') : '-'));
$position = trim((string) ($colMap['position'] !== null ? ($row[$colMap['position']] ?? '-') : '-'));
$employeeType = trim((string) ($colMap['employee_type'] !== null ? ($row[$colMap['employee_type']] ?? 'Karyawan') : 'Karyawan')) ?: 'Karyawan';
$rawUnitKerja = $colMap['unit_kerja'] !== null ? trim((string) ($row[$colMap['unit_kerja']] ?? '')) : '';
$rawDivision = $colMap['division'] !== null ? trim((string) ($row[$colMap['division']] ?? '')) : '';
$rawPosition = $colMap['position'] !== null ? trim((string) ($row[$colMap['position']] ?? '')) : '';
$rawEmployeeType = $colMap['employee_type'] !== null ? trim((string) ($row[$colMap['employee_type']] ?? '')) : '';
$rawOperator = $colMap['is_operator'] !== null ? trim((string) ($row[$colMap['is_operator']] ?? '')) : '';
$rawSimper = $colMap['simper_expired_at'] !== null ? trim((string) ($row[$colMap['simper_expired_at']] ?? '')) : '';
$unitKerja = $rawUnitKerja ?: 'Umum';
$division = $rawDivision ?: '-';
$position = $rawPosition ?: '-';
$employeeType = $rawEmployeeType ?: 'Karyawan';
// Deteksi status driver (jika kolom ada dan berisi ya/driver)
$operatorRaw = $colMap['is_operator'] !== null ? strtolower(trim((string) ($row[$colMap['is_operator']] ?? ''))) : '';
$operatorRaw = strtolower($rawOperator);
$isOperator = in_array($operatorRaw, ['ya', 'yes', '1', 'true', 'driver', 'operator', 'y']);
// Deteksi tanggal SIMPER
$simperRaw = $colMap['simper_expired_at'] !== null ? trim((string) ($row[$colMap['simper_expired_at']] ?? '')) : '';
$simperExpiredAt = $isOperator ? SimpleXlsxImporter::normalizeDate($simperRaw) : null;
$simperExpiredAt = $isOperator ? SimpleXlsxImporter::normalizeDate($rawSimper) : null;
// 1. Sinkronisasi Akun User untuk login karyawan
// 1. Sinkronisasi Akun User untuk login karyawan (gunakan withTrashed agar tidak bentrok dengan data di Tong Sampah)
$cleanEmail = strtolower(str_replace(['-', ' '], '', $nik)) . '@kmh.co.id';
$user = User::firstOrCreate(
['username' => $nik],
[
$user = User::withTrashed()->where('username', $nik)->first();
if ($user) {
if ($user->trashed()) {
$user->restore();
}
$user->update([
'name' => $name,
'role' => $user->role ?: 'employee',
]);
} else {
if (User::withTrashed()->where('email', $cleanEmail)->exists()) {
$cleanEmail = strtolower(str_replace(['-', ' '], '', $nik)) . '.' . uniqid() . '@kmh.co.id';
}
$user = User::create([
'username' => $nik,
'name' => $name,
'email' => $cleanEmail,
'password' => Hash::make(config('auth.default_employee_password', '123456')),
'role' => 'employee',
]
);
]);
}
if (!$user->hasRole('employee')) {
$user->assignRole('employee');
}
// 2. Simpan atau perbarui data master Employee
$isExisting = Employee::where('nik', $nik)->first();
// 2. Simpan atau perbarui data master Employee (gunakan withTrashed agar tidak duplikat dengan NIK di Tong Sampah)
$isExisting = Employee::withTrashed()->where('nik', $nik)->first();
if ($isExisting) {
$isExisting->update([
if ($isExisting->trashed()) {
$isExisting->restore();
}
$updateData = [
'name' => $name,
'employee_type' => $employeeType,
'unit_kerja' => $unitKerja ?: 'Umum',
'division' => $division ?: '-',
'position' => $position ?: '-',
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'user_id' => $user->id,
]);
];
// Perbarui kolom secara selektif jika pada berkas Excel terisi data baru
if ($rawEmployeeType !== '') {
$updateData['employee_type'] = $employeeType;
}
if ($rawUnitKerja !== '') {
$updateData['unit_kerja'] = $unitKerja;
} elseif (empty($isExisting->unit_kerja) || $isExisting->unit_kerja === '-') {
$updateData['unit_kerja'] = 'Umum';
}
if ($rawDivision !== '') {
$updateData['division'] = $division;
}
if ($rawPosition !== '') {
$updateData['position'] = $position;
}
if ($rawOperator !== '') {
$updateData['is_operator'] = $isOperator;
if ($rawSimper !== '' && $isOperator) {
$updateData['simper_expired_at'] = $simperExpiredAt;
}
} elseif ($rawSimper !== '' && $isExisting->is_operator) {
$updateData['simper_expired_at'] = SimpleXlsxImporter::normalizeDate($rawSimper);
}
$isExisting->update($updateData);
$updatedCount++;
} else {
Employee::create([
@@ -580,7 +639,7 @@ class EmployeeController extends Controller
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'nik' => ['required', 'string', 'max:50', 'unique:employees,nik'],
'nik' => ['required', 'string', 'max:50', Rule::unique('employees', 'nik')->whereNull('deleted_at')],
'name' => ['required', 'string', 'max:100'],
'unit_kerja' => ['required', 'string'],
'division' => ['required', 'string'],
@@ -588,6 +647,10 @@ class EmployeeController extends Controller
'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
'simper_assignments' => ['nullable', 'array'],
'simper_assignments.*.expired_at' => ['nullable', 'date'],
'simper_assignments.*.simper_number' => ['nullable', 'string', 'max:100'],
'renew_simper_type_id' => ['nullable', 'string'],
], [
'nik.required' => 'NIK wajib diisi.',
'nik.unique' => 'NIK sudah terdaftar dalam sistem.',
@@ -601,6 +664,23 @@ class EmployeeController extends Controller
$isOperator = (bool) $validated['is_operator'];
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null;
// Validasi kustom penugasan SIMPER ketika driver aktif
if ($isOperator && is_array($request->input('simper_assignments'))) {
$today = Carbon::today()->toDateString();
foreach ($request->input('simper_assignments') as $typeId => $data) {
if (!empty($data['enabled'])) {
$st = SimperType::find($typeId);
$typeName = $st ? $st->name : "Tipe #{$typeId}";
if (empty($data['expired_at'])) {
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' wajib diisi ketika dicentang.");
}
if ($data['expired_at'] < $today) {
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' tidak boleh tanggal lampau (minimal hari ini).");
}
}
}
}
$employeeType = $request->input('employee_type');
if ($employeeType === '__CUSTOM__' && $request->filled('custom_employee_type')) {
$employeeType = trim($request->input('custom_employee_type'));
@@ -609,15 +689,24 @@ class EmployeeController extends Controller
$employeeType = 'Karyawan';
}
$user = User::firstOrCreate(
['username' => $validated['nik']],
[
$user = User::withTrashed()->where('username', $validated['nik'])->first();
if ($user) {
if ($user->trashed()) {
$user->restore();
}
$user->update([
'name' => $validated['name'],
'role' => $user->role ?: 'employee',
]);
} else {
$user = User::create([
'username' => $validated['nik'],
'name' => $validated['name'],
'email' => strtolower(str_replace(['-', ' '], '', $validated['nik'])) . '@kmh.co.id',
'password' => Hash::make(config('auth.default_employee_password', '123456')),
'role' => 'employee',
]
);
]);
}
if (!$user->hasRole('employee')) {
$user->assignRole('employee');
@@ -629,18 +718,36 @@ class EmployeeController extends Controller
$user->update(['photo_path' => $photoPath]);
}
$employee = Employee::create([
'nik' => $validated['nik'],
'name' => $validated['name'],
'employee_type' => $employeeType,
'unit_kerja' => $validated['unit_kerja'],
'division' => $validated['division'],
'position' => $validated['position'],
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath,
'user_id' => $user->id,
]);
$employee = Employee::withTrashed()->where('nik', $validated['nik'])->first();
if ($employee) {
if ($employee->trashed()) {
$employee->restore();
}
$employee->update([
'name' => $validated['name'],
'employee_type' => $employeeType,
'unit_kerja' => $validated['unit_kerja'],
'division' => $validated['division'],
'position' => $validated['position'],
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath ?? $employee->photo_path,
'user_id' => $user->id,
]);
} else {
$employee = Employee::create([
'nik' => $validated['nik'],
'name' => $validated['name'],
'employee_type' => $employeeType,
'unit_kerja' => $validated['unit_kerja'],
'division' => $validated['division'],
'position' => $validated['position'],
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath,
'user_id' => $user->id,
]);
}
// Sinkronisasi Multi-SIMPER Personil
$this->syncEmployeeSimpers($employee, $request, $isOperator, $simperExpiredAt);
@@ -696,6 +803,10 @@ class EmployeeController extends Controller
'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
'simper_assignments' => ['nullable', 'array'],
'simper_assignments.*.expired_at' => ['nullable', 'date'],
'simper_assignments.*.simper_number' => ['nullable', 'string', 'max:100'],
'renew_simper_type_id' => ['nullable', 'string'],
], [
'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.',
'name.required' => 'Nama lengkap wajib diisi.',
@@ -705,6 +816,28 @@ class EmployeeController extends Controller
$isOperator = (bool) $validated['is_operator'];
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? $employee->simper_expired_at) : null;
// Validasi kustom penugasan SIMPER ketika driver aktif
if ($isOperator && is_array($request->input('simper_assignments'))) {
$today = Carbon::today()->toDateString();
foreach ($request->input('simper_assignments') as $typeId => $data) {
if (!empty($data['enabled'])) {
$st = SimperType::find($typeId);
$typeName = $st ? $st->name : "Tipe #{$typeId}";
if (empty($data['expired_at'])) {
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' wajib diisi ketika dicentang.");
}
if ($data['expired_at'] < $today) {
// Cek apakah tanggal ini memang tanggal lama yang belum diubah oleh admin
$existingSimper = $employee->simpers->firstWhere('simper_type_id', (int) $typeId);
$isOldUnchanged = $existingSimper && $existingSimper->expired_at?->format('Y-m-d') === $data['expired_at'];
if (!$isOldUnchanged) {
return back()->withInput()->with('error', "Masa berlaku untuk jenis SIMPER '{$typeName}' tidak boleh tanggal lampau (minimal hari ini: {$today}).");
}
}
}
}
}
$employeeType = $request->input('employee_type');
if ($employeeType === '__CUSTOM__' && $request->filled('custom_employee_type')) {
$employeeType = trim($request->input('custom_employee_type'));
@@ -755,26 +888,12 @@ class EmployeeController extends Controller
}
/**
* Hapus data personil / karyawan beserta izin SIMPER dan akun login terkait.
* Hapus data personil / karyawan (Soft Delete masuk ke Tong Sampah).
* Seluruh riwayat transaksi (Timesheet, Gate, P2H) tetap aman dan terhubung.
*/
public function destroy(int $id): RedirectResponse
{
$employee = Employee::with(['user', 'activities', 'p2hRecords', 'supportTimesheets'])->findOrFail($id);
// 1. Proteksi integritas relasi: pastikan tidak ada logbook perjalanan kendaraan
if ($employee->activities()->exists()) {
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah tercatat dalam riwayat logbook operasional kendaraan.");
}
// 2. Proteksi integritas relasi: pastikan tidak ada data inspeksi P2H
if ($employee->p2hRecords()->exists()) {
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah memiliki formulir riwayat inspeksi P2H.");
}
// 3. Proteksi integritas relasi: pastikan tidak ada data timesheet unit support
if ($employee->supportTimesheets()->exists()) {
return back()->with('error', "Aksi Ditolak: Karyawan '{$employee->name}' ({$employee->nik}) tidak dapat dihapus karena telah tercatat dalam riwayat timesheet unit support.");
}
$employee = Employee::with(['user'])->findOrFail($id);
$empName = $employee->name;
$empNik = $employee->nik;
@@ -786,22 +905,24 @@ class EmployeeController extends Controller
// Berkas foto tidak dihapus saat soft delete agar foto tetap ada jika dipulihkan dari tong sampah.
// Berkas baru dihapus permanen ketika dilakukan 'Hapus Permanen' (force delete) di TrashService.
// Hapus data karyawan (relasi employee_simpers otomatis cascade terhapus)
// Hapus data karyawan (soft delete - dipindahkan ke Tong Sampah)
$employee->delete();
// Hapus akun login User terkait jika perannya murni hanya karyawan (bukan admin)
// Nonaktifkan / soft delete akun login User terkait jika perannya murni hanya karyawan (bukan admin)
if ($user && $user->role === 'employee' && ! $user->hasAnyRole(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer'])) {
$user->syncRoles([]);
$user->delete();
}
});
$message = "Data personil '{$empName}' ({$empNik}) berhasil dihapus dan dipindahkan ke Tong Sampah. Seluruh riwayat operasional masa lalu tetap tersimpan utuh.";
// Jika request berasal dari halaman edit terpisah, arahkan kembali ke index
if (url()->previous() === route('hse.employees.edit', $id)) {
return redirect()->route('hse.employees.index')->with('success', "Data karyawan '{$empName}' ({$empNik}) berhasil dihapus dari sistem.");
return redirect()->route('hse.employees.index')->with('success', $message);
}
return back()->with('success', "Data karyawan '{$empName}' ({$empNik}) berhasil dihapus dari sistem.");
return back()->with('success', $message);
}
/**
@@ -810,7 +931,8 @@ class EmployeeController extends Controller
private function syncEmployeeSimpers(Employee $employee, Request $request, bool $isOperator, ?string $fallbackDate): void
{
if (! $isOperator) {
$employee->simpers()->delete();
$employee->simpers()->forceDelete();
$employee->update(['simper_expired_at' => null]);
return;
}
@@ -821,20 +943,30 @@ class EmployeeController extends Controller
$maxExpiredAt = null;
foreach ($simperAssignments as $typeId => $data) {
$isEnabled = ! empty($data['enabled']) || (! isset($data['enabled']) && ! empty($data['expired_at']));
// Hanya aktif jika dicentang eksplisit, ATAU fallback jika form tidak menyertakan checkbox enabled namun memiliki tanggal
$isEnabled = ! empty($data['enabled']);
if (! $isEnabled && ! isset($data['enabled']) && ! empty($data['expired_at'])) {
$isEnabled = true;
}
if ($isEnabled && ! empty($data['expired_at'])) {
$expDate = $data['expired_at'];
$simperNum = ! empty($data['simper_number']) ? trim($data['simper_number']) : ('SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT));
EmployeeSimper::updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $typeId],
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => (int) $typeId],
[
'simper_number' => $simperNum,
'expired_at' => $expDate,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
$activeTypeIds[] = (int) $typeId;
if (! $maxExpiredAt || $expDate > $maxExpiredAt) {
@@ -843,26 +975,84 @@ class EmployeeController extends Controller
}
}
// Hapus jenis SIMPER yang sudah tidak dicentang
// Hapus jenis SIMPER yang sudah tidak dicentang (Gunakan forceDelete agar tidak memicu benturan Unique Index)
EmployeeSimper::where('employee_id', $employee->id)
->whereNotIn('simper_type_id', $activeTypeIds)
->delete();
->forceDelete();
if ($maxExpiredAt && $employee->simper_expired_at != $maxExpiredAt) {
$employee->update(['simper_expired_at' => $maxExpiredAt]);
$employee->update(['simper_expired_at' => $maxExpiredAt]);
} elseif ($request->filled('renew_simper_type_id')) {
// Khusus alur Perpanjang SIMPER via Modal (#renewModal)
$renewTypeId = $request->input('renew_simper_type_id');
$newExpiry = $request->input('simper_expired_at');
if ($newExpiry) {
if ($renewTypeId === 'all') {
// Perpanjang semua SIMPER yang aktif dimiliki oleh karyawan
$existingSimpers = $employee->simpers;
if ($existingSimpers->isNotEmpty()) {
foreach ($existingSimpers as $s) {
$s->update([
'expired_at' => $newExpiry,
'status' => 'active',
]);
}
} else {
// Jika belum ada SIMPER sama sekali, buatkan SIMPER-LV default
$lvTypeId = SimperType::where('code', 'SIMPER-LV')->value('id');
if ($lvTypeId) {
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $lvTypeId],
[
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $newExpiry,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
}
}
} else {
// Perpanjang jenis SIMPER spesifik yang dipilih pada dropdown
$targetTypeId = (int) $renewTypeId;
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $targetTypeId],
[
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $newExpiry,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
}
// Sinkronkan simper_expired_at master karyawan dengan tanggal terlama di antara simper aktif
$latestMax = $employee->simpers()->max('expired_at');
$employee->update(['simper_expired_at' => $latestMax]);
}
} elseif ($fallbackDate) {
// Fallback untuk form sederhana / pengujian yang mengirimkan 1 tanggal simper_expired_at
// Fallback untuk pengujian sederhana yang mengirimkan 1 tanggal simper_expired_at
$lvTypeId = SimperType::where('code', 'SIMPER-LV')->value('id');
if ($lvTypeId) {
EmployeeSimper::updateOrCreate(
$simper = EmployeeSimper::withTrashed()->updateOrCreate(
['employee_id' => $employee->id, 'simper_type_id' => $lvTypeId],
[
'simper_number' => 'SMP-' . str_pad($employee->id, 4, '0', STR_PAD_LEFT),
'expired_at' => $fallbackDate,
'status' => 'active',
'deleted_at' => null,
]
);
if ($simper->trashed()) {
$simper->restore();
}
$employee->update(['simper_expired_at' => $fallbackDate]);
}
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Pg;
use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Models\Gate;
use App\Models\SecurityGuard;
use App\Models\VehicleActivity;
@@ -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,19 +160,23 @@ class GateInspectionController extends Controller
public function approve(Request $request, int $id): RedirectResponse
{
$user = $request->user();
$currentGuard = $user ? $user->securityGuard : null;
$guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null);
$guard = $user ? ($user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first() ?: SecurityGuard::where('name', $user->name)->first() ?: SecurityGuard::where('badge_id', $user->username)->first()) : null;
if (!$guardId) {
$request->validate([
'security_guard_id' => ['required', 'exists:security_guards,id'],
], [
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam yang melakukan pemeriksaan fisik.',
'security_guard_id.exists' => 'Petugas Satpam yang dipilih tidak valid dalam sistem.',
]);
$guardId = $request->input('security_guard_id');
if (!$guard && $user) {
$guard = SecurityGuard::firstOrCreate(
['user_id' => $user->id],
[
'badge_id' => $user->username ?: ('PG-' . str_pad($user->id, 3, '0', STR_PAD_LEFT)),
'name' => $user->name,
'team' => 1,
'gate_id' => session('active_gate_id') ?: Gate::first()?->id,
'is_active' => true,
]
);
}
$guardId = $guard?->id ?: ($request->input('security_guard_id') ?: SecurityGuard::value('id'));
$activity = VehicleActivity::with(['vehicle', 'gate'])->findOrFail($id);
if ($activity->validation_status !== 'pending') {
@@ -179,6 +184,10 @@ class GateInspectionController extends Controller
}
$guard = SecurityGuard::find($guardId);
if ($guard && ! $guard->is_active && ! ($user && $user->isSuperAdmin())) {
return back()->with('error', 'Aksi Ditolak: Petugas Satpam berstatus Nonaktif tidak diizinkan memvalidasi aktivitas pos gerbang.');
}
$guardName = $guard?->name ?? ($user?->name ?? 'Petugas Pos Gerbang');
DB::transaction(function () use ($guardId, $guardName, $activity, $user) {
@@ -237,24 +246,34 @@ class GateInspectionController extends Controller
public function reject(Request $request, int $id): RedirectResponse
{
$user = $request->user();
$currentGuard = $user ? $user->securityGuard : null;
$guardId = $request->input('security_guard_id') ?? ($currentGuard ? $currentGuard->id : null);
$guard = $user ? ($user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first() ?: SecurityGuard::where('name', $user->name)->first() ?: SecurityGuard::where('badge_id', $user->username)->first()) : null;
if (!$guardId) {
$request->validate([
'security_guard_id' => ['required', 'exists:security_guards,id'],
], [
'security_guard_id.required' => 'Silakan pilih nama petugas Satpam.',
]);
$guardId = $request->input('security_guard_id');
if (!$guard && $user) {
$guard = SecurityGuard::firstOrCreate(
['user_id' => $user->id],
[
'badge_id' => $user->username ?: ('PG-' . str_pad($user->id, 3, '0', STR_PAD_LEFT)),
'name' => $user->name,
'team' => 1,
'gate_id' => session('active_gate_id') ?: Gate::first()?->id,
'is_active' => true,
]
);
}
$guardId = $guard?->id ?: ($request->input('security_guard_id') ?: SecurityGuard::value('id'));
$request->validate([
'rejection_note' => ['required', 'string', 'max:500'],
], [
'rejection_note.required' => 'Alasan penolakan wajib diisi.',
]);
$guard = SecurityGuard::find($guardId);
if ($guard && ! $guard->is_active && ! ($user && $user->isSuperAdmin())) {
return back()->with('error', 'Aksi Ditolak: Petugas Satpam berstatus Nonaktif tidak diizinkan memvalidasi aktivitas pos gerbang.');
}
$activity = VehicleActivity::with('vehicle')->findOrFail($id);
if ($activity->validation_status !== 'pending') {
@@ -268,6 +287,15 @@ class GateInspectionController extends Controller
'validated_at' => Carbon::now(),
]);
return back()->with('success', "Aktivitas kendaraan {$activity->vehicle->code} telah ditolak.");
AdminActivityLog::record(
'reject',
'pos_gerbang',
"Penolakan perlintasan gerbang untuk kendaraan {$activity->vehicle?->code} (Driver: {$activity->driver?->name}). Alasan: {$activity->rejection_note}",
'vehicle_activity',
$activity->id,
$activity->transaction_no
);
return back()->with('success', "Aktivitas perlintasan kendaraan {$activity->vehicle->code} telah ditolak.");
}
}
@@ -13,6 +13,7 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;
@@ -258,9 +259,23 @@ class SecurityGuardController extends Controller
]);
// 3. Otomatis buat / sinkronkan profil Employee untuk Satpam (Divisi: Private Guard, Jabatan: Anggota)
Employee::firstOrCreate(
['nik' => $badgeId],
[
$guardEmp = Employee::withTrashed()->where('nik', $badgeId)->first();
if ($guardEmp) {
if ($guardEmp->trashed()) {
$guardEmp->restore();
}
$guardEmp->update([
'user_id' => $user->id,
'name' => $request->input('name'),
'employee_type' => 'Karyawan',
'unit_kerja' => $guardEmp->unit_kerja ?: 'Private Guard',
'division' => ($guardEmp->division && $guardEmp->division !== '-') ? $guardEmp->division : 'Private Guard',
'position' => ($guardEmp->position && $guardEmp->position !== '-') ? $guardEmp->position : 'Anggota',
'is_operator' => false,
]);
} else {
Employee::create([
'nik' => $badgeId,
'user_id' => $user->id,
'name' => $request->input('name'),
'employee_type' => 'Karyawan',
@@ -268,35 +283,52 @@ class SecurityGuardController extends Controller
'division' => 'Private Guard',
'position' => 'Anggota',
'is_operator' => false,
]
);
]);
}
});
return back()->with('success', "Petugas Satpam {$request->input('name')} (ID: {$request->input('badge_id')}) berhasil didaftarkan.");
}
/**
* Perbarui data Satpam (Nama, Regu, Penempatan Pos, dan Password opsional).
* Perbarui data Satpam (ID Satpam, Nama, Regu, Penempatan Pos, dan Password opsional).
*/
public function update(Request $request, int $id): RedirectResponse
{
$guard = SecurityGuard::with('user')->findOrFail($id);
$newBadgeId = strtoupper(trim((string) $request->input('badge_id')));
$request->merge(['badge_id' => $newBadgeId]);
$emp = Employee::where('user_id', $guard->user_id)->orWhere('nik', $guard->badge_id)->first();
$request->validate([
'badge_id' => [
'required',
'string',
'max:50',
Rule::unique('security_guards', 'badge_id')->ignore($guard->id),
Rule::unique('users', 'username')->ignore($guard->user_id),
Rule::unique('employees', 'nik')->ignore($emp?->id),
],
'name' => ['required', 'string', 'max:100'],
'team' => ['required', 'integer', 'in:1,2,3'],
'gate_id' => ['nullable', 'exists:gates,id'],
'password' => ['nullable', 'string', 'min:4'],
], [
'badge_id.required' => 'ID Satpam wajib diisi.',
'badge_id.unique' => 'ID Satpam / NIK ini sudah digunakan oleh petugas/karyawan lain.',
'name.required' => 'Nama lengkap Satpam wajib diisi.',
'team.required' => 'Silakan pilih Regu Satpam (1, 2, atau 3).',
'password.min' => 'Password minimal terdiri dari 4 karakter.',
]);
DB::transaction(function () use ($request, $guard) {
DB::transaction(function () use ($request, $guard, $newBadgeId, $emp) {
$oldBadgeId = $guard->badge_id;
$gateId = $request->has('gate_id') ? ($request->input('gate_id') ?: null) : $guard->gate_id;
$guard->update([
'badge_id' => $newBadgeId,
'name' => $request->input('name'),
'team' => (int) $request->input('team'),
'gate_id' => $gateId,
@@ -305,9 +337,14 @@ class SecurityGuardController extends Controller
if ($guard->user) {
$userData = [
'name' => $request->input('name'),
'username' => $newBadgeId,
'gate_id' => $gateId,
];
if ($guard->user->email === strtolower((string) $oldBadgeId) . '@kmh.co.id') {
$userData['email'] = strtolower($newBadgeId) . '@kmh.co.id';
}
if ($request->filled('password')) {
$userData['password'] = Hash::make($request->input('password'));
}
@@ -316,9 +353,9 @@ class SecurityGuardController extends Controller
}
// Sinkronkan nama dan profil Employee Satpam
$emp = Employee::where('user_id', $guard->user_id)->orWhere('nik', $guard->badge_id)->first();
if ($emp) {
$emp->update([
'nik' => $newBadgeId,
'name' => $guard->name,
'unit_kerja' => $emp->unit_kerja ?: 'Private Guard',
'division' => ($emp->division && $emp->division !== '-') ? $emp->division : 'Private Guard',
@@ -327,7 +364,7 @@ class SecurityGuardController extends Controller
}
});
return back()->with('success', "Data petugas Satpam {$guard->name} berhasil diperbarui.");
return back()->with('success', "Data petugas Satpam {$guard->name} ({$newBadgeId}) berhasil diperbarui.");
}
/**
@@ -735,8 +735,11 @@ class P2hInspectionController extends Controller
]);
// Jika unit dinyatakan aman dan sebelumnya breakdown karena review, status unit disetujui operasi
if (!$record->hasDefects() && $record->vehicle->status === 'Breakdown') {
$record->vehicle->update(['status' => 'Operation']);
if (!$record->hasDefects() && $record->vehicle && $record->vehicle->status === 'Breakdown') {
$record->vehicle->update([
'status' => 'Operation',
'location_note' => "Status dipulihkan ke Operation pasca persetujuan P2H {$record->transaction_no}",
]);
}
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} berhasil DISETUJUI.");
@@ -134,15 +134,24 @@ class SupportTimesheetController extends Controller
$timesheets = $query->paginate($perPage)->withQueryString();
// KPI Ringkasan Data Terfilter
$statsQuery = clone $this->getFilteredQuery($request);
$totalEntries = (clone $statsQuery)->count();
$totalOperatingHours = (clone $statsQuery)->sum('operating_hours');
$totalFuelLiters = (clone $statsQuery)->sum('fuel_liters');
$activeUnitsCount = (clone $statsQuery)->distinct('vehicle_id')->count('vehicle_id');
$breakdownCount = (clone $statsQuery)->where('status', 'Breakdown')->count();
$statsItems = (clone $this->getFilteredQuery($request))->get();
$totalEntries = $statsItems->count();
$totalOperatingHours = 0.0;
foreach ($statsItems as $item) {
$totalOperatingHours += (float) ($item->effective_operating_hours ?? 0);
}
$totalFuelLiters = $statsItems->sum('fuel_liters');
$activeUnitsCount = $statsItems->pluck('vehicle_id')->unique()->count();
$breakdownCount = $statsItems->where('status', 'Breakdown')->count();
// Data Master untuk Form & Filter
// Data Master untuk Form & Filter (Alat Berat / Heavy Equipment - Bebas dari Unit LV)
$unitSupports = Vehicle::unitSupports()
->where('category', '!=', 'light_vehicle')
->where(function (Builder $q) {
$q->where('code', 'not like', 'LV %')
->where('code', 'not like', 'LV-%')
->where('code', 'not like', 'LV_%');
})
->where(function (Builder $q) {
$q->whereNotNull('parent_id')
->orWhereDoesntHave('units');
@@ -168,8 +177,37 @@ class SupportTimesheetController extends Controller
}
$shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions();
// Ambil preset + aktivitas yang pernah diisi secara dinamis di database
$dbActivities = UnitSupportTimesheet::whereNotNull('activity_type')
->where('activity_type', '!=', '')
->distinct()
->pluck('activity_type')
->all();
$activityTypes = collect(self::PRESET_ACTIVITIES)
->merge($dbActivities)
->map(fn($a) => trim($a))
->filter()
->unique()
->values()
->all();
// Ambil seluruh saran lokasi dari gerbang, kendaraan, riwayat, dan timesheet
$dbTimesheetLocs = UnitSupportTimesheet::whereNotNull('location')
->where('location', '!=', '')
->distinct()
->pluck('location')
->all();
$locationSuggestions = collect(UnitManagementController::getAllLocationSuggestions())
->merge($dbTimesheetLocs)
->map(fn($l) => trim($l))
->filter()
->unique()
->sort()
->values()
->all();
$unitLocations = $unitSupports->groupBy(function ($u) {
return trim($u->location) ?: 'Site Kerinci';
@@ -282,7 +320,26 @@ class SupportTimesheetController extends Controller
$endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null
? (float) $validated['end_meter']
: null;
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
if ($endMeter === null) {
$nextEntry = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where(function ($q) use ($validated, $startMeter) {
$q->where('date', '>', $validated['date'])
->orWhere(function ($sq) use ($validated, $startMeter) {
$sq->where('date', $validated['date'])
->where('start_meter', '>=', $startMeter);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($nextEntry && (float) $nextEntry->start_meter >= $startMeter) {
$endMeter = (float) $nextEntry->start_meter;
}
}
$operatingHours = $endMeter !== null ? max(0.0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang';
$updaterName = auth()->user()?->name ?? 'Admin QMA';
$timesheetNo = null;
@@ -325,6 +382,25 @@ class SupportTimesheetController extends Controller
'created_by_user_id' => auth()->id(),
]);
// 1b. Perbarui entri sebelumnya yang belum memiliki end_meter untuk unit yang sama (1 HM = 1 Jam)
$prevTimesheet = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where('id', '<', $timesheet->id)
->whereDate('date', '<=', $validated['date'])
->where(function ($q) {
$q->whereNull('end_meter')
->orWhere('end_meter', '<=', 0);
})
->orderByDesc('id')
->first();
if ($prevTimesheet && (float) $startMeter >= (float) $prevTimesheet->start_meter) {
$prevDiff = (float) $startMeter - (float) $prevTimesheet->start_meter;
$prevTimesheet->update([
'end_meter' => $startMeter,
'operating_hours' => $prevDiff,
]);
}
// 2. Sinkronisasi Master Kendaraan (Odometer & Posisi di Manajemen Unit)
$updateData = [
'status' => $validated['status'],
@@ -355,7 +431,12 @@ class SupportTimesheetController extends Controller
]);
});
return back()->with('success', "Timesheet {$timesheetNo} untuk unit {$vehicle->code} berhasil disimpan.");
$successMsg = "Timesheet {$timesheetNo} untuk unit {$vehicle->code} berhasil disimpan.";
if ($operatingHours !== null && $operatingHours > 24) {
$successMsg .= " (Catatan: Total waktu operasi tercatat {$operatingHours} HM/Jam [> 24 jam]. Harap periksa apakah angka Start HM atau End HM sudah sesuai).";
}
return back()->with('success', $successMsg);
}
/**
@@ -457,7 +538,12 @@ class SupportTimesheetController extends Controller
'notes' => $validated['notes'] ?? null,
]);
return back()->with('success', "Timesheet {$timesheet->timesheet_no} berhasil diperbarui.");
$successMsg = "Timesheet {$timesheet->timesheet_no} berhasil diperbarui.";
if ($operatingHours !== null && $operatingHours > 24) {
$successMsg .= " (Catatan: Total waktu operasi tercatat {$operatingHours} HM/Jam [> 24 jam]. Harap periksa apakah angka Start HM atau End HM sudah sesuai).";
}
return back()->with('success', $successMsg);
}
/**
@@ -511,6 +597,9 @@ class SupportTimesheetController extends Controller
$rows = [];
foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [
$idx + 1,
$ts->timesheet_no,
@@ -523,8 +612,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->nik ?: '-',
$ts->meter_type,
number_format($ts->start_meter, 2, ',', '.'),
number_format($ts->end_meter, 2, ',', '.'),
number_format($ts->operating_hours, 2, ',', '.'),
$endMeter !== null ? number_format($endMeter, 2, ',', '.') : '-',
$opHours !== null ? number_format($opHours, 2, ',', '.') : '-',
number_format($ts->standby_hours, 2, ',', '.'),
number_format($ts->breakdown_hours, 2, ',', '.'),
$ts->location,
@@ -606,6 +695,9 @@ class SupportTimesheetController extends Controller
$rows = [];
foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [
$idx + 1,
$ts->date ? $ts->date->format('d/m/Y') : '-',
@@ -614,8 +706,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->name ? ($ts->operator->name . ' (' . ($ts->operator->employee_type ?: 'Karyawan') . ')') : '-',
$ts->shift,
number_format($ts->start_meter, 1, ',', '.'),
number_format($ts->end_meter, 1, ',', '.'),
number_format($ts->operating_hours, 1, ',', '.') . ' ' . $ts->meter_type,
$endMeter !== null ? number_format($endMeter, 1, ',', '.') : '-',
($opHours !== null ? number_format($opHours, 1, ',', '.') : '-') . ' ' . $ts->meter_type,
$ts->location,
$ts->status,
];
@@ -143,12 +143,48 @@ class UnitTransferController extends Controller
->map(fn($group) => $group->count())
->sortKeys();
// 2. Daftar unit kendaraan kita untuk armada pengangkut (Truk, Flatbed, Lowbed, Towing, LV, dsb.)
// 2. Daftar armada pengangkut khusus truk/alat angkut (Lowbed, Flatbed, Trailer, Dump Truck, Light Truck, Crane Truck)
$transporterCategories = [
'Low Bed',
'Flat Bed',
'Trailer',
'Dump Truck',
'Light Truck',
'Crane Truck',
];
$transporterUnits = Vehicle::trackableUnits()
->orderBy('category')
->where(function (Builder $q) use ($transporterCategories) {
$q->whereIn('unit_category', $transporterCategories)
->orWhere(function (Builder $sub) {
$sub->where('code', 'like', 'LB %')
->orWhere('code', 'like', 'LB-%')
->orWhere('code', 'like', 'FB %')
->orWhere('code', 'like', 'FB-%')
->orWhere('code', 'like', 'TR %')
->orWhere('code', 'like', 'TR-%')
->orWhere('code', 'like', 'DT %')
->orWhere('code', 'like', 'DT-%')
->orWhere('code', 'like', 'LT %')
->orWhere('code', 'like', 'LT-%')
->orWhere('code', 'like', 'CT %')
->orWhere('code', 'like', 'CT-%');
});
})
->where(function (Builder $q) {
$q->where('code', 'not like', 'LV %')
->where('code', 'not like', 'LV-%')
->where('code', 'not like', 'LV/%')
->where('code', 'not like', 'LV_%');
})
->orderBy('code')
->get();
// Lokasi asal armada pengangkut internal yang tersedia beserta jumlah unitnya
$transporterLocations = $transporterUnits->groupBy(fn($u) => $u->location ?: 'Site Kerinci')
->map(fn($group) => $group->count())
->sortKeys();
// 3. Daftar pengemudi / operator
$drivers = Employee::where('is_operator', true)
->orderBy('name')
@@ -166,6 +202,7 @@ class UnitTransferController extends Controller
'originLocations',
'selectedOriginLocation',
'transporterUnits',
'transporterLocations',
'drivers',
'locationSuggestions',
'defaultDocNumber',
@@ -186,6 +223,8 @@ class UnitTransferController extends Controller
'to_site_status' => ['required', 'in:inside_site,outside_site'],
'description' => ['nullable', 'string', 'max:2000'],
'reported_by' => ['required', 'string', 'max:255'],
'transporter_type' => ['nullable', 'string', 'in:internal,external,none'],
'transporter_origin_location' => ['nullable', 'string', 'max:255'],
'transporter_vehicle_id' => ['nullable', 'integer', 'exists:vehicles,id'],
'transporter_unit_name' => ['nullable', 'string', 'max:255'],
'transporter_driver_id' => ['nullable', 'integer', 'exists:employees,id'],
@@ -221,14 +260,25 @@ class UnitTransferController extends Controller
$fromLocation = $vehicle->location ?: ($validated['from_location'] ?? 'Site Kerinci');
$fromSiteStatus = $vehicle->site_status ?: 'inside_site';
// Sumber Armada Pengangkut (Internal / External / None)
$transporterType = $validated['transporter_type'] ?? (!empty($validated['transporter_vehicle_id']) ? 'internal' : (!empty($validated['transporter_unit_name']) ? 'external' : 'none'));
$transporterVehicleId = ($transporterType === 'internal') ? ($validated['transporter_vehicle_id'] ?? null) : null;
$transporterOriginLocation = !empty($validated['transporter_origin_location']) ? trim($validated['transporter_origin_location']) : null;
// Nama armada pengangkut
$transporterUnitName = !empty($validated['transporter_unit_name']) ? trim($validated['transporter_unit_name']) : null;
if (empty($transporterUnitName) && !empty($validated['transporter_vehicle_id'])) {
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']);
if ($transporterType === 'internal' && !empty($transporterVehicleId)) {
$transporterVeh = Vehicle::find($transporterVehicleId);
if ($transporterVeh) {
$plate = $transporterVeh->license_plate ? " ({$transporterVeh->license_plate})" : '';
$transporterUnitName = "{$transporterVeh->code} - {$transporterVeh->brand_type}{$plate}";
if (empty($transporterOriginLocation)) {
$transporterOriginLocation = $transporterVeh->location ?: 'Site Kerinci';
}
}
} elseif ($transporterType === 'none') {
$transporterUnitName = 'Mobilisasi Mandiri (Tanpa Pengangkut)';
$transporterOriginLocation = null;
}
// Nama driver pengangkut
@@ -262,7 +312,9 @@ class UnitTransferController extends Controller
'description' => !empty($validated['description']) ? trim($validated['description']) : null,
'reported_by' => $reportedBy,
'user_id' => auth()->id(),
'transporter_vehicle_id' => $validated['transporter_vehicle_id'] ?? null,
'transporter_type' => $transporterType,
'transporter_vehicle_id' => $transporterVehicleId,
'transporter_origin_location' => $transporterOriginLocation,
'transporter_unit_name' => $transporterUnitName,
'transporter_driver_id' => $validated['transporter_driver_id'] ?? null,
'transporter_driver_name' => $transporterDriverName,
@@ -285,6 +337,9 @@ class UnitTransferController extends Controller
// 3. Catat di audit log riwayat pergerakan unit (VehicleLocationHistory)
$transporterSummary = $transporterUnitName ? " Pengangkut: {$transporterUnitName}" : "";
if ($transporterOriginLocation) {
$transporterSummary .= " [Asal: {$transporterOriginLocation}]";
}
if ($transporterDriverName) {
$transporterSummary .= " (Driver: {$transporterDriverName})";
}
@@ -305,9 +360,9 @@ class UnitTransferController extends Controller
'recorded_at' => Carbon::now(),
]);
// 4. Jika opsi perbarui posisi truk pengangkut aktif
if ($updateTransporter && !empty($validated['transporter_vehicle_id'])) {
$transporterVeh = Vehicle::find($validated['transporter_vehicle_id']);
// 4. Jika opsi perbarui posisi truk pengangkut aktif (Hanya armada internal)
if ($transporterType === 'internal' && $updateTransporter && !empty($transporterVehicleId)) {
$transporterVeh = Vehicle::find($transporterVehicleId);
if ($transporterVeh && $transporterVeh->id !== $vehicle->id) {
$transporterNote = $docNumber
? "Armada Pengangkut BAST {$docNumber} untuk {$vehicle->code} ke {$toLocation}"
@@ -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'],
+514 -62
View File
@@ -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);
+6
View File
@@ -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);
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+29
View File
@@ -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);
+53 -1
View File
@@ -45,6 +45,11 @@ class UnitSupportTimesheet extends Model
'fuel_liters' => 'decimal:2',
];
protected $appends = [
'effective_end_meter',
'effective_operating_hours',
];
public function vehicle(): BelongsTo
{
return $this->belongsTo(Vehicle::class);
@@ -52,7 +57,7 @@ class UnitSupportTimesheet extends Model
public function operator(): BelongsTo
{
return $this->belongsTo(Employee::class, 'operator_id');
return $this->belongsTo(Employee::class, 'operator_id')->withTrashed();
}
public function createdByUser(): BelongsTo
@@ -60,6 +65,53 @@ class UnitSupportTimesheet extends Model
return $this->belongsTo(User::class, 'created_by_user_id');
}
/**
* Dapatkan meter akhir efektif.
* Jika end_meter sudah diisi, gunakan nilainya.
* Jika belum, cari dari start_meter entri berikutnya untuk unit yang sama.
*/
public function getEffectiveEndMeterAttribute(): ?float
{
if ($this->end_meter !== null && (float) $this->end_meter > 0) {
return (float) $this->end_meter;
}
$next = static::where('vehicle_id', $this->vehicle_id)
->where(function ($q) {
$q->where('date', '>', $this->date)
->orWhere(function ($sq) {
$sq->where('date', $this->date)
->where('id', '>', $this->id);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($next && $next->start_meter !== null && (float) $next->start_meter >= (float) $this->start_meter) {
return (float) $next->start_meter;
}
return null;
}
/**
* Dapatkan jam kerja operasional efektif (1 HM = 1 Jam).
*/
public function getEffectiveOperatingHoursAttribute(): ?float
{
if ($this->operating_hours !== null && (float) $this->operating_hours > 0) {
return (float) $this->operating_hours;
}
$end = $this->effective_end_meter;
if ($end !== null && $this->start_meter !== null) {
return max(0.0, (float) $end - (float) $this->start_meter);
}
return null;
}
/**
* Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001).
* Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records.
+3 -1
View File
@@ -24,7 +24,9 @@ class UnitTransfer extends Model
'description',
'reported_by',
'user_id',
'transporter_type',
'transporter_vehicle_id',
'transporter_origin_location',
'transporter_unit_name',
'transporter_driver_id',
'transporter_driver_name',
@@ -66,7 +68,7 @@ class UnitTransfer extends Model
*/
public function transporterDriver(): BelongsTo
{
return $this->belongsTo(Employee::class, 'transporter_driver_id');
return $this->belongsTo(Employee::class, 'transporter_driver_id')->withTrashed();
}
/**
+18 -9
View File
@@ -33,17 +33,26 @@ class User extends Authenticatable
});
static::deleting(function (User $user) {
if ($user->employee) {
if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) {
throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
$employee = $user->employee ?: Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
$guard = $user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first();
if ($user->isForceDeleting()) {
$employeeTrashed = $employee ?: Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
if ($employeeTrashed && ($employeeTrashed->activities()->exists() || $employeeTrashed->p2hRecords()->exists() || $employeeTrashed->supportTimesheets()->exists())) {
throw new \RuntimeException("Tidak dapat menghapus permanen user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
}
$user->employee->delete();
}
if ($user->securityGuard) {
if ($user->securityGuard->activities()->exists()) {
throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
$guardTrashed = $guard ?: SecurityGuard::withTrashed()->where('user_id', $user->id)->first();
if ($guardTrashed && $guardTrashed->activities()->exists()) {
throw new \RuntimeException("Tidak dapat menghapus permanen user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
}
} else {
// Soft delete: cukup cascade soft delete data employee & securityGuard jika ada dan belum terhapus
if ($employee && ! $employee->trashed()) {
$employee->delete();
}
if ($guard && ! $guard->trashed()) {
$guard->delete();
}
$user->securityGuard->delete();
}
});
}
+1
View File
@@ -29,6 +29,7 @@ class Vehicle extends Model
'photo_path',
'unit_category',
'unit_type',
'operational_group',
'brand',
'model_number',
'production_year',
+1 -1
View File
@@ -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
+5
View File
@@ -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'])) {
+55 -43
View File
@@ -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,55 +674,67 @@ class DatabaseBackupService
fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n");
$query = DB::table($tableName);
// Pastikan data yang berada di tong sampah (soft-deleted) tidak bocor ke dalam data backup
$sql = "SELECT * FROM `{$tableName}`";
if (Schema::hasColumn($tableName, 'deleted_at')) {
$query->whereNull('deleted_at');
$sql .= " WHERE `deleted_at` IS NULL";
}
$totalRows = $query->count();
try {
$stmt = $pdo->query($sql);
} catch (\Throwable $e) {
$stmt = null;
}
if ($totalRows === 0) {
fwrite($handle, "-- (Tabel kosong)\n\n");
if (!$stmt) {
fwrite($handle, "-- (Tabel kosong atau gagal dibaca)\n\n");
return;
}
$query->orderBy(DB::raw('1'))->chunk(200, function ($rows) use ($handle, $pdo, $tableName) {
if ($rows->isEmpty()) return;
$batch = [];
$batchSize = 500;
$columnsStr = null;
$hasData = false;
$columns = array_keys((array) $rows->first());
$escapedColumns = array_map(fn ($c) => "`{$c}`", $columns);
$columnsStr = implode(', ', $escapedColumns);
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
$rowCount = count($rows);
$i = 0;
foreach ($rows as $row) {
$i++;
$values = [];
foreach ((array) $row as $val) {
if (is_null($val)) {
$values[] = 'NULL';
} elseif (is_int($val) || is_float($val)) {
$values[] = (string) $val;
} elseif (is_bool($val)) {
$values[] = $val ? '1' : '0';
} else {
$values[] = $pdo->quote((string) $val);
}
}
$line = ' (' . implode(', ', $values) . ')';
$line .= ($i === $rowCount) ? ";\n" : ",\n";
fwrite($handle, $line);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hasData = true;
if ($columnsStr === null) {
$columns = array_keys($row);
$escapedColumns = array_map(fn ($c) => "`{$c}`", $columns);
$columnsStr = implode(', ', $escapedColumns);
}
});
fwrite($handle, "\n");
$values = [];
foreach ($row as $val) {
if (is_null($val)) {
$values[] = 'NULL';
} elseif (is_int($val) || is_float($val)) {
$values[] = (string) $val;
} elseif (is_bool($val)) {
$values[] = $val ? '1' : '0';
} else {
$values[] = $pdo->quote((string) $val);
}
}
$batch[] = ' (' . implode(', ', $values) . ')';
if (count($batch) >= $batchSize) {
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
fwrite($handle, implode(",\n", $batch) . ";\n");
$batch = [];
}
}
if (!empty($batch)) {
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
fwrite($handle, implode(",\n", $batch) . ";\n");
}
if (!$hasData) {
fwrite($handle, "-- (Tabel kosong)\n\n");
} else {
fwrite($handle, "\n");
}
}
/**
+773
View File
@@ -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);
}
}
}
+33 -31
View File
@@ -306,51 +306,53 @@ class P2hInspectionPdfExporter extends FPDF
}
// -------------------------------------------------------------
// BLOK PENGESAHAN & TANDA TANGAN (3 Kolom)
// BLOK PENGESAHAN & TANDA TANGAN (2 Pihak: Operator & Admin QMA)
// -------------------------------------------------------------
if ($pdf->GetY() > 240) {
if ($pdf->GetY() > 235) {
$pdf->AddPage();
}
$pdf->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');
}
+33 -22
View File
@@ -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;
+3 -2
View File
@@ -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>';
+61 -6
View File
@@ -378,6 +378,36 @@ class TrashService
EmployeeSimper::onlyTrashed()
->where('employee_id', $item->id)
->restore();
$user = User::onlyTrashed()->where('id', $item->user_id)->orWhere('username', $item->nik)->first();
if ($user) {
$user->restore();
if ($user->role && ! $user->hasRole($user->role)) {
$role = \Spatie\Permission\Models\Role::where('name', $user->role)->first();
if ($role) {
$user->assignRole($role);
}
}
}
}
if ($item instanceof User) {
if ($item->role && ! $item->hasRole($item->role)) {
$role = \Spatie\Permission\Models\Role::where('name', $item->role)->first();
if ($role) {
$item->assignRole($role);
}
}
$employee = Employee::onlyTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
if ($employee) {
$employee->restore();
}
$guard = SecurityGuard::onlyTrashed()->where('user_id', $item->id)->first();
if ($guard) {
$guard->restore();
}
}
if ($item instanceof SimperType) {
@@ -422,6 +452,11 @@ class TrashService
}
if ($item instanceof Employee) {
// Cegah hapus permanen jika karyawan memiliki riwayat operasional (menjaga integritas data)
if ($item->activities()->exists() || $item->p2hRecords()->exists() || $item->supportTimesheets()->exists()) {
throw new \RuntimeException("Karyawan '{$item->name}' ({$item->nik}) memiliki riwayat transaksi aktif dan tidak dapat dihapus permanen untuk menjaga integritas data.");
}
EmployeeSimper::withTrashed()
->where('employee_id', $item->id)
->forceDelete();
@@ -448,6 +483,14 @@ class TrashService
}
if ($item instanceof User) {
$employee = Employee::withTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
if ($employee && ($employee->activities()->exists() || $employee->p2hRecords()->exists() || $employee->supportTimesheets()->exists())) {
throw new \RuntimeException("User '{$item->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H dan tidak dapat dihapus permanen untuk menjaga integritas data.");
}
$guard = SecurityGuard::withTrashed()->where('user_id', $item->id)->first();
if ($guard && $guard->activities()->exists()) {
throw new \RuntimeException("User '{$item->name}' memiliki riwayat data validasi pos gerbang dan tidak dapat dihapus permanen untuk menjaga integritas data.");
}
ImageCompressionService::deleteIfExists($item->photo_path ?? null);
}
@@ -469,8 +512,12 @@ class TrashService
$model = $categories[$category]['model'];
$items = $model::onlyTrashed()->get();
foreach ($items as $item) {
$this->forceDeleteItem($category, $item->id);
$totalDeleted++;
try {
$this->forceDeleteItem($category, $item->id);
$totalDeleted++;
} catch (\Throwable) {
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
}
}
return $totalDeleted;
}
@@ -480,8 +527,12 @@ class TrashService
$model = $config['model'];
$items = $model::onlyTrashed()->get();
foreach ($items as $item) {
$this->forceDeleteItem($catKey, $item->id);
$totalDeleted++;
try {
$this->forceDeleteItem($catKey, $item->id);
$totalDeleted++;
} catch (\Throwable) {
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
}
}
}
@@ -510,8 +561,12 @@ class TrashService
$model = $config['model'];
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
foreach ($expiredItems as $item) {
$this->forceDeleteItem($catKey, $item->id);
$prunedCount++;
try {
$this->forceDeleteItem($catKey, $item->id);
$prunedCount++;
} catch (\Throwable) {
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
}
}
}
+2
View File
@@ -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,
@@ -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
}
};
@@ -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');
}
});
}
};
+15
View File
@@ -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).");
+1
View File
@@ -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
+14 -3
View File
@@ -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).* {
+5 -5
View File
@@ -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
View File
@@ -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 -1
View File
@@ -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
+702 -2
View File
@@ -15,6 +15,11 @@
</p>
</div>
<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="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">
@@ -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 &amp; 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"
@@ -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">&times;</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 &amp; 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 &amp; 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 &amp; 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 &amp; 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>
@@ -775,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) */
@@ -863,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
+419 -134
View File
@@ -9,7 +9,7 @@
<div>
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5">
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span>
<span>Matriks Peran & Hak Akses Pengguna</span>
<span>Matriks Role & Hak Akses Pengguna</span>
<!-- Tooltip Super Admin Priviledge -->
<div class="relative group/tip inline-flex">
<button type="button"
@@ -75,167 +75,294 @@
</div>
@endif
<!-- Ringkasan Role Cards -->
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
@foreach($roles as $role)
@php
$isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']);
$badgeColor = match($role->name) {
'super_admin' => 'bg-indigo-600 text-white',
'hse_admin' => 'bg-emerald-600 text-white',
'qma_admin' => 'bg-blue-600 text-white',
'pg_admin' => 'bg-purple-600 text-white',
'gate_officer' => 'bg-amber-600 text-white',
default => 'bg-slate-700 text-white'
};
@endphp
<div class="bg-white border border-slate-200/80 rounded-2xl p-4 shadow-sm flex flex-col justify-between">
<div>
<div class="flex items-center justify-between mb-2">
<span class="w-2.5 h-2.5 rounded-full {{ $badgeColor }}"></span>
@if(!$isCoreRole)
<button type="button"
onclick='openDeleteRoleModal({{ $role->id }}, "{{ $role->name }}")'
class="text-slate-400 hover:text-rose-600 transition"
title="Hapus Role Kustom">
<i class="fa-solid fa-trash-can text-xs"></i>
</button>
<!-- Selector Tab Role Interaktif (Compact & User Friendly) -->
<div class="space-y-3">
<div class="flex items-center justify-between">
<span class="text-xs font-bold uppercase tracking-wider text-slate-500 flex items-center gap-1.5">
<i class="fa-solid fa-id-badge text-indigo-600"></i>
<span>Pilih Peran Pengguna (Role):</span>
</span>
<span class="text-[11px] text-slate-400">Pilih salah satu peran untuk melihat dan mengatur izinnya</span>
</div>
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
@foreach($roles as $role)
@php
$isCoreRole = in_array($role->name, ['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer']);
$dotColor = match($role->name) {
'super_admin' => 'bg-indigo-600',
'hse_admin' => 'bg-emerald-600',
'qma_admin' => 'bg-blue-600',
'pg_admin' => 'bg-purple-600',
'gate_officer' => 'bg-amber-600',
default => 'bg-slate-700'
};
@endphp
<button type="button"
onclick="switchRoleTab({{ $role->id }})"
id="tab-btn-{{ $role->id }}"
class="role-tab-btn text-left p-3.5 rounded-2xl border transition duration-200 relative group flex flex-col justify-between {{ $loop->first ? 'border-indigo-600 bg-indigo-50/60 ring-2 ring-indigo-500/20 shadow-sm' : 'border-slate-200/80 bg-white hover:bg-slate-50 hover:border-slate-300' }}">
<div class="w-full">
<div class="flex items-center justify-between mb-2">
<span class="w-2.5 h-2.5 rounded-full {{ $dotColor }}"></span>
@if(!$isCoreRole)
<span onclick="event.stopPropagation(); openDeleteRoleModal({{ $role->id }}, '{{ $role->name }}')"
class="text-slate-300 hover:text-rose-600 p-1 -mr-1 transition"
title="Hapus Role Kustom">
<i class="fa-solid fa-trash-can text-xs"></i>
</span>
@else
<span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Peran Utama</span>
@endif
</div>
<h2 class="text-xs font-bold text-slate-800 capitalize leading-snug">
{{ str_replace('_', ' ', $role->name) }}
</h2>
<p class="text-[10px] text-slate-400 font-mono mt-0.5 truncate">{{ $role->name }}</p>
</div>
<div class="mt-3 pt-2 border-t border-slate-100 flex items-center justify-between text-[11px] w-full">
<span class="text-slate-500">Izin Akses:</span>
@if($role->name === 'super_admin')
<span class="font-black text-indigo-700 flex items-center gap-1">
<i class="fa-solid fa-crown text-[9px] text-amber-500"></i>
<span>Penuh</span>
</span>
@else
<span class="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Peran Utama</span>
<span class="font-bold text-indigo-700 role-perm-badge-count" data-role-id="{{ $role->id }}">
{{ $role->permissions->count() }} Izin
</span>
@endif
</div>
<h2 class="text-xs font-bold text-slate-800 capitalize">{{ str_replace('_', ' ', $role->name) }}</h2>
<p class="text-[10px] text-slate-400 mt-0.5 font-mono">{{ $role->name }}</p>
</div>
<div class="mt-3 pt-2.5 border-t border-slate-100 flex items-center justify-between text-[11px]">
<span class="text-slate-500">Jumlah Hak Akses:</span>
@if($role->name === 'super_admin')
<div class="relative group/tip inline-flex">
<span class="font-bold text-indigo-700 cursor-help flex items-center gap-1">
<span>Akses Lengkap</span>
<i class="fa-solid fa-circle-info text-[10px] text-indigo-400"></i>
</span>
<div class="absolute right-0 bottom-full mb-2 hidden group-hover/tip:block z-50 w-72 p-3 bg-slate-900 text-white text-xs rounded-xl shadow-xl pointer-events-none">
<div class="flex items-start gap-2">
<i class="fa-solid fa-crown text-amber-400 text-xs mt-0.5 flex-shrink-0"></i>
<div>
<strong class="font-bold text-white text-xs block">Hak Akses Penuh Super Administrator</strong>
<p class="text-slate-300 text-[11px] mt-0.5 leading-relaxed">
Secara otomatis memiliki akses penuh ke seluruh menu dan modul sistem tanpa batasan.
</p>
</div>
</div>
<div class="absolute -bottom-1 right-3 w-2 h-2 bg-slate-900 rotate-45"></div>
</div>
</div>
@else
<span class="font-bold text-indigo-700">
{{ $role->permissions->count() . ' Izin' }}
</span>
@endif
</div>
</div>
@endforeach
</button>
@endforeach
</div>
</div>
<!-- Matriks Role & Permissions Table -->
<!-- Kontainer Panel Hak Akses Per Role (Hanya Role Aktif yang Ditampilkan) -->
<div class="space-y-6">
@foreach($roles as $role)
<div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden">
<div class="px-5 py-3.5 bg-slate-50 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded-xl bg-indigo-50 border border-indigo-100 text-indigo-700 flex items-center justify-center font-bold text-xs">
@php
$rolePermNames = $role->permissions->pluck('name')->toArray();
$isSuperAdmin = $role->name === 'super_admin';
@endphp
<div id="role-panel-{{ $role->id }}"
class="role-panel bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden {{ $loop->first ? '' : 'hidden' }}">
<!-- Panel Header Sticky/Top Bar -->
<div class="px-5 py-4 bg-slate-50/80 border-b border-slate-200/70 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div class="flex items-start sm:items-center gap-3">
<div class="w-10 h-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center font-bold text-sm shadow-sm flex-shrink-0">
<i class="fa-solid fa-shield-halved"></i>
</div>
<div>
<h2 class="text-sm font-bold text-slate-900 capitalize flex items-center gap-2">
<span>Peran: {{ str_replace('_', ' ', $role->name) }}</span>
@if($role->name === 'super_admin')
<div class="relative group/satip inline-flex">
<span class="px-2 py-0.5 rounded-full text-[9px] font-black bg-indigo-100 text-indigo-800 flex items-center gap-1 cursor-help">
<i class="fa-solid fa-crown text-[8px]"></i>
<span>AKSES LENGKAP</span>
<i class="fa-solid fa-circle-info text-[9px] text-indigo-500"></i>
</span>
<div class="absolute left-0 top-full mt-2 hidden group-hover/satip:block z-50 w-72 sm:w-80 p-3 bg-slate-900 text-white text-xs rounded-xl shadow-xl pointer-events-none">
<div class="flex items-start gap-2.5">
<i class="fa-solid fa-crown text-amber-400 text-xs mt-0.5 flex-shrink-0"></i>
<div>
<strong class="font-bold text-white text-xs block">Hak Akses Penuh Super Administrator</strong>
<p class="text-slate-300 text-[11px] mt-0.5 leading-relaxed">
Akun dengan peran <strong>Super Administrator</strong> secara otomatis memiliki akses penuh ke seluruh menu dan modul sistem tanpa batasan. Pilihan centang di bawah digunakan untuk mengatur batasan akses peran staf operasional lainnya.
</p>
</div>
</div>
<div class="absolute -top-1 left-4 w-2 h-2 bg-slate-900 rotate-45"></div>
</div>
</div>
<div class="flex items-center gap-2 flex-wrap">
<h2 class="text-base font-extrabold text-slate-800 capitalize">
Pengaturan Hak Akses: {{ str_replace('_', ' ', $role->name) }}
</h2>
@if($isSuperAdmin)
<span class="px-2.5 py-0.5 rounded-full text-[10px] font-black bg-amber-100 text-amber-800 border border-amber-200 inline-flex items-center gap-1">
<i class="fa-solid fa-crown text-[9px]"></i>
<span>BYPASS PENUH</span>
</span>
@else
<span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-indigo-100 text-indigo-800 border border-indigo-200">
Peran: <code class="font-mono">{{ $role->name }}</code>
</span>
@endif
</h2>
<p class="text-[11px] text-slate-400">Atur centang hak akses menu yang diizinkan untuk peran pengguna ini.</p>
</div>
<p class="text-xs text-slate-500 mt-0.5">
@if($isSuperAdmin)
Peran ini adalah tingkat tertinggi sistem. Seluruh hak akses otomatis aktif secara permanen.
@else
Centang fitur atau menu yang boleh diakses dan dijalankan oleh pengguna dengan peran ini.
@endif
</p>
</div>
</div>
@if($role->name !== 'super_admin')
<button type="submit"
form="form-role-{{ $role->id }}"
class="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-sm transition self-end sm:self-auto">
<i class="fa-solid fa-floppy-disk"></i>
<span>Simpan Hak Akses</span>
</button>
@endif
<!-- Tombol Aksi & Simpan -->
<div class="flex items-center gap-2 self-end md:self-auto flex-wrap">
@if(!$isSuperAdmin)
<button type="button"
onclick="toggleAllRolePermissions({{ $role->id }}, true)"
class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5"
title="Centang semua hak akses untuk peran ini">
<i class="fa-solid fa-check-double text-indigo-600"></i>
<span>Pilih Semua</span>
</button>
<button type="button"
onclick="toggleAllRolePermissions({{ $role->id }}, false)"
class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5"
title="Hilangkan semua centang untuk peran ini">
<i class="fa-solid fa-rotate-left text-slate-500"></i>
<span>Kosongkan</span>
</button>
<button type="submit"
form="form-role-{{ $role->id }}"
class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-md shadow-indigo-600/20 transition">
<i class="fa-solid fa-floppy-disk"></i>
<span>Simpan Perubahan</span>
</button>
@endif
</div>
</div>
@if($isSuperAdmin)
<!-- Notifikasi Super Admin Bypass -->
<div class="m-5 p-4 rounded-xl bg-amber-50/70 border border-amber-200/80 flex items-start gap-3 text-amber-900 text-xs">
<i class="fa-solid fa-circle-exclamation text-amber-600 text-base mt-0.5 flex-shrink-0"></i>
<div>
<strong class="font-bold block">Hak Akses Super Administrator Tidak Terbatas</strong>
<p class="text-amber-800 text-[11px] mt-0.5 leading-relaxed">
Sesuai arsitektur keamanan Spatie RBAC, pengguna dengan peran <code>super_admin</code> memiliki hak <em>Gate::before bypass</em> yang mengizinkan akses ke seluruh API, controller, rute, dan menu tanpa perlu diverifikasi satu per satu.
</p>
</div>
</div>
@else
<!-- Search Filter Bar per Role -->
<div class="px-5 pt-4 pb-2 flex flex-col sm:flex-row items-center justify-between gap-3 border-b border-slate-100">
<div class="relative w-full sm:w-80">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="search-role-{{ $role->id }}"
oninput="filterRolePermissions({{ $role->id }}, this.value)"
placeholder="Cari izin / nama menu (misal: p2h, simper, gate)..."
class="w-full pl-9 pr-8 py-2 bg-slate-50 border border-slate-200 rounded-xl text-xs focus:ring-2 focus:ring-indigo-500 focus:bg-white focus:border-indigo-500 transition">
<button type="button"
onclick="clearRoleSearch({{ $role->id }})"
id="clear-search-{{ $role->id }}"
class="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 hidden text-xs">
<i class="fa-solid fa-circle-xmark"></i>
</button>
</div>
<div class="text-[11px] text-slate-500 flex items-center gap-2">
<span class="w-2 h-2 rounded-full bg-emerald-500"></span>
<span>Total Terpilih:</span>
<strong class="font-bold text-slate-800" id="selected-stat-{{ $role->id }}">{{ count($rolePermNames) }}</strong>
<span class="text-slate-400">izin aktif</span>
</div>
</div>
@endif
<!-- Form Modul & Permission Checklists -->
<form id="form-role-{{ $role->id }}"
action="{{ route('admin.roles.permissions.update', $role->id) }}"
method="POST"
class="p-5">
@csrf
@php
$rolePermNames = $role->permissions->pluck('name')->toArray();
@endphp
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div id="module-grid-{{ $role->id }}" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
@foreach($modules as $moduleKey => $module)
<div class="bg-slate-50/70 border border-slate-200/60 rounded-xl p-4 space-y-3">
<h3 class="text-xs font-bold text-slate-800 flex items-center justify-between pb-2 border-b border-slate-200/60">
<span class="flex items-center gap-1.5">
<i class="{{ $module['icon'] }} text-indigo-600 text-xs"></i>
<span>{{ $module['name'] }}</span>
</span>
<span class="text-[10px] text-slate-400 font-semibold">{{ count($module['permissions']) }} hak akses</span>
</h3>
<div class="space-y-2">
@foreach($module['permissions'] as $permKey => $permMeta)
@php
$isChecked = $role->name === 'super_admin' || in_array($permKey, $rolePermNames);
@endphp
<label class="flex items-start gap-2.5 text-xs text-slate-700 cursor-pointer select-none group p-2 rounded-lg hover:bg-white hover:shadow-xs border border-transparent hover:border-slate-200/60 transition">
<input type="checkbox"
name="permissions[]"
value="{{ $permKey }}"
{{ $isChecked ? 'checked' : '' }}
{{ $role->name === 'super_admin' ? 'disabled' : '' }}
class="mt-1 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 transition">
<div>
<span class="text-xs font-bold text-slate-800 group-hover:text-indigo-600 transition block">
{{ $permMeta['label'] }}
</span>
<p class="text-[11px] text-slate-500 mt-0.5 leading-snug">
{{ $permMeta['description'] }}
</p>
<span class="font-mono text-[10px] text-slate-400 mt-1 block">
{{ $permKey }}
</span>
@php
$totalInModule = count($module['permissions']);
$activeInModule = 0;
foreach($module['permissions'] as $pKey => $pMeta) {
if ($isSuperAdmin || in_array($pKey, $rolePermNames)) {
$activeInModule++;
}
}
@endphp
<div class="perm-module-card bg-slate-50/70 border border-slate-200/70 rounded-xl p-4 flex flex-col justify-between space-y-3 transition"
data-module-key="{{ $moduleKey }}">
<div>
<!-- Header Modul -->
<div class="flex items-center justify-between pb-2.5 border-b border-slate-200/60 mb-2.5">
<div class="flex items-center gap-2">
<div class="w-6 h-6 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center text-xs">
<i class="{{ $module['icon'] }}"></i>
</div>
</label>
@endforeach
<h3 class="text-xs font-bold text-slate-800 leading-snug">
{{ $module['name'] }}
</h3>
</div>
<div class="flex items-center gap-2">
<span class="text-[10px] font-bold text-slate-500 bg-white px-2 py-0.5 rounded-md border border-slate-200/80 module-counter"
id="mod-count-{{ $role->id }}-{{ $moduleKey }}">
{{ $activeInModule }}/{{ $totalInModule }}
</span>
@if(!$isSuperAdmin)
<div class="flex items-center space-x-1">
<button type="button"
onclick="toggleModuleCheckboxes({{ $role->id }}, '{{ $moduleKey }}', true)"
class="text-[10px] font-bold text-indigo-600 hover:text-indigo-800 px-1 py-0.5 hover:bg-indigo-50 rounded transition"
title="Centang semua di modul ini">
Semua
</button>
<span class="text-slate-300 text-[10px]">|</span>
<button type="button"
onclick="toggleModuleCheckboxes({{ $role->id }}, '{{ $moduleKey }}', false)"
class="text-[10px] font-bold text-slate-500 hover:text-slate-700 px-1 py-0.5 hover:bg-slate-200/50 rounded transition"
title="Batalkan centang modul ini">
Batal
</button>
</div>
@endif
</div>
</div>
<!-- Daftar Permission -->
<div class="space-y-1.5">
@foreach($module['permissions'] as $permKey => $permMeta)
@php
$isChecked = $isSuperAdmin || in_array($permKey, $rolePermNames);
@endphp
<label class="perm-item flex items-start gap-2.5 text-xs text-slate-700 cursor-pointer select-none group p-2 rounded-lg hover:bg-white hover:shadow-xs border border-transparent hover:border-slate-200/60 transition {{ $isChecked ? 'bg-indigo-50/20' : '' }}"
data-search-text="{{ strtolower($permMeta['label'] . ' ' . $permMeta['description'] . ' ' . $permKey . ' ' . $module['name']) }}">
<input type="checkbox"
name="permissions[]"
value="{{ $permKey }}"
data-module="{{ $moduleKey }}"
onchange="onPermissionChange({{ $role->id }}, '{{ $moduleKey }}')"
{{ $isChecked ? 'checked' : '' }}
{{ $isSuperAdmin ? 'disabled' : '' }}
class="perm-checkbox-{{ $role->id }} mt-0.5 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 transition">
<div class="flex-1 min-w-0">
<span class="text-xs font-bold text-slate-800 group-hover:text-indigo-600 transition block">
{{ $permMeta['label'] }}
</span>
<p class="text-[11px] text-slate-500 mt-0.5 leading-snug">
{{ $permMeta['description'] }}
</p>
<span class="font-mono text-[9px] text-slate-400 mt-0.5 block truncate">
{{ $permKey }}
</span>
</div>
</label>
@endforeach
</div>
</div>
</div>
@endforeach
</div>
<!-- Empty Search Result State -->
<div id="empty-search-{{ $role->id }}" class="hidden py-12 text-center">
<div class="w-12 h-12 rounded-full bg-slate-100 text-slate-400 flex items-center justify-center mx-auto mb-2 text-base">
<i class="fa-solid fa-magnifying-glass"></i>
</div>
<h4 class="text-xs font-bold text-slate-700">Tidak ada hak akses yang cocok</h4>
<p class="text-[11px] text-slate-400 mt-0.5">Coba gunakan kata kunci pencarian yang lain.</p>
<button type="button" onclick="clearRoleSearch({{ $role->id }})" class="mt-3 px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-lg text-xs font-bold transition">
Reset Pencarian
</button>
</div>
@if(!$isSuperAdmin)
<!-- Bottom Action Bar -->
<div class="mt-6 pt-4 border-t border-slate-100 flex items-center justify-between">
<p class="text-xs text-slate-400">
Pastikan klik tombol <strong>Simpan Perubahan</strong> untuk menerapkan hak akses ke pengguna terkait.
</p>
<button type="submit"
class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-md shadow-indigo-600/20 transition">
<i class="fa-solid fa-floppy-disk"></i>
<span>Simpan Perubahan</span>
</button>
</div>
@endif
</form>
</div>
@endforeach
@@ -306,6 +433,164 @@
</div>
<script>
// Tab switching antar Role
function switchRoleTab(roleId) {
// Sembunyikan semua panel role
document.querySelectorAll('.role-panel').forEach(panel => {
panel.classList.add('hidden');
});
// Non-aktifkan semua styling tombol tab
document.querySelectorAll('.role-tab-btn').forEach(btn => {
btn.classList.remove('border-indigo-600', 'bg-indigo-50/60', 'ring-2', 'ring-indigo-500/20', 'shadow-sm');
btn.classList.add('border-slate-200/80', 'bg-white');
});
// Tampilkan panel role terpilih
const activePanel = document.getElementById(`role-panel-${roleId}`);
if (activePanel) {
activePanel.classList.remove('hidden');
}
// Aktifkan styling tab terpilih
const activeBtn = document.getElementById(`tab-btn-${roleId}`);
if (activeBtn) {
activeBtn.classList.remove('border-slate-200/80', 'bg-white');
activeBtn.classList.add('border-indigo-600', 'bg-indigo-50/60', 'ring-2', 'ring-indigo-500/20', 'shadow-sm');
}
}
// Toggle semua checkbox untuk role tertentu
function toggleAllRolePermissions(roleId, checked) {
const checkboxes = document.querySelectorAll(`.perm-checkbox-${roleId}`);
checkboxes.forEach(cb => {
if (!cb.disabled) {
cb.checked = checked;
}
});
updateRoleStats(roleId);
}
// Toggle checkbox per modul
function toggleModuleCheckboxes(roleId, moduleKey, checked) {
const checkboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${moduleKey}"]`);
checkboxes.forEach(cb => {
if (!cb.disabled) {
cb.checked = checked;
}
});
onPermissionChange(roleId, moduleKey);
}
// Handler ketika ada checkbox yang berubah
function onPermissionChange(roleId, moduleKey) {
// Update counter per modul
const modCheckboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${moduleKey}"]`);
const checkedInMod = Array.from(modCheckboxes).filter(cb => cb.checked).length;
const totalInMod = modCheckboxes.length;
const counterEl = document.getElementById(`mod-count-${roleId}-${moduleKey}`);
if (counterEl) {
counterEl.textContent = `${checkedInMod}/${totalInMod}`;
}
updateRoleStats(roleId);
}
// Update counter total hak akses aktif untuk suatu role
function updateRoleStats(roleId) {
const allCheckboxes = document.querySelectorAll(`.perm-checkbox-${roleId}`);
const totalChecked = Array.from(allCheckboxes).filter(cb => cb.checked).length;
// Update badge di header panel
const statEl = document.getElementById(`selected-stat-${roleId}`);
if (statEl) {
statEl.textContent = totalChecked;
}
// Update badge di tombol tab atas
const tabBadge = document.querySelector(`.role-perm-badge-count[data-role-id="${roleId}"]`);
if (tabBadge) {
tabBadge.textContent = `${totalChecked} Izin`;
}
// Update semua counter modul
const modules = new Set();
allCheckboxes.forEach(cb => {
const m = cb.getAttribute('data-module');
if (m) modules.add(m);
});
modules.forEach(m => {
const modCheckboxes = document.querySelectorAll(`#form-role-${roleId} input[data-module="${m}"]`);
const checkedInMod = Array.from(modCheckboxes).filter(cb => cb.checked).length;
const totalInMod = modCheckboxes.length;
const counterEl = document.getElementById(`mod-count-${roleId}-${m}`);
if (counterEl) {
counterEl.textContent = `${checkedInMod}/${totalInMod}`;
}
});
}
// Live Search Filter Hak Akses
function filterRolePermissions(roleId, rawKeyword) {
const keyword = (rawKeyword || '').toLowerCase().trim();
const clearBtn = document.getElementById(`clear-search-${roleId}`);
if (clearBtn) {
clearBtn.classList.toggle('hidden', keyword.length === 0);
}
const panel = document.getElementById(`role-panel-${roleId}`);
if (!panel) return;
const moduleCards = panel.querySelectorAll('.perm-module-card');
let totalVisibleCards = 0;
moduleCards.forEach(card => {
const items = card.querySelectorAll('.perm-item');
let visibleInCard = 0;
items.forEach(item => {
const text = item.getAttribute('data-search-text') || '';
if (!keyword || text.includes(keyword)) {
item.classList.remove('hidden');
visibleInCard++;
} else {
item.classList.add('hidden');
}
});
if (visibleInCard > 0) {
card.classList.remove('hidden');
totalVisibleCards++;
} else {
card.classList.add('hidden');
}
});
const emptyState = document.getElementById(`empty-search-${roleId}`);
const moduleGrid = document.getElementById(`module-grid-${roleId}`);
if (emptyState && moduleGrid) {
if (totalVisibleCards === 0 && keyword.length > 0) {
emptyState.classList.remove('hidden');
moduleGrid.classList.add('hidden');
} else {
emptyState.classList.add('hidden');
moduleGrid.classList.remove('hidden');
}
}
}
function clearRoleSearch(roleId) {
const input = document.getElementById(`search-role-${roleId}`);
if (input) {
input.value = '';
filterRolePermissions(roleId, '');
input.focus();
}
}
// Modal Manajemen Role
function openCreateRoleModal() {
document.getElementById('createRoleModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
+3 -2
View File
@@ -1162,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'
}
});
+2 -2
View File
@@ -560,11 +560,11 @@
const pdfBtn = document.getElementById('modalDownloadPdfBtn');
const tableBody = document.getElementById('modalItemsTableBody');
pdfBtn.href = "{{ url('/karyawan/riwayat/p2h') }}/" + recordId + "/pdf";
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') }}/" + recordId)
fetch("{{ url('/karyawan/riwayat/p2h', [], false) }}/" + recordId)
.then(res => {
if (!res.ok) throw new Error('Gagal memuat detail data.');
return res.json();
+17
View File
@@ -197,6 +197,23 @@
<span>Berlaku s.d. {{ $log->simper_expired_at->locale('id')->translatedFormat('d M Y') }} ({{ $log->simper_expired_at->locale('id')->diffForHumans() }})</span>
</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 -->
+39 -13
View File
@@ -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 = '';
}
}
}
}
+490 -58
View File
@@ -281,7 +281,7 @@
<i class="fa-solid fa-up-right-from-square text-[11px]"></i>
</a>
<span class="text-slate-200">|</span>
<button onclick="openRenewModal({{ $emp->id }}, '{{ addslashes($emp->name) }}', '{{ $emp->simper_expired_at ? $emp->simper_expired_at->format('Y-m-d') : '' }}', {{ $emp->is_operator ? '1' : '0' }})"
<button onclick='openRenewModal(@json($emp))'
class="text-emerald-700 hover:text-emerald-900 font-bold underline text-[11px] px-1 cursor-pointer"
title="Perpanjang Masa Berlaku SIMPER">
Perpanjang
@@ -483,18 +483,21 @@
<div class="space-y-2 max-h-[48vh] overflow-y-auto pr-1">
@foreach($availableSimperTypes as $st)
<div class="p-3 rounded-2xl border border-slate-200 bg-slate-50/70 hover:bg-slate-50 transition">
<div class="flex items-center justify-between gap-2">
<label class="flex items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
<div class="flex items-start sm:items-center justify-between gap-2.5">
<label class="flex items-start sm:items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
<input type="checkbox"
name="simper_assignments[{{ $st->id }}][enabled]"
value="1"
id="addSimperCheck_{{ $st->id }}"
onchange="toggleAddSimperFields({{ $st->id }})"
class="w-4 h-4 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0">
<span class="truncate">{{ $st->name }} ({{ $st->code }})</span>
class="w-4 h-4 mt-0.5 sm:mt-0 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0 cursor-pointer">
<div class="min-w-0">
<span class="block truncate font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
<span class="block text-[10px] font-mono text-slate-400 font-semibold">{{ $st->code }}</span>
</div>
</label>
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase flex-shrink-0" title="{{ $st->category_scope_display }}">
{{ $st->category_scope_display }}
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase max-w-[140px] sm:max-w-[200px] truncate flex-shrink-0" title="{{ $st->category_scope_display }}">
{{ $st->short_scope_display ?? $st->category_scope_display }}
</span>
</div>
<div id="addSimperFields_{{ $st->id }}" class="hidden grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2 pt-2 border-t border-slate-200/60">
@@ -633,43 +636,123 @@
</div>
</div>
<!-- Modal Dialog Perpanjang SIMPER (Clean White Card) -->
<!-- Modal Dialog Perpanjang SIMPER (Clean White Card dengan Dukungan Multi-SIMPER) -->
<div id="renewModal" data-backdrop="static" class="hidden fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl shadow-2xl max-w-md w-full p-7 border border-slate-100 overflow-hidden">
<div class="flex items-center justify-between pb-4 border-b border-slate-100">
<h3 class="text-xl font-bold text-slate-900 tracking-tight">Perpanjang SIMPER</h3>
<div class="bg-white rounded-3xl shadow-2xl max-w-lg w-full p-6 sm:p-7 border border-slate-100 overflow-hidden animate-scale-in max-h-[92vh] flex flex-col">
<div class="flex items-center justify-between pb-3.5 border-b border-slate-100 flex-shrink-0">
<div>
<h3 class="text-base sm:text-lg font-bold text-slate-900 tracking-tight flex items-center gap-2">
<div class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center text-sm border border-emerald-100">
<i class="fa-solid fa-id-card-clip"></i>
</div>
<span>Perpanjang Masa Berlaku SIMPER</span>
</h3>
<p class="text-xs text-slate-500 mt-0.5">Pilih jenis SIMPER personel dan tentukan tanggal masa berlaku operasional baru.</p>
</div>
<button type="button" onclick="closeRenewModal()" class="text-slate-400 hover:text-slate-600 transition p-1">
<i class="fa-solid fa-xmark text-lg"></i>
</button>
</div>
<form id="renewForm" method="POST" action="" class="mt-5 space-y-4">
<form id="renewForm" method="POST" action="" class="mt-4 space-y-4 overflow-y-auto pr-1">
@csrf
<div class="bg-slate-50 p-3.5 rounded-2xl border border-slate-200/80">
<span class="text-xs text-slate-400 block font-medium">Pengemudi:</span>
<strong id="renewName" class="block text-base text-slate-900 font-bold mt-0.5"></strong>
<!-- Identitas Personel (Karyawan / Sukon) -->
<div class="bg-slate-50/90 p-3.5 rounded-2xl border border-slate-200/80 flex items-start justify-between gap-3">
<div class="min-w-0">
<span class="text-[10px] text-slate-400 block font-bold uppercase tracking-wider">Personel / Operator:</span>
<strong id="renewName" class="block text-sm text-slate-900 font-extrabold mt-0.5 truncate"></strong>
<div class="flex items-center gap-2 mt-1 flex-wrap">
<span id="renewNik" class="text-[11px] font-mono font-bold text-slate-600 bg-white px-2 py-0.5 rounded border border-slate-200"></span>
<span id="renewUnitDept" class="text-[11px] text-slate-500"></span>
</div>
</div>
<div class="flex flex-col items-end gap-1 flex-shrink-0">
<span id="renewCategoryBadge" class="px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-slate-200/70 text-slate-700">
Karyawan
</span>
<span class="px-2.5 py-0.5 rounded-lg text-[10px] font-bold bg-emerald-100 text-[#1b5e20] border border-emerald-200/80">
Driver / Operator
</span>
</div>
</div>
<!-- Status Driver (Hidden input default 1) -->
<input type="hidden" name="is_operator" id="renewOperator" value="1">
<!-- Ringkasan SIMPER yang Sedang Dimiliki Saat Ini -->
<div class="p-3.5 rounded-2xl bg-indigo-50/30 border border-indigo-100/70 space-y-2">
<div class="flex items-center justify-between">
<span class="text-xs font-bold text-slate-800 flex items-center gap-1.5">
<i class="fa-solid fa-shield-halved text-indigo-600 text-xs"></i>
<span>SIMPER yang Sedang Dimiliki Saat Ini:</span>
</span>
<span id="renewSimperBadge" class="text-[10px] font-bold px-2 py-0.5 rounded-full bg-white text-indigo-700 border border-indigo-200 font-mono"></span>
</div>
<div id="renewCurrentSimperCards" class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
<!-- Dinamis via JavaScript -->
</div>
</div>
<!-- Dropdown Pilihan Jenis SIMPER yang Diperpanjang -->
<div>
<label class="block text-sm font-bold text-slate-800 mb-2">Status Driver</label>
<select name="is_operator" id="renewOperator" onchange="toggleSimperInput('renew')"
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition">
<option value="1">YA (Aktif Mengemudi)</option>
<option value="0">TIDAK (Bukan Driver)</option>
<label for="renewSimperTypeSelect" class="block text-xs font-bold text-slate-800 mb-1.5 flex items-center justify-between">
<span>Pilih SIMPER yang Ingin Diperpanjang <span class="text-rose-500">*</span></span>
<span class="text-[10px] text-slate-400 font-normal">Pilih satu atau semua</span>
</label>
<select name="renew_simper_type_id" id="renewSimperTypeSelect" onchange="onRenewSimperTypeChange(this.value)" required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-300 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition shadow-xs">
<!-- Dinamis via JavaScript -->
</select>
</div>
<div>
<label class="block text-sm font-bold text-slate-800 mb-2">Masa Berlaku Baru <span class="text-rose-500">*</span></label>
<input type="date" name="simper_expired_at" id="renewDate" required
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition">
<!-- Detail SIMPER Terpilih (Live Information Box) -->
<div id="renewSelectedDetailBox" class="p-3 rounded-xl bg-slate-50 border border-slate-200/80 text-xs space-y-1">
<div class="flex items-center justify-between">
<span class="text-[11px] text-slate-500">Masa Berlaku Saat Ini:</span>
<strong id="renewCurrentExpText" class="text-slate-800 font-mono text-[11px]">-</strong>
</div>
<div class="flex items-center justify-between">
<span class="text-[11px] text-slate-500">Status Izin:</span>
<span id="renewCurrentStatusBadge" class="text-[10px] font-bold px-2 py-0.2 rounded font-mono">-</span>
</div>
</div>
<div class="pt-6 border-t border-slate-100 flex items-center justify-end space-x-3 mt-6">
<!-- Input Tanggal Kedaluwarsa Baru -->
<div>
<label for="renewDate" class="block text-xs font-bold text-slate-800 mb-1.5 flex items-center justify-between">
<span>Masa Berlaku Baru (Hasil Perpanjangan) <span class="text-rose-500">*</span></span>
<span class="text-[10px] text-emerald-700 font-semibold" id="renewRecommendLabel">Rekomendasi: +1 Tahun</span>
</label>
<input type="date" name="simper_expired_at" id="renewDate" required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-300 bg-white text-slate-800 font-bold font-mono focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition shadow-xs">
<!-- Quick Preset Buttons (+6 Bulan, +1 Tahun, +2 Tahun, +3 Tahun) -->
<div class="flex items-center gap-1.5 mt-2 flex-wrap">
<span class="text-[10px] text-slate-400 font-bold uppercase tracking-wider mr-1">Pintas Cepat:</span>
<button type="button" onclick="setRenewDateOffset(6)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+6 Bulan
</button>
<button type="button" onclick="setRenewDateOffset(12)" class="text-[11px] px-2.5 py-1 rounded-lg border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-[#1b5e20] font-bold transition cursor-pointer">
+1 Tahun (Standar)
</button>
<button type="button" onclick="setRenewDateOffset(24)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+2 Tahun
</button>
<button type="button" onclick="setRenewDateOffset(36)" class="text-[11px] px-2.5 py-1 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 font-semibold transition cursor-pointer">
+3 Tahun
</button>
</div>
</div>
<div class="pt-4 border-t border-slate-100 flex items-center justify-end space-x-2.5 mt-5">
<button type="button" onclick="closeRenewModal()"
class="px-6 py-2.5 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 font-bold text-sm transition">
class="px-4 py-2 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 font-bold text-xs transition">
Batal
</button>
<button type="submit"
class="px-6 py-2.5 rounded-xl bg-[#1b5e20] hover:bg-[#144919] text-white font-bold text-sm transition shadow-sm">
Simpan Data
class="px-5 py-2.5 rounded-xl bg-[#1b5e20] hover:bg-[#144919] text-white font-bold text-xs transition shadow-md shadow-emerald-700/20 inline-flex items-center gap-1.5">
<i class="fa-solid fa-floppy-disk text-xs"></i>
<span>Simpan Perpanjangan</span>
</button>
</div>
</form>
@@ -839,18 +922,21 @@
<div class="space-y-2 max-h-[50vh] overflow-y-auto pr-1">
@foreach($availableSimperTypes as $st)
<div class="p-3 rounded-2xl border border-slate-200 bg-slate-50/70 hover:bg-slate-50 transition">
<div class="flex items-center justify-between gap-2">
<label class="flex items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
<div class="flex items-start sm:items-center justify-between gap-2.5">
<label class="flex items-start sm:items-center space-x-2.5 text-xs font-bold text-slate-800 cursor-pointer flex-1 min-w-0">
<input type="checkbox"
name="simper_assignments[{{ $st->id }}][enabled]"
value="1"
id="editSimperCheck_{{ $st->id }}"
onchange="toggleEditSimperFields({{ $st->id }})"
class="w-4 h-4 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0">
<span class="truncate">{{ $st->name }} ({{ $st->code }})</span>
class="w-4 h-4 mt-0.5 sm:mt-0 rounded text-emerald-700 border-slate-300 focus:ring-emerald-500 flex-shrink-0 cursor-pointer">
<div class="min-w-0">
<span class="block truncate font-extrabold text-slate-900 text-xs">{{ $st->name }}</span>
<span class="block text-[10px] font-mono text-slate-400 font-semibold">{{ $st->code }}</span>
</div>
</label>
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase flex-shrink-0" title="{{ $st->category_scope_display }}">
{{ $st->category_scope_display }}
<span class="text-[9px] font-mono px-2 py-0.5 rounded-md bg-slate-200 text-slate-700 font-bold uppercase max-w-[140px] sm:max-w-[200px] truncate flex-shrink-0" title="{{ $st->category_scope_display }}">
{{ $st->short_scope_display ?? $st->category_scope_display }}
</span>
</div>
<div id="editSimperFields_{{ $st->id }}" class="hidden grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2 pt-2 border-t border-slate-200/60">
@@ -1120,13 +1206,32 @@
function toggleAddSimperFields(id) {
const check = document.getElementById(`addSimperCheck_${id}`);
const fields = document.getElementById(`addSimperFields_${id}`);
const numInp = document.getElementById(`addSimperNum_${id}`);
const expInp = document.getElementById(`addSimperExp_${id}`);
const todayStr = new Date().toISOString().split('T')[0];
if (check && fields) {
if (check.checked) {
fields.classList.remove('hidden');
if (numInp) numInp.disabled = false;
if (expInp) {
expInp.disabled = false;
expInp.required = true;
expInp.min = todayStr;
if (!expInp.value) {
const d = new Date();
d.setFullYear(d.getFullYear() + 1);
expInp.value = d.toISOString().split('T')[0];
}
}
} else {
fields.classList.add('hidden');
const expInp = document.getElementById(`addSimperExp_${id}`);
if (expInp) expInp.value = '';
if (numInp) numInp.disabled = true;
if (expInp) {
expInp.disabled = true;
expInp.required = false;
expInp.value = '';
}
}
}
syncAddPrimarySimperDate();
@@ -1152,13 +1257,32 @@
function toggleEditSimperFields(id) {
const check = document.getElementById(`editSimperCheck_${id}`);
const fields = document.getElementById(`editSimperFields_${id}`);
const numInp = document.getElementById(`editSimperNum_${id}`);
const expInp = document.getElementById(`editSimperExp_${id}`);
const todayStr = new Date().toISOString().split('T')[0];
if (check && fields) {
if (check.checked) {
fields.classList.remove('hidden');
if (numInp) numInp.disabled = false;
if (expInp) {
expInp.disabled = false;
expInp.required = true;
expInp.min = todayStr;
if (!expInp.value) {
const d = new Date();
d.setFullYear(d.getFullYear() + 1);
expInp.value = d.toISOString().split('T')[0];
}
}
} else {
fields.classList.add('hidden');
const expInp = document.getElementById(`editSimperExp_${id}`);
if (expInp) expInp.value = '';
if (numInp) numInp.disabled = true;
if (expInp) {
expInp.disabled = true;
expInp.required = false;
expInp.value = '';
}
}
}
syncEditPrimarySimperDate();
@@ -1248,9 +1372,9 @@
const fields = document.getElementById(`editSimperFields_${id}`);
if (fields) fields.classList.add('hidden');
const num = document.getElementById(`editSimperNum_${id}`);
if (num) num.value = '';
if (num) { num.value = ''; num.disabled = true; }
const exp = document.getElementById(`editSimperExp_${id}`);
if (exp) exp.value = '';
if (exp) { exp.value = ''; exp.disabled = true; }
});
// Isi checklist SIMPER dari data emp.simpers
@@ -1263,8 +1387,8 @@
if (cb) {
cb.checked = true;
if (fields) fields.classList.remove('hidden');
if (num) num.value = s.simper_number || '';
if (exp && s.expired_at) exp.value = s.expired_at.substring(0, 10);
if (num) { num.value = s.simper_number || ''; num.disabled = false; }
if (exp && s.expired_at) { exp.value = s.expired_at.substring(0, 10); exp.disabled = false; }
}
});
} else if (emp.is_operator && expDate) {
@@ -1274,8 +1398,10 @@
const id = firstCb.id.replace('editSimperCheck_', '');
const fields = document.getElementById(`editSimperFields_${id}`);
if (fields) fields.classList.remove('hidden');
const num = document.getElementById(`editSimperNum_${id}`);
if (num) num.disabled = false;
const exp = document.getElementById(`editSimperExp_${id}`);
if (exp) exp.value = expDate;
if (exp) { exp.value = expDate; exp.disabled = false; }
}
}
syncEditPrimarySimperDate();
@@ -1320,28 +1446,310 @@
document.getElementById('editForm').action = `/hse/employees/${emp.id}`;
document.getElementById('editModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
document.body.classList.add('modal-open');
}
function closeEditModal() {
const modal = document.getElementById('editModal');
if (modal) modal.classList.add('hidden');
if (modal) {
modal.classList.add('hidden');
document.documentElement.classList.remove('modal-open');
document.body.classList.remove('modal-open');
}
}
function openRenewModal(id, name, expiredDate, isOperator) {
document.getElementById('renewName').textContent = name;
document.getElementById('renewOperator').value = isOperator ? '1' : '0';
document.getElementById('renewDate').value = expiredDate;
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');
+188 -28
View File
@@ -165,8 +165,13 @@
onclick="switchP2hSection('{{ $secKey }}')"
id="p2h-tab-{{ $secKey }}"
data-section-key="{{ $secKey }}"
class="p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 {{ $isFirst ? 'bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]' : 'bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300' }}">
data-section-index="{{ $loop->index }}"
class="p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 {{ $isFirst ? 'bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]' : 'bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300' }}">
<span class="step-num text-[10px] font-mono opacity-80">#{{ $loop->iteration }}</span>
<span>{{ $sectionName }}</span>
<span id="tab-check-{{ $secKey }}" class="tab-check-icon hidden text-emerald-400 font-black">
<i class="fa-solid fa-circle-check text-[11px]"></i>
</span>
</button>
@endforeach
</div>
@@ -213,13 +218,13 @@
</div>
@if(in_array($item->question_type, ['choice', 'condition', 'Multiple choice: only one answer', 'Matrix']))
<!-- Opsi Jawaban Radio: Baik & Rusak -->
<!-- Opsi Jawaban Radio: Baik & Rusak (Kosongan secara Default, Wajib Dipilih Operator) -->
<div class="flex items-center space-x-2 flex-shrink-0">
<label class="cursor-pointer">
<input type="radio"
name="items[{{ $item->id }}][condition]"
value="baik"
checked
{{ old("items.{$item->id}.condition") === 'baik' ? 'checked' : '' }}
onchange="handleConditionChange({{ $item->id }}, 'baik')"
class="peer sr-only">
<span class="inline-flex items-center justify-center min-w-[62px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-[#1b5e20] peer-checked:text-white peer-checked:border-[#1b5e20] peer-checked:shadow-sm transition">
@@ -231,6 +236,7 @@
<input type="radio"
name="items[{{ $item->id }}][condition]"
value="rusak"
{{ old("items.{$item->id}.condition") === 'rusak' ? 'checked' : '' }}
onchange="handleConditionChange({{ $item->id }}, 'rusak')"
class="peer sr-only">
<span class="inline-flex items-center justify-center space-x-1.5 min-w-[68px] px-3.5 py-1.5 rounded-xl text-xs font-bold border border-slate-300 text-slate-600 bg-white peer-checked:bg-rose-600 peer-checked:text-white peer-checked:border-rose-600 peer-checked:shadow-sm transition">
@@ -289,15 +295,15 @@
@endforeach
</div>
<!-- Navigasi Cepat Antar Section (Sebelumnya & Selanjutnya) -->
<!-- Navigasi Wizard Bertahap Antar Section -->
@if(count($groupedItems) > 1)
<div class="px-4 py-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between">
@if($prevKey)
<button type="button"
onclick="switchP2hSection('{{ $prevKey }}')"
class="inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-100 transition shadow-2xs cursor-pointer">
class="inline-flex items-center space-x-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold text-slate-600 hover:text-slate-900 bg-white border border-slate-200 hover:bg-slate-100 transition shadow-2xs cursor-pointer">
<i class="fa-solid fa-chevron-left text-[10px]"></i>
<span>Bagian Sebelumnya</span>
<span>Kembali</span>
</button>
@else
<div></div>
@@ -305,15 +311,18 @@
@if($nextKey)
<button type="button"
onclick="switchP2hSection('{{ $nextKey }}')"
class="inline-flex items-center space-x-1.5 px-3 py-1.5 rounded-lg text-xs font-bold text-emerald-800 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition shadow-2xs cursor-pointer">
<span>Bagian Selanjutnya</span>
onclick="completeAndNextSection('{{ $secKey }}', '{{ $nextKey }}')"
class="inline-flex items-center space-x-1.5 px-4 py-2 rounded-xl text-xs font-bold text-white bg-[#1b5e20] hover:bg-[#144918] transition shadow-xs cursor-pointer">
<span>Selesaikan Bagian Ini & Lanjut</span>
<i class="fa-solid fa-chevron-right text-[10px]"></i>
</button>
@else
<span class="text-[11px] font-semibold text-slate-400 flex items-center">
<i class="fa-solid fa-flag-checkered mr-1.5 text-emerald-600"></i> Bagian Terakhir
</span>
<button type="button"
onclick="markLastSectionComplete('{{ $secKey }}')"
class="inline-flex items-center space-x-1.5 px-4 py-2 rounded-xl text-xs font-bold text-emerald-800 bg-emerald-100 hover:bg-emerald-200 border border-emerald-300 transition shadow-xs cursor-pointer">
<i class="fa-solid fa-circle-check text-xs"></i>
<span>Selesaikan Pemeriksaan Bagian Terakhir</span>
</button>
@endif
</div>
@endif
@@ -324,24 +333,36 @@
<!-- Card Catatan Umum Operator -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 space-y-3">
<label for="general_notes" class="block text-xs font-bold uppercase tracking-wider text-slate-700">
Catatan Umum / Keterangan Tambahan Operator
<label for="general_notes" class="flex items-center justify-between text-xs font-bold uppercase tracking-wider text-slate-700">
<span>Catatan Umum / Keterangan Tambahan Operator</span>
<span class="text-[10px] font-medium text-slate-400 normal-case italic">(opsional / boleh dikosongkan)</span>
</label>
<textarea name="general_notes" id="general_notes" rows="3" placeholder="Tuliskan temuan atau catatan umum lainnya mengenai kondisi Heavy Equipment hari ini..." class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-xs text-slate-800 focus:border-emerald-500 focus:ring-4 focus:ring-emerald-500/10 transition resize-none">{{ old('general_notes') }}</textarea>
</div>
<!-- Tombol Aksi Submit -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 flex items-center justify-between gap-3">
<a href="{{ route('p2h.index') }}" class="bg-slate-100 hover:bg-slate-200 text-slate-600 font-semibold py-2.5 px-4 rounded-xl transition text-xs">
Batal
</a>
<!-- Card Tombol Aksi Submit P2H (Aktif Setelah Seluruh Bagian Ditinjau) -->
<div id="p2hSubmitCard" class="bg-white rounded-2xl shadow-sm border border-slate-200 p-4 sm:p-5 transition-all">
<div id="p2hPendingNotice" class="{{ count($groupedItems) > 1 ? '' : 'hidden' }} flex items-center justify-between text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded-xl p-3 mb-3">
<div class="flex items-center gap-2">
<i class="fa-solid fa-circle-info text-amber-600 text-sm"></i>
<span>Harap selesaikan pemeriksaan pada seluruh bagian (section) di atas untuk memunculkan tombol pengiriman formulir P2H ke QMA.</span>
</div>
</div>
<button type="submit"
id="btnSubmitP2h"
class="bg-[#1b5e20] hover:bg-[#144918] active:scale-[0.99] text-white font-bold py-2.5 px-6 rounded-xl shadow-sm hover:shadow transition flex items-center space-x-2 text-xs sm:text-sm cursor-pointer">
<i class="fa-solid fa-paper-plane text-xs"></i>
<span>Kirim Formulir P2H ke QMA</span>
</button>
<div class="flex items-center justify-between gap-3">
<a href="{{ route('p2h.index') }}" class="bg-slate-100 hover:bg-slate-200 text-slate-600 font-semibold py-2.5 px-4 rounded-xl transition text-xs">
Batal
</a>
<div id="p2hSubmitBtnContainer" class="{{ count($groupedItems) > 1 ? 'hidden' : '' }}">
<button type="submit"
id="btnSubmitP2h"
class="bg-[#1b5e20] hover:bg-[#144918] active:scale-[0.99] text-white font-bold py-2.5 px-6 rounded-xl shadow-sm hover:shadow transition flex items-center space-x-2 text-xs sm:text-sm cursor-pointer">
<i class="fa-solid fa-paper-plane text-xs"></i>
<span>Kirim Formulir P2H ke QMA</span>
</button>
</div>
</div>
</div>
</form>
</div>
@@ -349,20 +370,26 @@
@section('scripts')
<script>
const allSectionKeys = @json($sectionKeys);
const completedSections = {};
function switchP2hSection(secKey) {
// 1. Update tab styling
const allTabs = document.querySelectorAll('.p2h-section-tab');
allTabs.forEach(tab => {
const key = tab.dataset.sectionKey;
const isCompleted = !!completedSections[key];
if (key === secKey) {
tab.className = 'p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]';
tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-[#1b5e20] text-white shadow-xs border border-[#1b5e20]';
tab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
} else if (isCompleted) {
tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-emerald-50 border border-emerald-200 text-emerald-800 hover:bg-emerald-100';
} else {
tab.className = 'p2h-section-tab group inline-flex items-center px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300';
tab.className = 'p2h-section-tab group inline-flex items-center space-x-1.5 px-4 py-2.5 rounded-xl text-xs font-bold transition whitespace-nowrap cursor-pointer shrink-0 bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 hover:border-slate-300';
}
});
// 2. Show active panel, hide others
// 2. Tampilkan panel aktif, sembunyikan lainnya
const allPanels = document.querySelectorAll('.p2h-section-content');
allPanels.forEach(panel => {
if (panel.id === 'p2h-content-' + secKey) {
@@ -371,6 +398,102 @@
panel.classList.add('hidden');
}
});
checkAllSectionsCompleted();
}
function validateSectionNotes(secKey) {
const panel = document.getElementById('p2h-content-' + secKey);
if (!panel) return true;
// 1. Validasi: Pastikan setiap butir pemeriksaan radio di bagian ini telah dipilih (Baik / Rusak)
const radioRows = panel.querySelectorAll('.p2h-item-card');
for (const row of radioRows) {
const radios = row.querySelectorAll('input[type="radio"]');
if (radios.length > 0) {
const isSelected = Array.from(radios).some(r => r.checked);
if (!isSelected) {
row.scrollIntoView({ behavior: 'smooth', block: 'center' });
row.classList.add('ring-2', 'ring-rose-500', 'bg-rose-50/50');
setTimeout(() => {
row.classList.remove('ring-2', 'ring-rose-500', 'bg-rose-50/50');
}, 3500);
alert('Harap periksa dan tentukan kondisi (Baik atau Rusak) untuk seluruh butir pemeriksaan pada bagian ini.');
return false;
}
}
}
// 2. Validasi: Jika ada yang rusak, wajib diisi catatan penjelasannya
const damagedRadios = panel.querySelectorAll('input[type="radio"][value="rusak"]:checked');
for (const radio of damagedRadios) {
const match = radio.name.match(/items\[(\d+)\]/);
if (match && match[1]) {
const notesInput = panel.querySelector(`input[name="items[${match[1]}][notes]"]`);
if (notesInput && !notesInput.value.trim()) {
notesInput.focus();
alert('Mohon isi catatan kerusakan pada butir yang Anda tandai "Rusak" sebelum melanjutkan.');
return false;
}
}
}
return true;
}
function completeAndNextSection(currentKey, nextKey) {
if (!validateSectionNotes(currentKey)) {
return;
}
completedSections[currentKey] = true;
const checkIcon = document.getElementById('tab-check-' + currentKey);
if (checkIcon) checkIcon.classList.remove('hidden');
switchP2hSection(nextKey);
}
function markLastSectionComplete(lastSecKey) {
if (!validateSectionNotes(lastSecKey)) {
return;
}
completedSections[lastSecKey] = true;
const checkIcon = document.getElementById('tab-check-' + lastSecKey);
if (checkIcon) checkIcon.classList.remove('hidden');
checkAllSectionsCompleted();
// Gulir halus ke tombol kirim di bawah
const submitCard = document.getElementById('p2hSubmitCard');
if (submitCard) {
submitCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
function checkAllSectionsCompleted() {
if (!allSectionKeys || allSectionKeys.length <= 1) {
showSubmitButton();
return;
}
let allDone = true;
for (const key of allSectionKeys) {
if (!completedSections[key]) {
allDone = false;
break;
}
}
if (allDone) {
showSubmitButton();
}
}
function showSubmitButton() {
const container = document.getElementById('p2hSubmitBtnContainer');
const notice = document.getElementById('p2hPendingNotice');
if (container) container.classList.remove('hidden');
if (notice) notice.classList.add('hidden');
}
function handleConditionChange(itemId, condition) {
@@ -396,5 +519,42 @@
}
});
}
// Inisialisasi awal & proteksi submit form
document.addEventListener('DOMContentLoaded', function() {
if (!allSectionKeys || allSectionKeys.length <= 1) {
showSubmitButton();
}
const form = document.getElementById('p2hForm');
if (form) {
form.addEventListener('submit', function(e) {
const unselectedCards = [];
document.querySelectorAll('.p2h-item-card').forEach(row => {
const radios = row.querySelectorAll('input[type="radio"]');
if (radios.length > 0 && !Array.from(radios).some(r => r.checked)) {
unselectedCards.push(row);
}
});
if (unselectedCards.length > 0) {
e.preventDefault();
const firstUnselected = unselectedCards[0];
const panel = firstUnselected.closest('.p2h-section-content');
if (panel) {
const secKey = panel.id.replace('p2h-content-', '');
switchP2hSection(secKey);
}
firstUnselected.scrollIntoView({ behavior: 'smooth', block: 'center' });
firstUnselected.classList.add('ring-2', 'ring-rose-500', 'bg-rose-50/50');
setTimeout(() => {
firstUnselected.classList.remove('ring-2', 'ring-rose-500', 'bg-rose-50/50');
}, 3500);
alert(`Terdapat ${unselectedCards.length} butir pemeriksaan yang belum dipilih. Harap tentukan kondisi (Baik / Rusak) untuk seluruh butir sebelum mengirim formulir.`);
return false;
}
});
}
});
</script>
@endsection
+137 -3
View File
@@ -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
+7 -3
View File
@@ -374,10 +374,14 @@
<form id="editGuardForm" method="POST" action="" class="mt-5 space-y-4">
@csrf
<!-- ID Satpam (Read-only) -->
<!-- ID Satpam (Username Login) -->
<div>
<label class="block text-sm font-bold text-slate-800 mb-2">ID Satpam (Username Login)</label>
<input type="text" id="editBadgeId" disabled class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-slate-100 text-slate-600 font-mono font-bold">
<label for="editBadgeId" class="block text-sm font-bold text-slate-800 mb-2">
ID Satpam (Username Login) <span class="text-rose-500">*</span>
</label>
<input type="text" name="badge_id" id="editBadgeId" required placeholder="Contoh: SEC-001"
class="w-full text-sm px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-800 font-mono font-bold placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition">
<p class="text-[11px] text-slate-400 mt-1">Mengubah ID Satpam otomatis memperbarui username login dan NIK Karyawan.</p>
</div>
<!-- Nama Lengkap -->
@@ -113,32 +113,41 @@
</div>
@endif
<!-- Baris 4: Tombol Verifikasi Langsung di Card (Tanpa Popup & Tanpa Fitur Tolak) -->
<!-- Baris 4: Tombol Aksi Verifikasi & Tolak Perjalanan -->
<div class="mt-3.5 pt-3 border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-2.5">
<span class="text-[11px] text-slate-400 font-medium hidden sm:inline flex items-center gap-1.5">
<i class="fa-solid fa-shield-check text-[#1b5e20]"></i>
<span>Cek fisik kendaraan lalu klik verifikasi untuk membuka portal</span>
<span>Cek fisik kendaraan lalu pilih verifikasi atau tolak</span>
</span>
@can('gate.approve')
<form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-full sm:w-auto m-0">
@csrf
@if($currentGuard)
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}">
@elseif($guards->isNotEmpty())
<input type="hidden" name="security_guard_id" value="{{ $guards->first()->id }}">
@endif
<button type="submit"
onclick="this.disabled=true; this.innerHTML='<i class=\'fa-solid fa-spinner fa-spin text-xs\'></i> Memverifikasi...'; this.form.submit();"
class="w-full sm:w-auto px-6 py-2.5 bg-[#1b5e20] hover:bg-[#144919] active:bg-[#0f3613] text-white font-bold text-xs sm:text-sm rounded-xl shadow-xs hover:shadow transition flex items-center justify-center space-x-2 cursor-pointer">
<i class="fa-solid fa-clipboard-check text-sm"></i>
<span>Verifikasi</span>
<div class="flex items-center gap-2 w-full sm:w-auto">
@can('gate.reject')
<button type="button"
onclick="openRejectModal({{ $act->id }}, '{{ addslashes($act->vehicle->code . ' (' . ($act->vehicle->license_plate ?? 'Tanpa Plat') . ')') }}', '{{ addslashes($act->driver->name ?? 'Pengemudi') }}', '{{ strtolower($act->direction) }}')"
class="w-1/2 sm:w-auto px-4 py-2.5 bg-rose-50 hover:bg-rose-100 active:bg-rose-200 text-rose-700 border border-rose-200 font-bold text-xs sm:text-sm rounded-xl transition flex items-center justify-center space-x-1.5 cursor-pointer shadow-2xs">
<i class="fa-solid fa-ban text-xs"></i>
<span>Tolak</span>
</button>
</form>
@else
<span class="text-xs text-slate-400 italic">Tidak memiliki izin verifikasi</span>
@endcan
@endcan
@can('gate.approve')
<form action="{{ route('pg.gate.approve', $act->id) }}" method="POST" class="w-1/2 sm:w-auto m-0">
@csrf
@if($currentGuard)
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}">
@elseif($guards->isNotEmpty())
<input type="hidden" name="security_guard_id" value="{{ $guards->first()->id }}">
@endif
<button type="submit"
onclick="this.disabled=true; this.innerHTML='<i class=\'fa-solid fa-spinner fa-spin text-xs\'></i> Memverifikasi...'; this.form.submit();"
class="w-full sm:w-auto px-6 py-2.5 bg-[#1b5e20] hover:bg-[#144919] active:bg-[#0f3613] text-white font-bold text-xs sm:text-sm rounded-xl shadow-xs hover:shadow transition flex items-center justify-center space-x-2 cursor-pointer">
<i class="fa-solid fa-clipboard-check text-sm"></i>
<span>Verifikasi</span>
</button>
</form>
@endcan
</div>
</div>
</div>
@@ -658,7 +658,6 @@
}, 500);
});
});
});
// Panduan Halaman Modal
function openGuideModal() {
+294 -180
View File
@@ -301,11 +301,23 @@
</div>
</td>
<!-- Odometer Awal -->
<!-- Odometer Awal & Akhir -->
<td class="py-3.5 px-4 text-center font-mono whitespace-nowrap">
<span class="text-xs font-bold text-slate-900 bg-slate-100 px-2.5 py-1 rounded-lg border border-slate-200">
{{ number_format($ts->start_meter, 1, ',', '.') }} {{ $ts->meter_type }}
</span>
<div class="text-xs font-bold text-slate-900 bg-slate-100 px-2.5 py-1 rounded-lg border border-slate-200 inline-block">
{{ number_format($ts->start_meter, 1, ',', '.') }} {{ $ts->meter_type }}@if($ts->effective_end_meter) <span class="text-slate-400 font-normal">s/d</span> <span class="text-emerald-700">{{ number_format($ts->effective_end_meter, 1, ',', '.') }} {{ $ts->meter_type }}</span>@endif
</div>
@if($ts->effective_operating_hours !== null && $ts->effective_operating_hours > 0)
<div class="text-[10px] text-emerald-700 font-semibold font-sans mt-0.5">
+{{ number_format($ts->effective_operating_hours, 1, ',', '.') }} Jam Operasi
</div>
@elseif($ts->effective_end_meter)
<div class="text-[10px] text-slate-400 font-sans mt-0.5">0.0 Jam</div>
@else
<div class="text-[10px] text-amber-600 font-sans mt-0.5 flex items-center justify-center gap-1">
<span class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
<span>Berjalan (Finish Otomatis)</span>
</div>
@endif
</td>
<!-- Lokasi & Aktivitas -->
@@ -361,9 +373,9 @@
'operator_type' => $ts->operator?->employee_type ?: 'Karyawan',
'operator_nik' => $ts->operator?->nik ?: '-',
'start_meter' => number_format($ts->start_meter, 1, ',', '.'),
'end_meter' => number_format($ts->end_meter, 1, ',', '.'),
'end_meter' => $ts->effective_end_meter !== null ? number_format($ts->effective_end_meter, 1, ',', '.') : '-',
'meter_type' => $ts->meter_type,
'operating_hours' => number_format($ts->operating_hours, 1, ',', '.'),
'operating_hours' => $ts->effective_operating_hours !== null ? number_format($ts->effective_operating_hours, 1, ',', '.') : '-',
'standby_hours' => number_format($ts->standby_hours, 1, ',', '.'),
'breakdown_hours' => number_format($ts->breakdown_hours, 1, ',', '.'),
'fuel_liters' => $ts->fuel_liters ? number_format($ts->fuel_liters, 0, ',', '.') : '-',
@@ -479,37 +491,37 @@
<!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Lokasi Kerja <span class="text-rose-500">*</span>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Lokasi Kerja <span class="text-rose-500">*</span></span>
<span class="sr-only">Tentukan Lokasi Dulu</span>
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
</label>
<select id="addLocationSelect"
required
onchange="onTimesheetLocationChanged(this.value, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@if(isset($otherLocations) && count($otherLocations))
<optgroup label="Lokasi Lainnya di Site">
@foreach($otherLocations as $otherLoc)
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
@endforeach
</optgroup>
@endif
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
</select>
<div id="addCustomLocationWrapper" class="hidden mt-2">
<div class="relative">
<input type="text"
id="addCustomLocationInput"
name="custom_location"
placeholder="Ketik nama lokasi kerja baru..."
oninput="onCustomLocationTyped(this.value, 'add')"
class="w-full text-xs px-3.5 py-2 rounded-xl border border-emerald-300 bg-emerald-50/40 text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20]">
id="addLocationInput"
name="location"
list="addLocationsDatalist"
required
autocomplete="off"
placeholder="Pilih atau ketik lokasi kerja..."
oninput="onTimesheetLocationTyped(this.value, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<datalist id="addLocationsDatalist">
<option value="[Semua Unit]">[Semua Lokasi / Tampilkan Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@foreach($locationSuggestions as $suggLoc)
@if(!isset($unitLocations[$suggLoc]))
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
@endif
@endforeach
</datalist>
</div>
<input type="hidden" name="location" id="addFinalLocation" required>
<input type="hidden" id="addFinalLocation" value="">
<p class="text-[10px] text-slate-400 mt-1">
Pilih dari daftar atau ketik lokasi baru (otomatis tersimpan ke database).
</p>
</div>
<div>
@@ -517,13 +529,27 @@
<span>Heavy Equipment <span class="text-rose-500">*</span></span>
<span id="addUnitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
</label>
<select name="vehicle_id"
id="addVehicleSelect"
required
onchange="onVehicleSelectChanged(this, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>
</select>
<div class="space-y-1.5">
<div class="relative">
<i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="addVehicleSearch"
placeholder="Ketik untuk filter unit (kode / merek)..."
oninput="filterTimesheetVehicleOptions(this.value, 'add')"
autocomplete="off"
class="w-full pl-8 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
<button type="button" onclick="clearTimesheetVehicleFilter('add')" id="clearAddVehicleSearchBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
<i class="fa-solid fa-xmark text-xs"></i>
</button>
</div>
<select name="vehicle_id"
id="addVehicleSelect"
required
onchange="onVehicleSelectChanged(this, 'add')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>
</select>
</div>
<div id="addVehiclePreview" class="hidden mt-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-200/80 text-[11px] text-emerald-900 flex items-center justify-between">
<span id="addVehiclePreviewText" class="font-bold"></span>
<span id="addVehicleLastKmText" class="text-emerald-700 font-mono text-[10px]"></span>
@@ -626,7 +652,7 @@
</div>
</div>
<!-- Baris 4: Meter Awal & Satuan Meteran -->
<!-- Baris 4: Meter Awal & Meter Akhir (Finish HM) -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
@@ -644,6 +670,28 @@
</div>
</div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Meter Akhir (Finish HM/KM)</span>
<span class="text-[10px] text-emerald-700 font-semibold">Otomatis / Opsional</span>
</label>
<div class="relative">
<input type="number"
step="0.01"
name="end_meter"
id="addEndMeter"
placeholder="Dihitung otomatis jika kosong"
class="w-full text-xs pl-3.5 pr-14 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<span id="addEndMeterUnitLabel" class="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs font-extrabold text-slate-400">HM</span>
</div>
<p class="text-[10px] text-slate-400 mt-1">
<i class="fa-solid fa-clock text-emerald-600 mr-0.5"></i> 1 HM = 1 Jam. Dihitung otomatis saat entri berikutnya diinput.
</p>
</div>
</div>
<!-- Baris 4b: Satuan Meteran & Status Akhir Unit -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Satuan Meteran <span class="text-rose-500">*</span>
@@ -653,21 +701,21 @@
<option value="KM">KM (Odometer)</option>
</select>
</div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
</div>
<!-- Baris 5: Status Akhir Unit (Shift diset otomatis) -->
<input type="hidden" name="shift" value="Shift Siang">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
<!-- Baris 6: Rincian Tugas & Catatan -->
<div>
@@ -811,37 +859,37 @@
<!-- Baris 1: Lokasi Kerja & Heavy Equipment -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Lokasi Kerja <span class="text-rose-500">*</span>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Lokasi Kerja <span class="text-rose-500">*</span></span>
<span class="sr-only">Tentukan Lokasi Dulu</span>
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / pilih</span>
</label>
<select id="editLocationSelect"
required
onchange="onTimesheetLocationChanged(this.value, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja --</option>
<option value="ALL">[Semua Lokasi / Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@if(isset($otherLocations) && count($otherLocations))
<optgroup label="Lokasi Lainnya di Site">
@foreach($otherLocations as $otherLoc)
<option value="{{ $otherLoc }}">{{ $otherLoc }} (0 Unit)</option>
@endforeach
</optgroup>
@endif
<option value="__CUSTOM__">+ Ketik Lokasi Baru...</option>
</select>
<div id="editCustomLocationWrapper" class="hidden mt-2">
<div class="relative">
<input type="text"
id="editCustomLocationInput"
name="custom_location"
placeholder="Ketik nama lokasi kerja baru..."
oninput="onCustomLocationTyped(this.value, 'edit')"
class="w-full text-xs px-3.5 py-2 rounded-xl border border-emerald-300 bg-emerald-50/40 text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20]">
id="editLocationInput"
name="location"
list="editLocationsDatalist"
required
autocomplete="off"
placeholder="Pilih atau ketik lokasi kerja..."
oninput="onTimesheetLocationTyped(this.value, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<datalist id="editLocationsDatalist">
<option value="[Semua Unit]">[Semua Lokasi / Tampilkan Semua Unit]</option>
@foreach($unitLocations as $locName => $count)
<option value="{{ $locName }}">{{ $locName }} ({{ $count }} Unit Ready)</option>
@endforeach
@foreach($locationSuggestions as $suggLoc)
@if(!isset($unitLocations[$suggLoc]))
<option value="{{ $suggLoc }}">{{ $suggLoc }}</option>
@endif
@endforeach
</datalist>
</div>
<input type="hidden" name="location" id="editFinalLocation" required>
<input type="hidden" id="editFinalLocation" value="">
<p class="text-[10px] text-slate-400 mt-1">
Pilih dari daftar atau ketik lokasi baru (otomatis tersimpan).
</p>
</div>
<div>
@@ -849,13 +897,27 @@
<span>Heavy Equipment <span class="text-rose-500">*</span></span>
<span id="editUnitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
</label>
<select name="vehicle_id"
id="editVehicleSelect"
required
onchange="onVehicleSelectChanged(this, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>
</select>
<div class="space-y-1.5">
<div class="relative">
<i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="editVehicleSearch"
placeholder="Ketik untuk filter unit (kode / merek)..."
oninput="filterTimesheetVehicleOptions(this.value, 'edit')"
autocomplete="off"
class="w-full pl-8 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
<button type="button" onclick="clearTimesheetVehicleFilter('edit')" id="clearEditVehicleSearchBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
<i class="fa-solid fa-xmark text-xs"></i>
</button>
</div>
<select name="vehicle_id"
id="editVehicleSelect"
required
onchange="onVehicleSelectChanged(this, 'edit')"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>
</select>
</div>
<div id="editVehiclePreview" class="hidden mt-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-200/80 text-[11px] text-emerald-900 flex items-center justify-between">
<span id="editVehiclePreviewText" class="font-bold"></span>
<span id="editVehicleLastKmText" class="text-emerald-700 font-mono text-[10px]"></span>
@@ -956,7 +1018,7 @@
</div>
</div>
<!-- Baris 4: Meter Awal & Satuan Meteran -->
<!-- Baris 4: Meter Awal & Meter Akhir (Finish HM) -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
@@ -974,6 +1036,28 @@
</div>
</div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Meter Akhir (Finish HM/KM)</span>
<span class="text-[10px] text-emerald-700 font-semibold">Otomatis / Opsional</span>
</label>
<div class="relative">
<input type="number"
step="0.01"
name="end_meter"
id="editEndMeter"
placeholder="Dihitung otomatis jika kosong"
class="w-full text-xs pl-3.5 pr-14 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-mono font-bold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<span id="editEndMeterUnitLabel" class="absolute right-3.5 top-1/2 -translate-y-1/2 text-xs font-extrabold text-slate-400">HM</span>
</div>
<p class="text-[10px] text-slate-400 mt-1">
<i class="fa-solid fa-clock text-emerald-600 mr-0.5"></i> 1 HM = 1 Jam. Dihitung otomatis saat entri berikutnya diinput.
</p>
</div>
</div>
<!-- Baris 4b: Satuan Meteran & Status Akhir Unit -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Satuan Meteran <span class="text-rose-500">*</span>
@@ -983,21 +1067,22 @@
<option value="KM">KM (Odometer)</option>
</select>
</div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" id="editStatus" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
</div>
<!-- Baris 5: Status Akhir Unit (Shift disimpan secara otomatis) -->
<!-- Baris 5: Shift (disimpan otomatis) -->
<input type="hidden" name="shift" id="editShift" value="Shift Siang">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
Status Akhir Unit <span class="text-rose-500">*</span>
</label>
<select name="status" id="editStatus" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="Operation">Operation (Siap Jalan)</option>
<option value="Standby">Standby (Tersedia / Siaga)</option>
<option value="Breakdown">Breakdown (Kendala / Rusak)</option>
<option value="Maintenance">Maintenance (Servis Rutin)</option>
</select>
</div>
<!-- Baris 6: Deskripsi & Catatan -->
<div>
@@ -1318,23 +1403,15 @@
const modal = document.getElementById('addTimesheetModal');
if (modal) {
// Reset form pilihan lokasi & unit
const addLocSelect = document.getElementById('addLocationSelect');
if (addLocSelect) addLocSelect.selectedIndex = 0;
const customWrap = document.getElementById('addCustomLocationWrapper');
if (customWrap) customWrap.classList.add('hidden');
const customInput = document.getElementById('addCustomLocationInput');
if (customInput) customInput.value = '';
const addLocInput = document.getElementById('addLocationInput');
if (addLocInput) addLocInput.value = '';
const finalLoc = document.getElementById('addFinalLocation');
if (finalLoc) finalLoc.value = '';
const vehSelect = document.getElementById('addVehicleSelect');
if (vehSelect) {
vehSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
}
const counter = document.getElementById('addUnitCounterBadge');
if (counter) counter.classList.add('hidden');
const preview = document.getElementById('addVehiclePreview');
if (preview) preview.classList.add('hidden');
const endMeter = document.getElementById('addEndMeter');
if (endMeter) endMeter.value = '';
onTimesheetLocationTyped('', 'add');
const startMeter = document.getElementById('addStartMeter');
if (startMeter) startMeter.value = '';
@@ -1424,37 +1501,14 @@
document.getElementById('editTimesheetSubtitle').textContent = `No: ${ts.timesheet_no} (${unitCode || '-'})`;
// 1. Sinkronisasi Lokasi Kerja
const locSelect = document.getElementById('editLocationSelect');
const locInput = document.getElementById('editLocationInput');
const finalLoc = document.getElementById('editFinalLocation');
const customWrap = document.getElementById('editCustomLocationWrapper');
const targetLoc = ts.location || '';
finalLoc.value = targetLoc;
let matched = false;
if (locSelect) {
for (let i = 0; i < locSelect.options.length; i++) {
if (locSelect.options[i].value.toLowerCase() === targetLoc.toLowerCase()) {
locSelect.selectedIndex = i;
matched = true;
break;
}
}
if (!matched && targetLoc) {
// Tambahkan option lokasi baru jika belum terdaftar
const newOpt = document.createElement('option');
newOpt.value = targetLoc;
newOpt.textContent = `${targetLoc} (Lokasi Riwayat)`;
locSelect.appendChild(newOpt);
locSelect.value = targetLoc;
}
}
if (customWrap) customWrap.classList.add('hidden');
if (locInput) locInput.value = targetLoc;
if (finalLoc) finalLoc.value = targetLoc;
// Filter unit pada lokasi ini dengan memilih ts.vehicle_id
onTimesheetLocationChanged(locSelect ? locSelect.value : targetLoc, 'edit', ts.vehicle_id);
onTimesheetLocationTyped(targetLoc, 'edit', ts.vehicle_id);
// Cari jenis operator yang sedang diedit untuk mengaktifkan filter yang sesuai
let selectedOpType = 'all';
@@ -1487,6 +1541,10 @@
document.getElementById('editMeterType').value = ts.meter_type || 'HM';
document.getElementById('editStartMeter').value = ts.start_meter;
const editEndMeter = document.getElementById('editEndMeter');
if (editEndMeter) {
editEndMeter.value = (ts.end_meter && ts.end_meter !== '-') ? ts.end_meter.replace('.', '').replace(',', '.') : '';
}
document.getElementById('editActivityType').value = ts.activity_type;
document.getElementById('editStatus').value = ts.status || 'Operation';
@@ -1520,10 +1578,17 @@
modal.style.display = 'none';
}
// 5. Handler saat Lokasi Kerja Dipilih (Filter Heavy Equipment yang Ready di Lokasi tersebut)
// 5. Handler saat Lokasi Kerja Diketik / Dipilih via Datalist Input
function onTimesheetLocationTyped(val, prefix, preselectVehicleId = null) {
const trimmed = (val || '').trim();
const finalLoc = document.getElementById(`${prefix}FinalLocation`);
if (finalLoc) {
finalLoc.value = (trimmed === '[Semua Unit]' || trimmed === 'ALL') ? '' : trimmed;
}
onTimesheetLocationChanged(trimmed, prefix, preselectVehicleId);
}
function onTimesheetLocationChanged(selectedLoc, prefix, preselectVehicleId = null) {
const customWrapper = document.getElementById(`${prefix}CustomLocationWrapper`);
const customInput = document.getElementById(`${prefix}CustomLocationInput`);
const finalLocation = document.getElementById(`${prefix}FinalLocation`);
const vehicleSelect = document.getElementById(`${prefix}VehicleSelect`);
const counterBadge = document.getElementById(`${prefix}UnitCounterBadge`);
@@ -1531,58 +1596,48 @@
if (!vehicleSelect) return;
// Tangani pilihan custom atau ALL
if (selectedLoc === '__CUSTOM__') {
if (customWrapper) customWrapper.classList.remove('hidden');
if (customInput) {
customInput.focus();
if (finalLocation) finalLocation.value = customInput.value.trim();
}
} else {
if (customWrapper) customWrapper.classList.add('hidden');
if (finalLocation) {
finalLocation.value = (selectedLoc === 'ALL' || !selectedLoc) ? '' : selectedLoc;
}
if (finalLocation) {
finalLocation.value = (selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]' || !selectedLoc) ? '' : selectedLoc;
}
const allUnits = window.unitSupportsData || [];
let filteredUnits = [];
if (!selectedLoc) {
vehicleSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
if (counterBadge) counterBadge.classList.add('hidden');
if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
return;
} else if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
if (!selectedLoc || selectedLoc === 'ALL' || selectedLoc === '[Semua Unit]') {
filteredUnits = allUnits;
} else {
const norm = selectedLoc.trim().toLowerCase();
filteredUnits = allUnits.filter(u => {
const uLoc = (u.location || 'Site Kerinci').trim().toLowerCase();
return uLoc === norm;
return uLoc === norm || uLoc.includes(norm);
});
// Jika lokasi yang diketik adalah lokasi baru, tetap tampilkan semua unit agar bisa dipilih
if (filteredUnits.length === 0) {
filteredUnits = allUnits;
}
}
// Jika dalam mode edit dan preselectVehicleId tidak ditemukan di lokasi ini (misal unit berpindah setelah ts dicatat), sertakan unit tersebut
if (preselectVehicleId) {
const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId));
if (!foundInFiltered) {
const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId));
if (extra) filteredUnits.unshift(extra);
}
// Jika dalam mode edit dan preselectVehicleId tidak ditemukan di lokasi ini, sertakan unit tersebut
if (preselectVehicleId) {
const foundInFiltered = filteredUnits.some(u => String(u.id) === String(preselectVehicleId));
if (!foundInFiltered) {
const extra = allUnits.find(u => String(u.id) === String(preselectVehicleId));
if (extra) filteredUnits.unshift(extra);
}
}
// Update badge counter
if (counterBadge) {
counterBadge.classList.remove('hidden');
if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
counterBadge.textContent = `${filteredUnits.length} Total Unit`;
} else {
counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
}
counterBadge.textContent = `${filteredUnits.length} Unit Ready`;
}
// Reset input filter unit realtime
const vSearch = document.getElementById(`${prefix}VehicleSearch`);
if (vSearch) vSearch.value = '';
const vClear = document.getElementById(`clear${prefix === 'add' ? 'Add' : 'Edit'}VehicleSearchBtn`);
if (vClear) vClear.classList.add('hidden');
// Render option heavy equipment
vehicleSelect.innerHTML = '';
const defaultPrompt = document.createElement('option');
@@ -1590,7 +1645,7 @@
defaultPrompt.disabled = true;
defaultPrompt.textContent = filteredUnits.length > 0
? `-- Pilih Heavy Equipment (${filteredUnits.length} Unit Ready) --`
: `-- Tidak ada unit di lokasi ini (Pilih 'Semua Unit') --`;
: `-- Tidak ada unit (${allUnits.length} Unit Total) --`;
vehicleSelect.appendChild(defaultPrompt);
let hasSelected = false;
@@ -1633,6 +1688,58 @@
}
}
/**
* Filter Realtime Dropdown Heavy Equipment pada Timesheet berdasarkan Ketikan
*/
function filterTimesheetVehicleOptions(query, prefix) {
const select = document.getElementById(`${prefix}VehicleSelect`);
const clearBtn = document.getElementById(`clear${prefix === 'add' ? 'Add' : 'Edit'}VehicleSearchBtn`);
const badge = document.getElementById(`${prefix}UnitCounterBadge`);
if (!select) return;
const q = (query || '').trim().toLowerCase();
if (clearBtn) {
clearBtn.classList.toggle('hidden', !q);
}
let visibleCount = 0;
let firstMatch = null;
Array.from(select.options).forEach(opt => {
if (!opt.value) {
opt.hidden = false;
return;
}
const code = (opt.getAttribute('data-code') || '').toLowerCase();
const brand = (opt.getAttribute('data-brand') || '').toLowerCase();
const loc = (opt.getAttribute('data-location') || '').toLowerCase();
const text = opt.textContent.toLowerCase();
const match = text.includes(q) || code.includes(q) || brand.includes(q) || loc.includes(q);
opt.hidden = !match;
if (match) {
visibleCount++;
if (!firstMatch) firstMatch = opt;
}
});
if (badge) {
badge.classList.remove('hidden');
badge.textContent = q ? `${visibleCount} Unit Cocok` : `${visibleCount} Unit Ready`;
}
if (q && visibleCount === 1 && firstMatch) {
select.value = firstMatch.value;
onVehicleSelectChanged(select, prefix);
}
}
function clearTimesheetVehicleFilter(prefix) {
const input = document.getElementById(`${prefix}VehicleSearch`);
if (input) input.value = '';
filterTimesheetVehicleOptions('', prefix);
}
// 7. Handler saat Heavy Equipment Dipilih
function onVehicleSelectChanged(selectEl, prefix) {
const opt = selectEl.options[selectEl.selectedIndex];
@@ -1670,10 +1777,13 @@
updateMeterUnitLabels(prefix);
}
// Jika lokasi kerja dipilih 'ALL', sinkronkan finalLocation ke lokasi unit
const locSelect = document.getElementById(`${prefix}LocationSelect`);
// Jika lokasi kerja dipilih 'ALL' atau kosong, sinkronkan ke lokasi unit
const locInput = document.getElementById(`${prefix}LocationInput`);
const finalLoc = document.getElementById(`${prefix}FinalLocation`);
if (locSelect && locSelect.value === 'ALL' && finalLoc && !finalLoc.value) {
if (locInput && (!locInput.value || locInput.value === 'ALL' || locInput.value === '[Semua Unit]')) {
locInput.value = unitLocation;
}
if (finalLoc && (!finalLoc.value || finalLoc.value === 'ALL' || finalLoc.value === '[Semua Unit]')) {
finalLoc.value = unitLocation;
}
@@ -1690,6 +1800,10 @@
if (label) {
label.textContent = unit;
}
const endLabel = document.getElementById(`${prefix}EndMeterUnitLabel`);
if (endLabel) {
endLabel.textContent = unit;
}
}
document.getElementById('addMeterType')?.addEventListener('change', () => updateMeterUnitLabels('add'));
@@ -68,29 +68,43 @@
<div>
<label for="origin_location" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Lokasi Awal (Asal Unit) <span class="text-rose-500">*</span></span>
<span class="text-[10px] text-emerald-700 font-semibold">Filter Berdasarkan Posisi</span>
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / filter</span>
</label>
<div class="relative">
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<select name="from_location"
id="origin_location"
required
onchange="onOriginLocationChanged(this.value)"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-bold">
<option value="" disabled {{ empty($selectedOriginLocation) && !old('from_location') ? 'selected' : '' }}>
-- Pilih Lokasi Awal Alat Berat --
</option>
<option value="ALL" {{ old('from_location', $selectedOriginLocation) === 'ALL' ? 'selected' : '' }}>
[Tampilkan Semua Lokasi / Semua Alat Berat]
</option>
@foreach($originLocations as $locName => $count)
<option value="{{ $locName }}" {{ old('from_location', $selectedOriginLocation) === $locName ? 'selected' : '' }}>
{{ $locName }} ({{ $count }} Unit Tersedia)
<div class="space-y-1.5">
<div class="relative">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="originLocationSearch"
placeholder="Ketik untuk memfilter pilihan lokasi asal..."
oninput="filterOriginLocationSelect(this.value)"
autocomplete="off"
class="w-full pl-9 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
<button type="button" onclick="clearOriginLocationFilter()" id="clearOriginLocationFilterBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
<i class="fa-solid fa-xmark text-xs"></i>
</button>
</div>
<div class="relative">
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<select name="from_location"
id="origin_location"
required
onchange="onOriginLocationChanged(this.value)"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-bold">
<option value="" disabled {{ empty($selectedOriginLocation) && !old('from_location') ? 'selected' : '' }}>
-- Pilih Lokasi Awal Alat Berat --
</option>
@endforeach
</select>
<option value="ALL" {{ old('from_location', $selectedOriginLocation) === 'ALL' ? 'selected' : '' }}>
[Tampilkan Semua Lokasi / Semua Alat Berat]
</option>
@foreach($originLocations as $locName => $count)
<option value="{{ $locName }}" {{ old('from_location', $selectedOriginLocation) === $locName ? 'selected' : '' }}>
{{ $locName }} ({{ $count }} Unit Tersedia)
</option>
@endforeach
</select>
</div>
</div>
<p class="text-[10px] text-slate-400 mt-1">Memilih lokasi awal akan memfilter unit alat berat yang berada di titik tersebut.</p>
<p class="text-[10px] text-slate-400 mt-1">Ketik nama lokasi atau pilih dari daftar untuk memfilter unit.</p>
</div>
<!-- PILIH ALAT BERAT YANG AKAN DIPINDAHKAN -->
@@ -99,27 +113,41 @@
<span>Unit Alat Berat yang Dipindahkan <span class="text-rose-500">*</span></span>
<span id="unitCounterBadge" class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 hidden"></span>
</label>
<select name="vehicle_id"
id="vehicle_id"
required
onchange="onHeavyUnitSelected(this)"
class="w-full px-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-semibold">
<option value="" disabled {{ empty($selectedVehicleId) && !old('vehicle_id') ? 'selected' : '' }}>
-- Pilih Lokasi Awal Terlebih Dahulu --
</option>
@foreach($heavyUnits as $unit)
<option value="{{ $unit->id }}"
data-code="{{ $unit->code }}"
data-brand="{{ $unit->brand_type }}"
data-category="{{ $unit->unit_category ?? ($unit->parent?->brand_type ?? 'Heavy Equipment') }}"
data-location="{{ $unit->location ?: 'Site Kerinci' }}"
data-site-status="{{ $unit->site_status ?? 'inside_site' }}"
data-photo="{{ $unit->photo_url }}"
{{ old('vehicle_id', $selectedVehicleId) == $unit->id ? 'selected' : '' }}>
{{ $unit->code }} - {{ $unit->brand_type }} [Posisi: {{ $unit->location ?: 'Site Kerinci' }}]
<div class="space-y-1.5">
<div class="relative">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="heavyUnitSearch"
placeholder="Ketik kode / merek untuk filter unit..."
oninput="filterHeavyUnitOptions(this.value)"
autocomplete="off"
class="w-full pl-9 pr-7 py-2 text-xs rounded-xl border border-slate-200 bg-slate-50 focus:bg-white focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition font-medium">
<button type="button" onclick="clearHeavyUnitFilter()" id="clearHeavyUnitFilterBtn" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 cursor-pointer">
<i class="fa-solid fa-xmark text-xs"></i>
</button>
</div>
<select name="vehicle_id"
id="vehicle_id"
required
onchange="onHeavyUnitSelected(this)"
class="w-full px-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-semibold">
<option value="" disabled {{ empty($selectedVehicleId) && !old('vehicle_id') ? 'selected' : '' }}>
-- Pilih Lokasi Awal Terlebih Dahulu --
</option>
@endforeach
</select>
@foreach($heavyUnits as $unit)
<option value="{{ $unit->id }}"
data-code="{{ $unit->code }}"
data-brand="{{ $unit->brand_type }}"
data-category="{{ $unit->unit_category ?? ($unit->parent?->brand_type ?? 'Heavy Equipment') }}"
data-location="{{ $unit->location ?: 'Site Kerinci' }}"
data-site-status="{{ $unit->site_status ?? 'inside_site' }}"
data-photo="{{ $unit->photo_url }}"
{{ old('vehicle_id', $selectedVehicleId) == $unit->id ? 'selected' : '' }}>
{{ $unit->code }} - {{ $unit->brand_type }} [Posisi: {{ $unit->location ?: 'Site Kerinci' }}]
</option>
@endforeach
</select>
</div>
@error('vehicle_id')
<p class="text-rose-500 text-[11px] font-semibold mt-1">{{ $message }}</p>
@enderror
@@ -282,11 +310,55 @@
</div>
<div>
<h3 class="text-base font-extrabold text-slate-900">2. Armada & Supir Pengangkut (Transporter)</h3>
<p class="text-xs text-slate-500">Truk pengangkut dapat dipilih dari lokasi yang sama atau dimobilisasi dari pool/workshop lain.</p>
<p class="text-xs text-slate-500">Pilih kendaraan pengangkut dari armada internal proyek KMH atau input armada dari vendor/rekanan luar.</p>
</div>
</div>
<!-- Banner Info Logistik Rute (Muncul saat Truk dipilih) -->
<!-- Pilihan Jenis Pengangkut: Dari Dalam KMH (Internal) vs Dari Luar KMH (Eksternal) -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-2">
Asal Armada Pengangkut <span class="text-rose-500">*</span>
</label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-xl">
<!-- Opsi 1: Dari Dalam KMH -->
<label id="card_transporter_internal" class="flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs">
<input type="radio"
name="transporter_type"
value="internal"
id="radio_transporter_internal"
{{ old('transporter_type', 'internal') === 'internal' ? 'checked' : '' }}
onchange="onTransporterTypeChanged(this.value)"
class="text-blue-600 focus:ring-blue-500">
<div class="text-left">
<span class="block text-xs font-bold flex items-center space-x-1.5">
<i class="fa-solid fa-building-shield text-blue-600"></i>
<span>Dari Dalam KMH (Armada Internal)</span>
</span>
<span class="text-[10px] text-slate-500 block mt-0.5">Pilih lokasi asal armada & unit pengangkut proyek</span>
</div>
</label>
<!-- Opsi 2: Dari Luar KMH -->
<label id="card_transporter_external" class="flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer">
<input type="radio"
name="transporter_type"
value="external"
id="radio_transporter_external"
{{ old('transporter_type') === 'external' ? 'checked' : '' }}
onchange="onTransporterTypeChanged(this.value)"
class="text-blue-600 focus:ring-blue-500">
<div class="text-left">
<span class="block text-xs font-bold flex items-center space-x-1.5">
<i class="fa-solid fa-truck-ramp-box text-slate-500"></i>
<span>Dari Luar KMH (Rental / Vendor)</span>
</span>
<span class="text-[10px] text-slate-500 block mt-0.5">Input manual lokasi asal & nama unit rekanan luar</span>
</div>
</label>
</div>
</div>
<!-- Banner Info Logistik Rute (Muncul saat Truk dipilih / terisi) -->
<div id="routeLogisticsBanner" class="hidden p-3.5 rounded-xl bg-blue-50/80 border border-blue-200 text-xs text-blue-900 flex items-start space-x-3">
<i class="fa-solid fa-route text-blue-700 text-sm mt-0.5"></i>
<div class="flex-1">
@@ -295,64 +367,128 @@
</div>
</div>
<!-- Grid 2 Kolom: Pilih Mobil Pengangkut & Nama Pengangkut -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- Pilih Mobil dari Unit Kita -->
<div>
<label for="transporter_vehicle_id" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Pilih Kendaraan Pengangkut (Armada Kita)</span>
<span id="transporterLocationHint" class="text-[10px] text-slate-400 font-normal">Truk / Lowbed / Towing</span>
</label>
<select name="transporter_vehicle_id"
id="transporter_vehicle_id"
onchange="onTransporterSelected(this)"
class="w-full px-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800">
<option value="">-- Tanpa Truk Pengangkut / Rental Luar / Mobilisasi Mandiri --</option>
@foreach($transporterUnits as $tu)
<option value="{{ $tu->id }}"
data-code="{{ $tu->code }}"
data-name="{{ $tu->code }} - {{ $tu->brand_type }}{{ $tu->license_plate ? ' (' . $tu->license_plate . ')' : '' }}"
data-location="{{ $tu->location ?: 'Pool Workshop GA' }}"
{{ old('transporter_vehicle_id') == $tu->id ? 'selected' : '' }}>
{{ $tu->code }} - {{ $tu->brand_type }} [Posisi: {{ $tu->location ?: 'Pool Workshop' }}]
</option>
@endforeach
</select>
</div>
<!-- Input / Snapshot Nama Armada Pengangkut -->
<div>
<label for="transporter_unit_name" class="block text-xs font-bold text-slate-700 mb-1.5">
Identitas / Keterangan Kendaraan Pengangkut
</label>
<div class="relative">
<i class="fa-solid fa-truck absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
name="transporter_unit_name"
id="transporter_unit_name"
value="{{ old('transporter_unit_name') }}"
placeholder="Contoh: DT-05 Hino 500 / Truk Towing Rekanan Luar"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-800 font-semibold">
<!-- ============================================== -->
<!-- KONTAINER 1: PENGANGKUT DARI DALAM KMH -->
<!-- ============================================== -->
<div id="transporterInternalContainer" class="space-y-4">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- KIRI: PILIH LOKASI ASAL PENGANGKUT (INTERNAL) -->
<div>
<label for="transporter_origin_location_select" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Lokasi Asal Kendaraan Pengangkut</span>
<span class="text-[10px] text-blue-700 font-semibold">Filter Berdasarkan Posisi</span>
</label>
<div class="relative">
<i class="fa-solid fa-map-pin absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<select id="transporter_origin_location_select"
onchange="onTransporterOriginChanged(this.value)"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-bold">
<option value="" selected>-- Pilih Lokasi Asal Kendaraan Pengangkut --</option>
<option value="ALL">[Tampilkan Semua Lokasi / Semua Armada]</option>
@foreach($transporterLocations as $tLoc => $tCount)
<option value="{{ $tLoc }}" {{ old('transporter_origin_location') === $tLoc ? 'selected' : '' }}>
{{ $tLoc }} ({{ $tCount }} Unit Tersedia)
</option>
@endforeach
</select>
</div>
<p class="text-[10px] text-slate-400 mt-1">Pilih lokasi asal untuk memfilter unit pengangkut yang standby di titik tersebut.</p>
</div>
<p class="text-[10px] text-slate-400 mt-1">Otomatis terisi jika memilih armada internal, atau ketik nama vendor/unit rekanan luar.</p>
<!-- KANAN: PILIH KENDARAAN PENGANGKUT (INPUT KETIKAN TERFILTER) -->
<div>
<label for="internal_transporter_search" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Kendaraan Pengangkut (Armada Kita)</span>
<span id="transporterCounterBadge" class="text-[10px] font-semibold text-blue-700 bg-blue-50 px-2 py-0.5 rounded border border-blue-200 hidden"></span>
</label>
<div class="relative">
<i class="fa-solid fa-truck-moving absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="internal_transporter_search"
list="internalTransporterSuggestionList"
placeholder="Ketik kode/tipe truk (cth: LB 01, DT 05, Lowbed...)"
oninput="onInternalTransporterInput(this.value)"
autocomplete="off"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik atau pilih dari rekomendasi truk pengangkut internal (Lowbed, Flatbed, Dump Truck, Trailer, dll.).</p>
<!-- Datalist Autocomplete Khusus Truk Pengangkut Internal -->
<datalist id="internalTransporterSuggestionList">
@foreach($transporterUnits as $tu)
<option value="{{ $tu->code }} - {{ $tu->brand_type }}{{ $tu->license_plate ? ' (' . $tu->license_plate . ')' : '' }} [Posisi: {{ $tu->location ?: 'Site Kerinci' }}]" data-id="{{ $tu->id }}">
@endforeach
</datalist>
<!-- Hidden ID untuk backend -->
<input type="hidden" name="transporter_vehicle_id" id="transporter_vehicle_id" value="{{ old('transporter_vehicle_id') }}">
</div>
</div>
<!-- Opsi Sinkronisasi Lokasi Truk Pengangkut Internal -->
<div id="transporterUpdateCheckboxWrapper" class="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center space-x-3">
<input type="checkbox"
name="update_transporter_location"
id="update_transporter_location"
value="1"
checked
class="w-4 h-4 rounded text-[#1b5e20] focus:ring-[#1b5e20] border-slate-300 cursor-pointer">
<label for="update_transporter_location" class="text-xs text-slate-700 font-semibold cursor-pointer select-none">
Perbarui juga posisi terkini truk pengangkut ke lokasi tujuan setelah proses pemindahan selesai
</label>
</div>
</div>
<!-- Opsi Sinkronisasi Lokasi Truk Pengangkut -->
<div class="p-3 rounded-xl bg-slate-50 border border-slate-200 flex items-center space-x-3">
<input type="checkbox"
name="update_transporter_location"
id="update_transporter_location"
value="1"
checked
class="w-4 h-4 rounded text-[#1b5e20] focus:ring-[#1b5e20] border-slate-300 cursor-pointer">
<label for="update_transporter_location" class="text-xs text-slate-700 font-semibold cursor-pointer select-none">
Perbarui juga posisi terkini truk pengangkut ke lokasi tujuan setelah proses pemindahan selesai
</label>
<!-- ============================================== -->
<!-- KONTAINER 2: PENGANGKUT DARI LUAR KMH -->
<!-- ============================================== -->
<div id="transporterExternalContainer" class="hidden space-y-4">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- KIRI: ASAL KENDARAAN PENGANGKUT (ISIAN TEKS MANUAL) -->
<div>
<label for="transporter_origin_location_input" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Asal Kendaraan Pengangkut (Luar)</span>
<span class="text-[10px] text-slate-400 font-normal">Ketik Bebas / Rekomendasi</span>
</label>
<div class="relative">
<i class="fa-solid fa-map-location-dot absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="transporter_origin_location_input"
list="locationSuggestionList"
placeholder="Contoh: Pool Jambi, Workshop Padang, PT Bhara Seva..."
oninput="onExternalOriginInput(this.value)"
value="{{ old('transporter_type') === 'external' ? old('transporter_origin_location') : '' }}"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik kota asal, pool rekanan, atau nama subkon penyedia armada.</p>
</div>
<!-- KANAN: IDENTITAS / NAMA KENDARAAN PENGANGKUT (ISIAN TEKS MANUAL) -->
<div>
<label for="transporter_unit_name_input" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
<span>Identitas / Nama Kendaraan Pengangkut</span>
<span class="text-[10px] text-slate-400 font-normal">Isian Teks Bebas</span>
</label>
<div class="relative">
<i class="fa-solid fa-truck absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
id="transporter_unit_name_input"
placeholder="Contoh: Truk Tronton Hino BA 1234 XY / Lowbed Rental PT Surya"
oninput="onExternalUnitNameInput(this.value)"
value="{{ old('transporter_type') === 'external' ? old('transporter_unit_name') : '' }}"
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-600 transition bg-white text-slate-800 font-semibold">
</div>
<p class="text-[10px] text-slate-400 mt-1">Ketik jenis kendaraan, nomor plat polisi, atau identitas unit rekanan luar.</p>
</div>
</div>
</div>
<!-- Field Hidden Final yang Dikirim ke Server -->
<input type="hidden" name="transporter_origin_location" id="final_transporter_origin_location" value="{{ old('transporter_origin_location') }}">
<input type="hidden" name="transporter_unit_name" id="final_transporter_unit_name" value="{{ old('transporter_unit_name') }}">
<!-- Grid 2 Kolom: Supir Pengangkut & Catatan Angkutan -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-1">
<!-- Supir Pengangkut -->
<div>
<label for="transporter_driver_name" class="block text-xs font-bold text-slate-700 mb-1.5 flex items-center justify-between">
@@ -482,8 +618,20 @@
</div>
<script>
// Inisialisasi daftar semua unit alat berat dari options
// Inisialisasi daftar semua unit alat berat & armada pengangkut
let allHeavyUnits = [];
let allTransporterUnits = [
@foreach($transporterUnits as $tu)
{
id: {{ $tu->id }},
code: @json($tu->code),
name: @json($tu->code . ' - ' . $tu->brand_type . ($tu->license_plate ? ' (' . $tu->license_plate . ')' : '')),
location: @json($tu->location ?: 'Site Kerinci'),
category: @json($tu->unit_category ?? 'Truk'),
text: @json($tu->code . ' - ' . $tu->brand_type . ($tu->license_plate ? ' (' . $tu->license_plate . ')' : '') . ' [Posisi: ' . ($tu->location ?: 'Site Kerinci') . ']')
},
@endforeach
];
document.addEventListener('DOMContentLoaded', function() {
const unitSelect = document.getElementById('vehicle_id');
@@ -504,17 +652,193 @@
});
}
// Cek jika sudah ada lokasi awal (dari old value atau selectedOriginLocation)
// Cek jika sudah ada lokasi awal alat berat (dari old value atau selectedOriginLocation)
const originSelect = document.getElementById('origin_location');
if (originSelect && originSelect.value) {
onOriginLocationChanged(originSelect.value, "{{ old('vehicle_id', $selectedVehicleId ?? '') }}");
}
// Inisialisasi tampilan jenis pengangkut (internal vs external)
const currentTransporterType = document.querySelector('input[name="transporter_type"]:checked')?.value || 'internal';
onTransporterTypeChanged(currentTransporterType);
// Inisialisasi datalist saran truk internal
const oldTransporterOrigin = "{{ old('transporter_origin_location') }}";
const oldTransporterId = "{{ old('transporter_vehicle_id') }}";
if (currentTransporterType === 'internal') {
if (oldTransporterOrigin) {
const tLocSelect = document.getElementById('transporter_origin_location_select');
if (tLocSelect) tLocSelect.value = oldTransporterOrigin;
onTransporterOriginChanged(oldTransporterOrigin, oldTransporterId);
} else if (oldTransporterId) {
const matched = allTransporterUnits.find(u => String(u.id) === String(oldTransporterId));
if (matched) {
const tLocSelect = document.getElementById('transporter_origin_location_select');
if (tLocSelect) tLocSelect.value = matched.location;
onTransporterOriginChanged(matched.location, oldTransporterId);
} else {
onTransporterOriginChanged('');
}
} else {
onTransporterOriginChanged('');
}
}
// Inisialisasi tampilan BAST berdasarkan status site awal
const currentSiteStatus = document.querySelector('input[name="to_site_status"]:checked')?.value || 'inside_site';
onSiteStatusChanged(currentSiteStatus);
});
/**
* Handler untuk Jenis Pengangkut (Dari Dalam KMH vs Dari Luar KMH)
*/
function onTransporterTypeChanged(type) {
const cardInternal = document.getElementById('card_transporter_internal');
const cardExternal = document.getElementById('card_transporter_external');
const containerInternal = document.getElementById('transporterInternalContainer');
const containerExternal = document.getElementById('transporterExternalContainer');
const updateCheckboxWrapper = document.getElementById('transporterUpdateCheckboxWrapper');
const updateCheckbox = document.getElementById('update_transporter_location');
if (type === 'external') {
// Style Card External Aktif
cardExternal.className = 'flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs';
cardInternal.className = 'flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer';
containerInternal.classList.add('hidden');
containerExternal.classList.remove('hidden');
if (updateCheckboxWrapper) updateCheckboxWrapper.classList.add('hidden');
if (updateCheckbox) updateCheckbox.checked = false;
// Kosongkan seleksi unit internal
const vId = document.getElementById('transporter_vehicle_id');
if (vId) vId.value = '';
// Sinkronkan data dari input teks external
const extOrigin = document.getElementById('transporter_origin_location_input')?.value.trim() || '';
const extName = document.getElementById('transporter_unit_name_input')?.value.trim() || '';
document.getElementById('final_transporter_origin_location').value = extOrigin;
document.getElementById('final_transporter_unit_name').value = extName;
} else {
// Style Card Internal Aktif
cardInternal.className = 'flex items-center space-x-3 p-3 rounded-xl border-2 border-blue-600 bg-blue-50/50 text-blue-950 transition cursor-pointer shadow-xs';
cardExternal.className = 'flex items-center space-x-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 bg-white text-slate-700 transition cursor-pointer';
containerInternal.classList.remove('hidden');
containerExternal.classList.add('hidden');
if (updateCheckboxWrapper) updateCheckboxWrapper.classList.remove('hidden');
if (updateCheckbox) updateCheckbox.checked = true;
// Sinkronkan data dari input pencarian internal
const searchInput = document.getElementById('internal_transporter_search');
if (searchInput) onInternalTransporterInput(searchInput.value);
}
updateRouteBanner();
}
/**
* Handler ketika Lokasi Asal Armada Pengangkut Internal Berubah
*/
function onTransporterOriginChanged(selectedLocation, preselectId = null) {
const datalist = document.getElementById('internalTransporterSuggestionList');
const badge = document.getElementById('transporterCounterBadge');
const searchInput = document.getElementById('internal_transporter_search');
if (!datalist) return;
datalist.innerHTML = '';
const filtered = (!selectedLocation || selectedLocation === 'ALL')
? allTransporterUnits
: allTransporterUnits.filter(u => u.location === selectedLocation);
if (badge) {
badge.classList.remove('hidden');
badge.textContent = `${filtered.length} Truk Tersedia`;
}
if (searchInput) {
if (selectedLocation && selectedLocation !== 'ALL') {
searchInput.placeholder = `Ketik kode truk di ${selectedLocation} (${filtered.length} truk)...`;
} else {
searchInput.placeholder = `Ketik kode/tipe truk (${filtered.length} truk tersedia)...`;
}
}
filtered.forEach(u => {
const opt = document.createElement('option');
opt.value = u.text;
opt.setAttribute('data-id', u.id);
datalist.appendChild(opt);
});
if (preselectId) {
const matched = allTransporterUnits.find(u => String(u.id) === String(preselectId));
if (matched && searchInput) {
searchInput.value = matched.text;
onInternalTransporterInput(matched.text);
}
}
}
/**
* Handler ketika input ketikan truk internal berubah (Autocomplete / Pencarian)
*/
function onInternalTransporterInput(val) {
val = (val || '').trim();
const finalOrigin = document.getElementById('final_transporter_origin_location');
const finalName = document.getElementById('final_transporter_unit_name');
const vehicleIdInput = document.getElementById('transporter_vehicle_id');
if (!val) {
if (vehicleIdInput) vehicleIdInput.value = '';
if (finalName) finalName.value = '';
if (finalOrigin) finalOrigin.value = '';
updateRouteBanner();
return;
}
// Cari unit yang cocok di allTransporterUnits berdasarkan kode atau nama lengkap
const valUpper = val.toUpperCase();
const matched = allTransporterUnits.find(u =>
valUpper === u.code.toUpperCase() ||
valUpper === u.text.toUpperCase() ||
valUpper === u.name.toUpperCase() ||
valUpper.startsWith(u.code.toUpperCase() + ' ') ||
valUpper.startsWith(u.code.toUpperCase() + '-')
);
if (matched) {
if (vehicleIdInput) vehicleIdInput.value = matched.id;
if (finalName) finalName.value = matched.name;
if (finalOrigin) finalOrigin.value = matched.location;
} else {
// Teks ketikan bebas
if (vehicleIdInput) vehicleIdInput.value = '';
if (finalName) finalName.value = val;
}
updateRouteBanner();
}
/**
* Handler input Asal Kendaraan Luar
*/
function onExternalOriginInput(val) {
const finalOrigin = document.getElementById('final_transporter_origin_location');
if (finalOrigin) finalOrigin.value = (val || '').trim();
updateRouteBanner();
}
/**
* Handler input Nama / Identitas Kendaraan Luar
*/
function onExternalUnitNameInput(val) {
const finalName = document.getElementById('final_transporter_unit_name');
if (finalName) finalName.value = (val || '').trim();
updateRouteBanner();
}
/**
* Handler untuk Area Tujuan (Di Dalam Site vs Di Luar Site)
* Nomor BAST dan Dokumen hanya muncul saat transfer ke LUAR site.
@@ -577,6 +901,11 @@
// Kosongkan options
unitSelect.innerHTML = '';
const searchInput = document.getElementById('heavyUnitSearch');
if (searchInput) searchInput.value = '';
const searchClear = document.getElementById('clearHeavyUnitFilterBtn');
if (searchClear) searchClear.classList.add('hidden');
if (!selectedLocation) {
const defaultOpt = document.createElement('option');
defaultOpt.value = '';
@@ -679,47 +1008,148 @@
}
/**
* Handler saat Armada Pengangkut Terpilih
*/
function onTransporterSelected(selectElement) {
const option = selectElement.options[selectElement.selectedIndex];
const nameInput = document.getElementById('transporter_unit_name');
if (option && option.value) {
const dataName = option.getAttribute('data-name');
if (dataName) {
nameInput.value = dataName;
}
}
updateRouteBanner();
}
/**
* Update Banner Logistik Rute Perjalanan
* Update Banner Logistik Rute Perjalanan (Mendukung Internal & Eksternal)
*/
function updateRouteBanner() {
const banner = document.getElementById('routeLogisticsBanner');
const text = document.getElementById('routeLogisticsText');
const transporterSelect = document.getElementById('transporter_vehicle_id');
const originSelect = document.getElementById('origin_location');
const destinationInput = document.getElementById('to_location');
const transporterType = document.querySelector('input[name="transporter_type"]:checked')?.value || 'internal';
const optTransporter = transporterSelect.options[transporterSelect.selectedIndex];
if (!optTransporter || !optTransporter.value) {
banner.classList.add('hidden');
return;
}
if (!banner || !text) return;
const transporterCode = optTransporter.getAttribute('data-code');
const transporterLoc = optTransporter.getAttribute('data-location') || 'Pool Workshop';
const originLoc = originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
const destLoc = destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
const originLoc = originSelect && originSelect.value && originSelect.value !== 'ALL' ? originSelect.value : 'Lokasi Asal Alat Berat';
const destLoc = destinationInput && destinationInput.value ? destinationInput.value : '[Lokasi Tujuan Baru]';
banner.classList.remove('hidden');
if (transporterLoc === originLoc) {
text.innerHTML = `Truk <strong>${transporterCode}</strong> saat ini standby di <strong>${transporterLoc}</strong> (sama dengan lokasi alat berat) &rarr; Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`;
if (transporterType === 'internal') {
const truckName = document.getElementById('final_transporter_unit_name')?.value || document.getElementById('internal_transporter_search')?.value.trim();
const truckLoc = document.getElementById('final_transporter_origin_location')?.value || 'Site Kerinci';
if (!truckName) {
banner.classList.add('hidden');
return;
}
banner.classList.remove('hidden');
if (truckLoc === originLoc) {
text.innerHTML = `Truk <strong>${truckName}</strong> saat ini standby di <strong>${truckLoc}</strong> (sama dengan lokasi alat berat) &rarr; Langsung mengangkut unit menuju tujuan <strong>${destLoc}</strong>.`;
} else {
text.innerHTML = `Truk <strong>${truckName}</strong> diberangkatkan dari <strong>${truckLoc}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
}
} else {
text.innerHTML = `Truk <strong>${transporterCode}</strong> diberangkatkan dari <strong>${transporterLoc}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
const extOrigin = document.getElementById('transporter_origin_location_input')?.value.trim();
const extName = document.getElementById('transporter_unit_name_input')?.value.trim();
if (!extName && !extOrigin) {
banner.classList.add('hidden');
return;
}
const displayOrigin = extOrigin ? extOrigin : 'Luar Proyek';
const displayName = extName ? extName : 'Armada Eksternal';
banner.classList.remove('hidden');
text.innerHTML = `Armada luar (<strong>${displayName}</strong>) diberangkatkan dari <strong>${displayOrigin}</strong> &rarr; Menjemput alat berat di <strong>${originLoc}</strong> &rarr; Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
}
}
/**
* 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
+170 -171
View File
@@ -3,12 +3,12 @@
@section('title', 'Transfer Unit Alat Berat - Admin QMA | PT Kerinci Merangin Hidro')
@section('content')
<div class="w-full space-y-6">
<div class="w-full space-y-4 sm:space-y-5">
<!-- Header Judul & Tombol Aksi (Persis Format Standar HSE Employees) -->
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<!-- Header Judul & Tombol Aksi -->
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
<div>
<div class="flex items-center space-x-1.5 mb-1">
<div class="flex items-center space-x-1.5 mb-0.5">
<span class="text-xs font-bold uppercase tracking-wider text-[#1b5e20]">
MANAJEMEN SISTEM
</span>
@@ -19,22 +19,22 @@
<i class="fa-solid fa-info"></i>
</button>
</div>
<h2 class="text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight">
<h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
Transfer Unit Alat Berat
</h2>
</div>
<!-- Tombol Aksi Kanan -->
<div class="flex items-center gap-2.5 sm:gap-3 w-full sm:w-auto">
<div class="flex items-center gap-2 sm:gap-2.5 w-full sm:w-auto">
<!-- Dropdown Menu Ekspor Format it.allrole.web.id -->
<div class="relative inline-block w-full sm:w-auto flex-1 sm:flex-none" id="exportDropdownContainer">
<button type="button"
onclick="toggleExportMenu(event)"
id="btnExportTrigger"
class="w-full sm:w-auto border border-emerald-600/30 text-emerald-900 bg-white hover:bg-emerald-50/50 px-3 sm:px-4 py-2.5 rounded-xl text-xs font-bold flex items-center justify-center space-x-2 transition shadow-sm cursor-pointer">
class="w-full sm:w-auto border border-emerald-600/30 text-emerald-900 bg-white hover:bg-emerald-50/50 px-3 sm:px-3.5 py-2 rounded-xl text-xs font-bold flex items-center justify-center space-x-1.5 transition shadow-2xs cursor-pointer">
<i class="fa-regular fa-file-excel text-emerald-700 text-sm"></i>
<span class="truncate">Ekspor Data</span>
<i class="fa-solid fa-chevron-down text-[9px] text-slate-400 ml-0.5 sm:ml-1"></i>
<i class="fa-solid fa-chevron-down text-[9px] text-slate-400 ml-0.5"></i>
</button>
<div id="exportMenu" style="display: none;" class="absolute right-0 mt-2 w-52 bg-white rounded-xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] border border-slate-100 z-50 overflow-hidden">
<a href="{{ route('qma.unit_transfers.export_pdf', request()->query()) }}" target="_blank" class="flex items-center px-4 py-3 text-xs text-slate-700 hover:bg-slate-50 hover:text-[#1b5e20] font-bold transition">
@@ -51,21 +51,9 @@
@canany(['qma.vehicles.create', 'qma.vehicles.edit'])
<a href="{{ route('qma.unit_transfers.create') }}"
class="flex items-center justify-center space-x-2 bg-[#1b5e20] hover:bg-[#144919] text-white px-3 sm:px-4 py-2.5 rounded-xl text-xs font-bold transition shadow-sm cursor-pointer whitespace-nowrap">
<i class="fa-solid fa-truck-moving text-sm"></i>
<span class="hidden sm:inline">Transfer Unit Baru</span>
<span class="sm:hidden">Transfer Baru</span>
</a>
@endcanany
</div>
</div>
<!-- Tombol Buat Transfer Unit Baru -->
@canany(['qma.vehicles.create', 'qma.vehicles.edit'])
<a href="{{ route('qma.unit_transfers.create') }}"
class="inline-flex items-center justify-center space-x-2 bg-[#1b5e20] hover:bg-[#144919] text-white px-4 py-2.5 rounded-xl text-xs font-bold transition shadow-sm cursor-pointer whitespace-nowrap">
<i class="fa-solid fa-plus text-xs"></i>
<span>Buat Transfer Unit</span>
class="flex-1 sm:flex-none flex items-center justify-center space-x-1.5 bg-[#1b5e20] hover:bg-[#144919] text-white px-3.5 py-2 rounded-xl text-xs font-bold transition shadow-2xs cursor-pointer whitespace-nowrap">
<i class="fa-solid fa-truck-moving text-xs"></i>
<span>Transfer Unit Baru</span>
</a>
@endcanany
</div>
@@ -73,8 +61,8 @@
<!-- Alert Notifikasi Flash -->
@if(session('success'))
<div class="flex items-center space-x-3 p-4 bg-emerald-50/90 border border-emerald-200 rounded-2xl text-emerald-800 text-xs sm:text-sm font-semibold shadow-2xs">
<div class="w-7 h-7 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0">
<div class="flex items-center space-x-3 p-3.5 bg-emerald-50/90 border border-emerald-200 rounded-xl text-emerald-800 text-xs font-semibold shadow-2xs">
<div class="w-6 h-6 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0 text-xs">
<i class="fa-solid fa-check"></i>
</div>
<div class="flex-1">
@@ -84,8 +72,8 @@
@endif
@if(session('error'))
<div class="flex items-center space-x-3 p-4 bg-rose-50/90 border border-rose-200 rounded-2xl text-rose-800 text-xs sm:text-sm font-semibold shadow-2xs">
<div class="w-7 h-7 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center shrink-0">
<div class="flex items-center space-x-3 p-3.5 bg-rose-50/90 border border-rose-200 rounded-xl text-rose-800 text-xs font-semibold shadow-2xs">
<div class="w-6 h-6 rounded-full bg-rose-100 text-rose-700 flex items-center justify-center shrink-0 text-xs">
<i class="fa-solid fa-triangle-exclamation"></i>
</div>
<div class="flex-1">
@@ -94,178 +82,184 @@
</div>
@endif
<!-- KPI Ringkasan Pemindahan Unit -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3.5">
<!-- KPI Ringkasan Pemindahan Unit (Ramping & Sleek) -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-2.5 sm:gap-3">
<!-- 1. Total Transfer -->
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs">
<p class="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Pemindahan</p>
<h3 class="text-2xl font-black text-slate-800 mt-1">{{ number_format($totalTransfers, 0, ',', '.') }}</h3>
<span class="text-[10px] text-slate-400 font-medium block mt-1">Semua Dokumen BAST</span>
<div class="bg-white p-3 sm:p-3.5 rounded-xl border border-slate-200/80 shadow-2xs flex items-center justify-between">
<div>
<p class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Total BAST</p>
<h3 class="text-lg sm:text-xl font-black text-slate-800 mt-0.5">{{ number_format($totalTransfers, 0, ',', '.') }}</h3>
<span class="text-[10px] text-slate-400 font-medium">Semua Dokumen</span>
</div>
<div class="w-8 h-8 rounded-lg bg-slate-100 text-slate-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-file-contract"></i>
</div>
</div>
<!-- 2. Pemindahan Bulan Ini -->
<div class="bg-white p-4 rounded-2xl border border-blue-200/80 shadow-xs bg-gradient-to-br from-white to-blue-50/30">
<p class="text-[11px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p>
<h3 class="text-2xl font-black text-blue-800 mt-1">{{ number_format($thisMonthCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-blue-600 font-semibold block mt-1">{{ \Carbon\Carbon::now()->translatedFormat('F Y') }}</span>
<div class="bg-white p-3 sm:p-3.5 rounded-xl border border-blue-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-blue-50/20">
<div>
<p class="text-[10px] font-bold uppercase tracking-wider text-blue-700">Bulan Ini</p>
<h3 class="text-lg sm:text-xl font-black text-blue-800 mt-0.5">{{ number_format($thisMonthCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-blue-600 font-semibold">{{ \Carbon\Carbon::now()->translatedFormat('M Y') }}</span>
</div>
<div class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-calendar-check"></i>
</div>
</div>
<!-- 3. Di Dalam Site -->
<div class="bg-white p-4 rounded-2xl border border-emerald-200/80 shadow-xs bg-gradient-to-br from-white to-emerald-50/30">
<p class="text-[11px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p>
<h3 class="text-2xl font-black text-emerald-800 mt-1">{{ number_format($insideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-emerald-600 font-semibold block mt-1">Area Proyek KMH</span>
<div class="bg-white p-3 sm:p-3.5 rounded-xl border border-emerald-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-emerald-50/20">
<div>
<p class="text-[10px] font-bold uppercase tracking-wider text-emerald-700">Tujuan In-Site</p>
<h3 class="text-lg sm:text-xl font-black text-emerald-800 mt-0.5">{{ number_format($insideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-emerald-600 font-semibold">Area Proyek</span>
</div>
<div class="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-location-dot"></i>
</div>
</div>
<!-- 4. Di Luar Site -->
<div class="bg-white p-4 rounded-2xl border border-amber-200/80 shadow-xs bg-gradient-to-br from-white to-amber-50/30">
<p class="text-[11px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p>
<h3 class="text-2xl font-black text-amber-800 mt-1">{{ number_format($outsideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-amber-600 font-semibold block mt-1">Workshop/Luar Proyek</span>
<div class="bg-white p-3 sm:p-3.5 rounded-xl border border-amber-200/80 shadow-2xs flex items-center justify-between bg-gradient-to-br from-white to-amber-50/20">
<div>
<p class="text-[10px] font-bold uppercase tracking-wider text-amber-700">Tujuan Out-Site</p>
<h3 class="text-lg sm:text-xl font-black text-amber-800 mt-0.5">{{ number_format($outsideCount, 0, ',', '.') }}</h3>
<span class="text-[10px] text-amber-600 font-semibold">Workshop/Luar</span>
</div>
<div class="w-8 h-8 rounded-lg bg-amber-50 text-amber-600 flex items-center justify-center text-xs shrink-0">
<i class="fa-solid fa-arrow-up-right-from-square"></i>
</div>
</div>
</div>
<!-- Filter Card -->
<div class="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-xs">
<form method="GET" action="{{ route('qma.unit_transfers.index') }}" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-5 gap-3 items-center">
<!-- Search Text -->
<div class="relative md:col-span-2">
<i class="fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
<input type="text"
name="search"
value="{{ request('search') }}"
placeholder="Cari No BAST, Unit, Lokasi, Driver, Pelapor..."
class="w-full pl-9 pr-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition">
</div>
<!-- Kotak Pencarian & Filter Ramping (Inline Format Referensi HSE) -->
<form method="GET" action="{{ route('qma.unit_transfers.index') }}" id="transferFilterForm" class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2.5 sm:gap-3">
<!-- Search Text (Kiri) -->
<div class="relative w-full sm:max-w-md">
<span class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
<i class="fa-solid fa-magnifying-glass text-xs"></i>
</span>
<input type="text"
name="search"
id="transferSearchInput"
value="{{ request('search') }}"
placeholder="Cari No BAST, unit, lokasi, pengangkut, pelapor..."
class="w-full text-xs pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder-slate-400 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 shadow-sm transition">
</div>
<!-- Filter Dropdown (Kanan) -->
<div class="flex flex-wrap items-center gap-2 sm:gap-2.5 w-full sm:w-auto">
<!-- Filter Alat Berat -->
<div>
<select name="vehicle_id" class="w-full px-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-700">
<option value="all">Semua Alat Berat</option>
@foreach($heavyUnits as $hu)
<option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}>
{{ $hu->code }} - {{ $hu->brand_type }}
</option>
@endforeach
</select>
</div>
<select name="vehicle_id" onchange="this.form.submit()" class="text-xs rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] shadow-sm transition max-w-[200px] truncate">
<option value="all">Semua Alat Berat</option>
@foreach($heavyUnits as $hu)
<option value="{{ $hu->id }}" {{ request('vehicle_id') == $hu->id ? 'selected' : '' }}>
{{ $hu->code }} - {{ $hu->brand_type }}
</option>
@endforeach
</select>
<!-- Filter Status Area Tujuan -->
<div>
<select name="to_site_status" class="w-full px-3 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#1b5e20]/20 focus:border-[#1b5e20] transition bg-white text-slate-700">
<option value="all" {{ request('to_site_status') === 'all' ? 'selected' : '' }}>Semua Area Tujuan</option>
<option value="inside_site" {{ request('to_site_status') === 'inside_site' ? 'selected' : '' }}>Di Dalam Site</option>
<option value="outside_site" {{ request('to_site_status') === 'outside_site' ? 'selected' : '' }}>Di Luar Site</option>
</select>
</div>
<select name="to_site_status" onchange="this.form.submit()" class="text-xs rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-700 font-semibold focus:outline-none focus:border-[#1b5e20] shadow-sm transition">
<option value="all" {{ request('to_site_status') === 'all' ? 'selected' : '' }}>Semua Area Tujuan</option>
<option value="inside_site" {{ request('to_site_status') === 'inside_site' ? 'selected' : '' }}>Di Dalam Site</option>
<option value="outside_site" {{ request('to_site_status') === 'outside_site' ? 'selected' : '' }}>Di Luar Site</option>
</select>
<!-- Tombol Filter & Reset -->
<div class="flex items-center space-x-2">
<button type="submit" class="flex-1 px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl transition shadow-sm cursor-pointer text-center">
Filter
</button>
@if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date']))
<a href="{{ route('qma.unit_transfers.index') }}" class="px-3 py-2 rounded-xl text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 hover:bg-rose-100 transition whitespace-nowrap" title="Reset Filter">
<i class="fa-solid fa-rotate-left"></i>
</a>
@endif
</div>
</form>
</div>
@if(request()->anyFilled(['search', 'vehicle_id', 'to_site_status', 'start_date', 'end_date']))
<a href="{{ route('qma.unit_transfers.index') }}" class="px-2.5 py-2 rounded-xl text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 hover:bg-rose-100 transition whitespace-nowrap" title="Reset Filter">
<i class="fa-solid fa-rotate-left mr-1"></i>Reset
</a>
@endif
</div>
</form>
<!-- Tabel Riwayat Transfer Unit dengan Header Biru Tua Navy (Pada Mobile: Format Kotak Tanpa Border Radius) -->
<!-- Tabel Riwayat Transfer Unit -->
<div class="bg-white rounded-none sm:rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="min-w-full text-xs text-left border-collapse">
<!-- Header Tabel Navy Gelap Solid #06213f -->
<thead class="bg-[#06213f] text-white font-bold text-[11px] uppercase tracking-wider">
<tr>
<th class="py-3.5 px-4 text-center w-12">NO</th>
<th class="py-3.5 px-4 whitespace-nowrap">TANGGAL & NO TRANSFER</th>
<th class="py-3.5 px-4 whitespace-nowrap">BERITA ACARA (BAST)</th>
<th class="py-3.5 px-4 whitespace-nowrap min-w-[180px]">UNIT ALAT BERAT</th>
<th class="py-3.5 px-4 whitespace-nowrap min-w-[200px]">PERPINDAHAN LOKASI</th>
<th class="py-3.5 px-4 whitespace-nowrap">ARMADA & SUPIR</th>
<th class="py-3.5 px-4 whitespace-nowrap">PELAPOR</th>
<th class="py-3.5 px-4 text-center whitespace-nowrap w-28">AKSI</th>
<th class="py-3 px-3.5 text-center w-10">NO</th>
<th class="py-3 px-3.5 whitespace-nowrap">DOKUMEN & TANGGAL</th>
<th class="py-3 px-3.5 whitespace-nowrap">UNIT ALAT BERAT</th>
<th class="py-3 px-3.5 whitespace-nowrap">RUTE PEMINDAHAN</th>
<th class="py-3 px-3.5 whitespace-nowrap">PENGANGKUT & SUPIR</th>
<th class="py-3 px-3.5 whitespace-nowrap">PELAPOR</th>
<th class="py-3 px-3.5 text-center whitespace-nowrap w-24">AKSI</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 text-slate-700 bg-white">
@forelse($transfers as $index => $t)
<tr class="hover:bg-slate-50/80 transition">
<!-- 1. No -->
<td class="py-3.5 px-3.5 text-center text-slate-400 font-medium">
<td class="py-2.5 px-3.5 text-center text-slate-400 font-medium">
{{ $transfers->firstItem() + $index }}
</td>
<!-- 2. Tanggal & No Transfer -->
<td class="py-3.5 px-3.5 whitespace-nowrap">
<div class="font-bold text-slate-900">
{{ $t->transfer_date ? $t->transfer_date->translatedFormat('d M Y') : '-' }}
</div>
<span class="inline-block mt-0.5 font-mono text-[10px] text-slate-500 bg-slate-100 px-1.5 py-0.5 rounded">
{{ $t->transfer_no }}
</span>
</td>
<!-- 3. Berita Acara -->
<td class="py-3.5 px-3.5 min-w-[200px]">
@if($t->document_number)
<div class="font-bold text-slate-900 leading-tight font-mono text-xs">
{{ $t->document_number }}
</div>
<div class="text-[11px] text-slate-500 mt-0.5 line-clamp-1" title="{{ $t->document_title }}">
{{ $t->document_title }}
</div>
@if($t->document_file_path)
<a href="{{ $t->document_file_url }}" target="_blank" class="inline-flex items-center space-x-1 text-[10px] font-bold text-emerald-700 hover:text-emerald-900 mt-1">
<i class="fa-solid fa-paperclip"></i>
<span>Lihat Lampiran</span>
</a>
@endif
@else
<span class="inline-flex items-center space-x-1 px-2 py-0.5 rounded text-[11px] font-medium text-slate-500 bg-slate-100 border border-slate-200">
<span>Tanpa BAST (Internal Site)</span>
</span>
@endif
</td>
<!-- 4. Unit Alat Berat -->
<td class="py-3.5 px-3.5 whitespace-nowrap">
<div class="flex items-center space-x-2.5">
@if($t->vehicle && $t->vehicle->photo_url)
<img src="{{ $t->vehicle->photo_url }}" alt="{{ $t->vehicle->code }}" class="w-9 h-9 rounded-xl object-cover border border-slate-200 shrink-0">
<!-- 2. Dokumen BAST & Tanggal Transfer -->
<td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="flex items-center space-x-1.5">
@if($t->document_number)
<span class="font-bold text-slate-900 font-mono text-xs">
{{ $t->document_number }}
</span>
@if($t->document_file_path)
<a href="{{ $t->document_file_url }}" target="_blank" class="text-emerald-700 hover:text-emerald-900 text-xs" title="Lihat Lampiran Berkas">
<i class="fa-solid fa-paperclip"></i>
</a>
@endif
@else
<div class="w-9 h-9 rounded-xl bg-slate-100 text-slate-400 flex items-center justify-center shrink-0 border border-slate-200">
<i class="fa-solid fa-truck-monster text-sm"></i>
<span class="px-1.5 py-0.5 rounded text-[10px] font-bold text-slate-600 bg-slate-100 border border-slate-200">
Internal Site
</span>
@endif
</div>
<div class="text-[11px] text-slate-500 mt-0.5 flex items-center gap-1.5 font-medium">
<span>{{ $t->transfer_date ? $t->transfer_date->translatedFormat('d M Y') : '-' }}</span>
<span class="text-slate-300">&bull;</span>
<span class="font-mono text-[10px] text-slate-400">{{ $t->transfer_no }}</span>
</div>
</td>
<!-- 3. Unit Alat Berat -->
<td class="py-2.5 px-3.5 whitespace-nowrap">
<div class="flex items-center space-x-2">
@if($t->vehicle && $t->vehicle->photo_url)
<img src="{{ $t->vehicle->photo_url }}" alt="{{ $t->vehicle->code }}" class="w-8 h-8 rounded-lg object-cover border border-slate-200 shrink-0">
@else
<div class="w-8 h-8 rounded-lg bg-slate-100 text-slate-400 flex items-center justify-center shrink-0 border border-slate-200 text-xs">
<i class="fa-solid fa-truck-monster"></i>
</div>
@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');
+5
View File
@@ -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.
+4 -1
View File
@@ -88,7 +88,7 @@ Route::middleware('auth')->group(function () {
Route::post('/vehicles/unit-support/{id}/units', [VehicleController::class, 'storeSupportUnit'])->name('vehicles.support.units.store')->middleware('permission:qma.vehicles.create');
Route::post('/vehicles', [VehicleController::class, 'store'])->name('vehicles.store')->middleware('permission:qma.vehicles.create');
Route::post('/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit');
Route::match(['PUT', 'POST'], '/vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update')->middleware('permission:qma.vehicles.edit');
Route::delete('/vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy')->middleware('permission:qma.vehicles.delete');
Route::get('/activity-log', [ActivityLogController::class, 'index'])->name('activity.log')->middleware('permission:qma.logs.view');
Route::get('/activity-log/support-timesheet', [SupportTimesheetController::class, 'index'])->name('activity.support_timesheet')->middleware('permission:qma.logs.view');
@@ -214,11 +214,14 @@ Route::middleware('auth')->group(function () {
// Log Riwayat Aktivitas Super Admin
Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index');
Route::post('/activity-logs/clear', [AdminActivityLogController::class, 'clear'])->name('activity_logs.clear');
// Backup & Restore Sistem (Database & Media)
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
Route::post('/backups/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')->middleware('throttle:5,1');
+29
View File
@@ -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'));
}
}
+254
View File
@@ -0,0 +1,254 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\DatabaseBackupService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class BackupConverterTest extends TestCase
{
use RefreshDatabase;
private User $superAdmin;
private DatabaseBackupService $backupService;
protected function setUp(): void
{
parent::setUp();
$role = Role::firstOrCreate(['name' => 'super_admin']);
$this->superAdmin = User::factory()->create([
'username' => 'superadmin_conv_test',
'role' => 'super_admin',
'password' => bcrypt('password123'),
]);
$this->superAdmin->assignRole($role);
$this->backupService = new DatabaseBackupService();
}
protected function tearDown(): void
{
$dir = $this->backupService->getBackupDirectory();
if (File::isDirectory($dir)) {
foreach (File::files($dir) as $f) {
if (str_starts_with($f->getFilename(), 'test_conv_')) {
@unlink($f->getPathname());
}
}
}
parent::tearDown();
}
protected function createSampleKmhFile(string $name = 'test_conv_sample.kmh'): UploadedFile
{
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, $name);
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$content = file_get_contents($fullPath);
@unlink($fullPath);
return UploadedFile::fake()->createWithContent($name, $content);
}
public function test_super_admin_can_inspect_uploaded_kmh_backup(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_inspect.kmh');
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $uploadedFile,
]);
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'data' => [
'filename' => 'test_conv_inspect.kmh',
],
]);
$this->assertContains('users', $response->json('data.tables'));
$this->assertContains('roles', $response->json('data.tables'));
}
public function test_inspect_rejects_non_kmh_file(): void
{
$fakeFile = UploadedFile::fake()->create('document.pdf', 100);
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $fakeFile,
]);
$response->assertStatus(422);
$response->assertJson([
'success' => false,
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
]);
}
public function test_inspect_rejects_corrupted_kmh_content(): void
{
$corruptFile = UploadedFile::fake()->createWithContent('corrupted.kmh', "KMH_ENCRYPTED_BACKUP_V1\nCorruptedHMACandPayload12345");
$response = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $corruptFile,
]);
$response->assertStatus(422);
$response->assertJson([
'success' => false,
]);
}
public function test_super_admin_can_convert_single_table_to_xlsx(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_single.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Tabel_users_', $disposition);
$this->assertStringEndsWith('.xlsx', $disposition);
}
public function test_super_admin_can_convert_multiple_tables_to_xlsx_zip(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_multi_xlsx.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users', 'roles'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/zip');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_Excel_', $disposition);
$this->assertStringEndsWith('.zip', $disposition);
}
public function test_super_admin_can_convert_tables_to_csv_zip(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_csv.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users', 'roles'],
'format' => 'csv',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/zip');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_CSV_', $disposition);
$this->assertStringEndsWith('.zip', $disposition);
}
public function test_super_admin_can_convert_tables_to_sql(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_sql.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'sql',
]);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/sql');
$disposition = $response->headers->get('Content-Disposition');
$this->assertStringContainsString('Arsip_KMH_SQL_', $disposition);
$this->assertStringEndsWith('.sql', $disposition);
}
public function test_convert_validates_required_fields(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_val.kmh');
// Tanpa tabel
$response1 = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => [],
'format' => 'xlsx',
]);
$response1->assertStatus(422);
// Format tidak valid
$response2 = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'invalid_format',
]);
$response2->assertStatus(422);
}
public function test_active_database_remains_unaffected_after_conversion(): void
{
$initialUserCount = User::count();
$this->assertGreaterThan(0, $initialUserCount);
$uploadedFile = $this->createSampleKmhFile('test_conv_safety.kmh');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'backup_file' => $uploadedFile,
'tables' => ['users'],
'format' => 'xlsx',
]);
$response->assertStatus(200);
// Pastikan jumlah user di database aktif tetap sama persis
$this->assertEquals($initialUserCount, User::count());
}
public function test_super_admin_can_convert_using_session_token_without_reuploading(): void
{
$uploadedFile = $this->createSampleKmhFile('test_conv_token.kmh');
// Step 1: Inspect and receive session token
$inspectResponse = $this->actingAs($this->superAdmin)
->postJson(route('admin.backups.converter.inspect'), [
'backup_file' => $uploadedFile,
]);
$inspectResponse->assertStatus(200);
$token = $inspectResponse->json('data.token');
$this->assertNotEmpty($token);
// Step 2: Execute conversion passing ONLY the token (zero re-upload)
$executeResponse = $this->actingAs($this->superAdmin)
->post(route('admin.backups.converter.execute'), [
'token' => $token,
'tables' => ['users'],
'format' => 'xlsx',
]);
$executeResponse->assertStatus(200);
$executeResponse->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$disposition = $executeResponse->headers->get('Content-Disposition');
$this->assertStringContainsString('Tabel_users_', $disposition);
$this->assertStringEndsWith('.xlsx', $disposition);
}
}
+107
View File
@@ -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);
}
}
+91
View File
@@ -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'));
}
}
+93
View File
@@ -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);
}
}
+127
View File
@@ -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',
]);
}
}
+2
View File
@@ -334,6 +334,8 @@ class P2hInspectionTest extends TestCase
'category' => 'unit_support',
'brand_type' => 'Manitou MT-X 733',
'unit_category' => 'Telehandler',
'unit_type' => 'Telehandler',
'operational_group' => 'HEAVY',
'status' => 'Operation',
'current_km' => 0,
]);
@@ -0,0 +1,214 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Models\Vehicle;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class QmaHeavyEquipmentThreeLevelNavigationTest extends TestCase
{
use RefreshDatabase;
private User $qmaAdmin;
protected function setUp(): void
{
parent::setUp();
$this->seed(RolePermissionSeeder::class);
$this->qmaAdmin = User::factory()->create([
'name' => 'Admin QMA Test',
'username' => 'qma_test_3level',
'role' => 'qma_admin',
]);
$this->qmaAdmin->assignRole('qma_admin');
// 1. Hauling Units (Dump Truck & Mixer Truck)
Vehicle::create([
'code' => 'DT-01',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Dump Truck',
'unit_type' => 'DUMP TRUCK',
'brand' => 'HOWO',
'brand_type' => 'HOWO SINOTRUK 336',
'model_number' => 'ZZ3257N3847',
'serial_number' => 'HW123456',
'location' => 'Main Dam',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
Vehicle::create([
'code' => 'DT-02',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Dump Truck',
'unit_type' => 'DUMP TRUCK',
'brand' => 'HOWO',
'brand_type' => 'HOWO SINOTRUK 336',
'location' => 'Adit 3',
'site_status' => 'inside_site',
'status' => 'Standby',
]);
Vehicle::create([
'code' => 'MT-01',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_category' => 'Truk Mixer',
'unit_type' => 'MIXER TRUCK',
'brand' => 'YUCHAI',
'brand_type' => 'YUCHAI DIECI',
'location' => 'Batching Plant',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
// 2. Loader Units (Excavator)
Vehicle::create([
'code' => 'EX-01',
'category' => 'unit_support',
'operational_group' => 'LOADER',
'unit_category' => 'Excavator',
'unit_type' => 'EXCAVATOR',
'brand' => 'KOMATSU',
'brand_type' => 'KOMATSU PC200-8',
'location' => 'Power House',
'site_status' => 'inside_site',
'status' => 'Operation',
]);
// 3. Support Units (Compressor)
Vehicle::create([
'code' => 'CP-01',
'category' => 'unit_support',
'operational_group' => 'SUPPORT',
'unit_category' => 'Engine Compressor',
'unit_type' => 'COMPRESSOR',
'brand' => 'AIRMAN',
'brand_type' => 'AIRMAN PDS655S',
'location' => 'Adit 2',
'site_status' => 'inside_site',
'status' => 'Breakdown',
]);
}
/**
* Level 1: Halaman utama menampilkan daftar Kelompok Operasional (HAULING, LOADER, SUPPORT, dll).
*/
public function test_level_1_shows_operational_groups(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'groups');
$response->assertViewHas('groups');
// Memastikan nama-nama kelompok operasional tampil di tabel Level 1
$response->assertSee('HAULING');
$response->assertSee('LOADER');
$response->assertSee('SUPPORT');
$response->assertSee('Lihat Kategori');
}
/**
* Level 2: Memilih salah satu Kelompok Operasional menampilkan daftar tipe alat di dalamnya.
*/
public function test_level_2_shows_types_in_selected_group(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?group=HAULING');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'types');
$response->assertViewHas('selectedGroup', 'HAULING');
// Tipe dalam kelompok HAULING
$response->assertSee('DUMP TRUCK');
$response->assertSee('MIXER TRUCK');
$typesInView = collect($response->viewData('types')->items())->pluck('unit_type')->all();
$this->assertContains('DUMP TRUCK', $typesInView);
$this->assertContains('MIXER TRUCK', $typesInView);
$this->assertNotContains('EXCAVATOR', $typesInView);
$this->assertNotContains('COMPRESSOR', $typesInView);
// Breadcrumb & tombol kembali
$response->assertSee('Semua Kelompok');
$response->assertSee('Buka Unit');
}
/**
* Level 3: Memilih tipe alat menampilkan daftar unit fisik individual.
*/
public function test_level_3_shows_physical_units(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?group=HAULING&type=DUMP+TRUCK');
$response->assertStatus(200);
$response->assertViewIs('qma.vehicles_support');
$response->assertViewHas('level', 'units');
$response->assertViewHas('selectedGroup', 'HAULING');
$response->assertViewHas('selectedType', 'DUMP TRUCK');
// Unit fisik Dump Truck
$response->assertSee('DT-01');
$response->assertSee('DT-02');
$response->assertSee('HOWO SINOTRUK 336');
$response->assertSee('Main Dam');
$codesInView = collect($response->viewData('typeUnits')->items())->pluck('code')->all();
$this->assertContains('DT-01', $codesInView);
$this->assertContains('DT-02', $codesInView);
$this->assertNotContains('MT-01', $codesInView);
$this->assertNotContains('EX-01', $codesInView);
}
/**
* Auto-detect group jika user hanya memasukkan query parameter `type`.
*/
public function test_level_3_auto_detects_group_when_only_type_passed(): void
{
$response = $this->actingAs($this->qmaAdmin)->get('/qma/vehicles/unit-support?type=EXCAVATOR');
$response->assertStatus(200);
$response->assertViewHas('level', 'units');
$response->assertViewHas('selectedGroup', 'LOADER');
$response->assertViewHas('selectedType', 'EXCAVATOR');
$response->assertSee('EX-01');
$response->assertSee('Power House');
}
/**
* Admin QMA dapat mengedit data unit alat berat termasuk divisi penanggung jawab tanpa mereset atau menambah unit baru.
*/
public function test_qma_admin_can_update_unit_support_division_and_details(): void
{
$unit = Vehicle::where('code', 'DT-01')->firstOrFail();
$response = $this->actingAs($this->qmaAdmin)->post("/qma/vehicles/{$unit->id}", [
'code' => 'DT-01',
'category' => 'unit_support',
'operational_group' => 'HAULING',
'unit_type' => 'DUMP TRUCK',
'division' => 'Civil & Dam Construction',
'status' => 'Operation',
'location' => 'Main Dam',
'site_status' => 'inside_site',
]);
$response->assertSessionHasNoErrors();
$response->assertRedirect();
$unit->refresh();
$this->assertEquals('Civil & Dam Construction', $unit->division);
$this->assertEquals('HAULING', $unit->operational_group);
$this->assertEquals('DUMP TRUCK', $unit->unit_type);
}
}
+2
View File
@@ -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',
]);
}
+57
View File
@@ -675,4 +675,61 @@ class QmaSupportTimesheetTest extends TestCase
'operator_id' => $opDt->id,
]);
}
/**
* Uji perhitungan otomatis finish HM dan durasi operasional (1 HM = 1 Jam):
* Ketika Budi mengisi 1010 dan berikutnya Joko mengisi 1012, Budi otomatis tercatat selesai di 1012 (2 jam kerja).
*/
public function test_sequential_timesheets_auto_calculate_finish_hm_and_operating_hours(): void
{
$today = Carbon::today()->toDateString();
// 1. Budi mengisi timesheet dengan start_meter 1010 (tanpa end_meter)
$budiData = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => $today,
'start_time' => '08:00',
'meter_type' => 'HM',
'start_meter' => 1010.00,
'location' => 'Adit 3',
'activity_type' => 'Galian Material',
'status' => 'Operation',
];
$res1 = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $budiData);
$res1->assertSessionHas('success');
$budiTs = UnitSupportTimesheet::where('vehicle_id', $this->supportUnit->id)->latest('id')->first();
$this->assertNotNull($budiTs);
$this->assertEquals(1010.00, (float) $budiTs->start_meter);
// 2. Joko mengisi timesheet berikutnya untuk unit yang sama dengan start_meter 1012
$jokoData = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => $today,
'start_time' => '11:00',
'meter_type' => 'HM',
'start_meter' => 1012.00,
'location' => 'Power House',
'activity_type' => 'Loading Material',
'status' => 'Operation',
];
$res2 = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $jokoData);
$res2->assertSessionHas('success');
// Budi's timesheet harus otomatis terupdate end_meter = 1012 dan operating_hours = 2.00
$budiTs->refresh();
$this->assertEquals(1012.00, (float) $budiTs->end_meter);
$this->assertEquals(2.00, (float) $budiTs->operating_hours);
// 3. Uji pada ekspor Excel: Budi's row harus memiliki finish HM 1.012,00 dan jam operasi 2,00 (tidak 0)
$excelRes = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.export_excel'));
$excelRes->assertStatus(200);
}
}
+3 -3
View File
@@ -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', [
+33
View File
@@ -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);
}
}
+95
View File
@@ -2,6 +2,7 @@
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\Gate;
use App\Models\SecurityGuard;
use App\Models\User;
@@ -175,4 +176,98 @@ class SecurityGuardFilterTest extends TestCase
$this->assertSoftDeleted('users', ['id' => $userId]);
}
}
/**
* Memastikan petugas Satpam yang dinonaktifkan tidak dapat login dan ditolak middleware.
*/
public function test_deactivated_guard_cannot_login_and_blocked_by_middleware(): void
{
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-001')->first();
$this->assertNotNull($guard);
$user = $guard->user;
$this->assertNotNull($user);
// 1. Nonaktifkan petugas satpam
$guard->update(['is_active' => false]);
// Coba login -> Harus ditolak
$loginResponse = $this->post(route('login'), [
'username' => $user->username,
'password' => 'password',
]);
$loginResponse->assertSessionHasErrors('username');
$this->assertGuest();
// 2. Jika dalam sesi aktif tapi di-nonaktifkan -> Middleware tolak dengan 403
$middlewareResponse = $this->actingAs($user)->get(route('pg.dashboard'));
$middlewareResponse->assertStatus(403);
}
public function test_admin_pg_can_edit_guard_badge_id_and_syncs_with_user_and_employee(): void
{
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-002')->first();
$this->assertNotNull($guard);
$this->assertNotNull($guard->user);
// Pastikan ada Employee dengan NIK lama
$emp = Employee::firstOrCreate(
['nik' => 'SEC-002'],
[
'user_id' => $guard->user_id,
'name' => $guard->name,
'employee_type' => 'Karyawan',
'unit_kerja' => 'Private Guard',
'division' => 'Private Guard',
'position' => 'Anggota',
]
);
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
'badge_id' => 'SEC-002-EDIT',
'name' => 'Budi Santoso Diperbarui',
'team' => 3,
'password' => 'newpassword123',
]);
$response->assertRedirect();
$response->assertSessionHasNoErrors();
// Verifikasi SecurityGuard
$guard->refresh();
$this->assertEquals('SEC-002-EDIT', $guard->badge_id);
$this->assertEquals('Budi Santoso Diperbarui', $guard->name);
$this->assertEquals(3, $guard->team);
// Verifikasi User login
$guard->user->refresh();
$this->assertEquals('SEC-002-EDIT', $guard->user->username);
$this->assertEquals('[email protected]', $guard->user->email);
// Verifikasi Employee NIK
$emp->refresh();
$this->assertEquals('SEC-002-EDIT', $emp->nik);
$this->assertEquals('Budi Santoso Diperbarui', $emp->name);
// Verifikasi login dengan ID baru dan password baru
$this->post('/logout');
$loginResponse = $this->post('/login', [
'username' => 'SEC-002-EDIT',
'password' => 'newpassword123',
]);
$loginResponse->assertRedirect();
$this->assertAuthenticatedAs($guard->user);
}
public function test_editing_guard_with_duplicate_badge_id_is_rejected(): void
{
$guard = SecurityGuard::where('badge_id', 'SEC-002')->first();
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
'badge_id' => 'SEC-001', // sudah dipakai oleh guard 1
'name' => 'Budi Duplicate',
'team' => 2,
]);
$response->assertSessionHasErrors('badge_id');
}
}
@@ -48,8 +48,7 @@ class UnitSupportBusinessProcessTest extends TestCase
->get(route('qma.vehicles.support'));
$response->assertStatus(200);
$response->assertSee('TEST-CAT');
$response->assertSee('Tambah Kategori Heavy Equipment');
$response->assertSee('Tambah Unit');
}
/**
@@ -0,0 +1,110 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\Gate;
use App\Models\User;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class UserSoftDeleteAndProtectionTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
}
public function test_deleting_user_with_operational_history_soft_deletes_cleanly_without_500(): void
{
$superAdmin = User::where('username', 'superadmin')->first();
// Buat user & employee sukon/karyawan
$user = User::factory()->create([
'name' => 'Supri Driver',
'username' => '123456',
'email' => '[email protected]',
'role' => 'employee',
]);
$user->assignRole('employee');
$employee = Employee::create([
'user_id' => $user->id,
'nik' => '123456',
'name' => 'Supri Driver',
'employee_type' => 'Sukon',
'division' => 'subkon',
'position' => 'Driver',
'is_operator' => true,
]);
$gate = Gate::first() ?: Gate::create(['name' => 'Gate Utama', 'code' => 'GU-01']);
$vehicle = Vehicle::first() ?: Vehicle::factory()->create();
// Buat aktivitas riwayat operasional kendaraan
$activity = VehicleActivity::create([
'transaction_no' => 'TRX-SUPRI-001',
'vehicle_id' => $vehicle->id,
'driver_id' => $employee->id,
'gate_id' => $gate->id,
'direction' => 'out',
'previous_km' => 1000,
'current_km' => 1050,
'distance' => 50,
'purpose' => 'Pengiriman Material',
'recorded_at' => now(),
'status' => 'approved',
]);
// Super Admin menghapus akun user Supri dari menu Kelola Pengguna
$response = $this->actingAs($superAdmin)
->delete(route('admin.users.destroy', $user->id));
// Harus berhasil redirect tanpa error 500
$response->assertStatus(302);
$response->assertRedirect(route('admin.users.index'));
$response->assertSessionHas('success');
// Pastikan User & Employee berstatus Soft Deleted (ada di tong sampah)
$this->assertSoftDeleted('users', ['id' => $user->id]);
$this->assertSoftDeleted('employees', ['id' => $employee->id]);
// Pastikan riwayat aktivitas operasional tetap UTUH dan tidak hilang
$this->assertDatabaseHas('vehicle_activities', [
'id' => $activity->id,
'driver_id' => $employee->id,
]);
// Coba lakukan Hapus Permanen dari Tong Sampah -> Harus ditolak karena integritas audit
$forceResponse = $this->actingAs($superAdmin)
->delete(route('admin.trash.force_delete', [
'category' => 'users',
'id' => $user->id,
]));
$forceResponse->assertStatus(302);
$forceResponse->assertSessionHas('error');
// User tetap ada di basis data (tidak terhapus permanen)
$this->assertDatabaseHas('users', ['id' => $user->id]);
// Pulihkan akun dari Tong Sampah -> User & Employee harus aktif kembali beserta perannya
$restoreResponse = $this->actingAs($superAdmin)
->post(route('admin.trash.restore', [
'category' => 'users',
'id' => $user->id,
]));
$restoreResponse->assertStatus(302);
$restoreResponse->assertSessionHas('success');
$this->assertNotSoftDeleted('users', ['id' => $user->id]);
$this->assertNotSoftDeleted('employees', ['id' => $employee->id]);
$this->assertTrue($user->fresh()->hasRole('employee'));
}
}