Compare commits
12
Commits
b8fa1771b9
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f655c3af1e | ||
|
|
29f878e0e7 | ||
|
|
dc069fe0ec | ||
|
|
a55ead4c5b | ||
|
|
61332f948b | ||
|
|
c1be96c2ba | ||
|
|
6e5c6eeeb8 | ||
|
|
ff3ab616e0 | ||
|
|
5a4969b467 | ||
|
|
2fe265da37 | ||
|
|
008e5f6b9d | ||
|
|
23377631b3 |
+2
-1
@@ -21,4 +21,5 @@
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
Thumbs.db
|
||||
/Berkas/
|
||||
/Berkas/*
|
||||
!/Berkas/DATA LOKASI TERBARU RKM KMH.xlsx
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\UnitSupportTimesheet;
|
||||
use App\Models\UnitTransfer;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use App\Models\VehicleLocationHistory;
|
||||
use App\Services\TrashService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class CleanTestLogsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'kmh:clean-test-logs
|
||||
{--force : Jalankan pembersihan tanpa konfirmasi interaktif}
|
||||
{--include-he : Sertakan juga pembersihan timesheet alat berat & transfer unit}
|
||||
{--empty-trash : Kosongkan seluruh item di Tong Sampah}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Bersihkan seluruh riwayat transaksi uji coba (Timesheet LV, Riwayat Pos Gerbang, Log Aktivitas Admin) menjelang launching.';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(TrashService $trashService): int
|
||||
{
|
||||
$this->info('===============================================================');
|
||||
$this->info(' PEMBERSIHAN DATA UJI COBA (PRE-LAUNCH CLEAN SLATE) - RKM-KMH ');
|
||||
$this->info('===============================================================');
|
||||
$this->warn('Perintah ini akan membersihkan data riwayat pengujian:');
|
||||
$this->line(' - Riwayat Perjalanan LV / Perlintasan Gerbang (vehicle_activities)');
|
||||
$this->line(' - Riwayat Mutasi Lokasi Kendaraan (vehicle_location_histories)');
|
||||
$this->line(' - Log Riwayat Aktivitas Admin (admin_activity_logs)');
|
||||
|
||||
if ($this->option('include-he')) {
|
||||
$this->line(' - Timesheet Kendaraan Berat / HE (unit_support_timesheets)');
|
||||
$this->line(' - Riwayat Mobilisasi / Transfer Unit (unit_transfers)');
|
||||
}
|
||||
|
||||
if ($this->option('empty-trash')) {
|
||||
$this->line(' - Seluruh data di Tong Sampah (Recycle Bin)');
|
||||
}
|
||||
|
||||
$this->info("\nMaster Kendaraan, Data Karyawan, SIMPER, Pos Gerbang & Akun Pengguna TETAP 100% UTUH.");
|
||||
|
||||
if (!$this->option('force')) {
|
||||
if (!$this->confirm('Apakah Anda yakin ingin melanjutkan pembersihan riwayat uji coba ini?', false)) {
|
||||
$this->warn('Operasi pembersihan dibatalkan.');
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
$this->output->write('Sedang membersihkan log riwayat uji coba... ');
|
||||
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
try {
|
||||
// 1. Bersihkan Catatan Perjalanan LV & Perlintasan Gerbang
|
||||
$activityCount = DB::table('vehicle_activities')->count();
|
||||
DB::table('vehicle_activities')->truncate();
|
||||
|
||||
// 2. Bersihkan Riwayat Lokasi Kendaraan
|
||||
$locationHistoryCount = DB::table('vehicle_location_histories')->count();
|
||||
DB::table('vehicle_location_histories')->truncate();
|
||||
|
||||
// 3. Bersihkan Log Aktivitas Admin
|
||||
$adminLogCount = DB::table('admin_activity_logs')->count();
|
||||
DB::table('admin_activity_logs')->truncate();
|
||||
|
||||
// 4. Bersihkan Timesheet HE & Transfer jika dipilih
|
||||
$heCount = 0;
|
||||
$transferCount = 0;
|
||||
if ($this->option('include-he')) {
|
||||
$heCount = DB::table('unit_support_timesheets')->count();
|
||||
DB::table('unit_support_timesheets')->truncate();
|
||||
|
||||
$transferCount = DB::table('unit_transfers')->count();
|
||||
DB::table('unit_transfers')->truncate();
|
||||
}
|
||||
|
||||
// 5. Reset status site kendaraan kembali ke default ('inside_site')
|
||||
DB::table('vehicles')->update([
|
||||
'site_status' => 'inside_site',
|
||||
'location_updated_at' => null,
|
||||
'location_updated_by' => null,
|
||||
'location_note' => null,
|
||||
]);
|
||||
|
||||
// 6. Kosongkan Tong Sampah jika diminta
|
||||
$trashCount = 0;
|
||||
if ($this->option('empty-trash')) {
|
||||
$trashCount = $trashService->emptyTrash();
|
||||
}
|
||||
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
$this->info("SELESAI!\n");
|
||||
$this->table(['Kategori Log Dibersihkan', 'Jumlah Data Terhapus'], [
|
||||
['Riwayat Perjalanan LV (vehicle_activities)', number_format($activityCount)],
|
||||
['Riwayat Mutasi Lokasi (vehicle_location_histories)', number_format($locationHistoryCount)],
|
||||
['Log Riwayat Aktivitas Admin (admin_activity_logs)', number_format($adminLogCount)],
|
||||
['Timesheet Alat Berat / HE', $this->option('include-he') ? number_format($heCount) : 'Dilewati'],
|
||||
['Riwayat Transfer Unit', $this->option('include-he') ? number_format($transferCount) : 'Dilewati'],
|
||||
['Tong Sampah (Recycle Bin)', $this->option('empty-trash') ? number_format($trashCount) : 'Dilewati'],
|
||||
]);
|
||||
|
||||
$this->info("\nSistem sekarang bersih dan siap digunakan untuk peluncuran resmi (Launching)! 🎉");
|
||||
return Command::SUCCESS;
|
||||
} catch (\Throwable $e) {
|
||||
Schema::enableForeignKeyConstraints();
|
||||
$this->error("\nTerjadi kesalahan: " . $e->getMessage());
|
||||
return Command::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\User;
|
||||
@@ -105,6 +106,20 @@ class ImportSecurityGuardsCommand extends Command
|
||||
$updatedGuards++;
|
||||
}
|
||||
|
||||
// 3. Sinkronisasi Profil Master Personil / Karyawan (Data SIMPER)
|
||||
Employee::updateOrCreate(
|
||||
['nik' => $username],
|
||||
[
|
||||
'user_id' => $user->id,
|
||||
'name' => $p['name'],
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
'is_operator' => false,
|
||||
]
|
||||
);
|
||||
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
|
||||
@@ -31,19 +31,25 @@ class SyncExcelVehicleDataCommand extends Command
|
||||
public function handle(): int
|
||||
{
|
||||
$filePath = base_path($this->option('file'));
|
||||
if (!file_exists($filePath)) {
|
||||
$this->error("Berkas Excel tidak ditemukan di: {$filePath}");
|
||||
return self::FAILURE;
|
||||
$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...");
|
||||
}
|
||||
|
||||
$this->info("Membaca berkas: {$filePath} ...");
|
||||
$rows = SimpleXlsxImporter::parse($filePath);
|
||||
$totalRows = count($rows);
|
||||
$this->info("Total baris terbaca: {$totalRows}");
|
||||
|
||||
if ($totalRows < 2) {
|
||||
$this->warn('Berkas Excel kosong atau tidak memiliki baris data.');
|
||||
return self::SUCCESS;
|
||||
if ($hasExcel) {
|
||||
$this->info("Total baris terbaca: {$totalRows}");
|
||||
}
|
||||
|
||||
$updatedCount = 0;
|
||||
@@ -51,12 +57,13 @@ class SyncExcelVehicleDataCommand extends Command
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
for ($i = 1; $i < $totalRows; $i++) {
|
||||
$r = $rows[$i];
|
||||
$code1 = trim($r[4] ?? '');
|
||||
if (!$code1) {
|
||||
continue;
|
||||
}
|
||||
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';
|
||||
@@ -205,8 +212,9 @@ class SyncExcelVehicleDataCommand extends Command
|
||||
'recorded_at' => Carbon::now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback untuk unit support yang belum memiliki operational_group
|
||||
// Fallback untuk unit support yang belum memiliki operational_group
|
||||
$typeFallback = [
|
||||
'DUMP TRUCK' => 'HAULING',
|
||||
'DUMP TRUCK FFT' => 'HAULING',
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,21 +434,36 @@ class BackupController extends Controller
|
||||
public function converterInspect(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'backup_file' => 'required|file',
|
||||
'backup_file' => 'nullable|file',
|
||||
'server_filename' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$file = $request->file('backup_file');
|
||||
$originalName = $file->getClientOriginalName();
|
||||
|
||||
if (!str_ends_with(strtolower($originalName), '.kmh')) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$metadata = $this->converterService->inspectUploadedFile($file);
|
||||
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,
|
||||
|
||||
@@ -73,24 +73,28 @@ class TrashController extends Controller
|
||||
*/
|
||||
public function forceDelete(string $category, int $id): RedirectResponse
|
||||
{
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
try {
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
|
||||
if (!$success) {
|
||||
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
|
||||
if (!$success) {
|
||||
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
|
||||
}
|
||||
|
||||
$catDefinitions = TrashService::getCategoryDefinitions();
|
||||
$label = $catDefinitions[$category]['label'] ?? $category;
|
||||
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Tong Sampah',
|
||||
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
|
||||
targetType: $category,
|
||||
targetId: $id
|
||||
);
|
||||
|
||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||
} catch (\Throwable $e) {
|
||||
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$catDefinitions = TrashService::getCategoryDefinitions();
|
||||
$label = $catDefinitions[$category]['label'] ?? $category;
|
||||
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Tong Sampah',
|
||||
description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).",
|
||||
targetType: $category,
|
||||
targetId: $id
|
||||
);
|
||||
|
||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Services\ImageCompressionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
@@ -419,23 +420,29 @@ class UserController extends Controller
|
||||
$userRole = $user->role ?? '';
|
||||
$userId = $user->id;
|
||||
|
||||
$user->syncRoles([]);
|
||||
$user->delete();
|
||||
try {
|
||||
DB::transaction(function () use ($user) {
|
||||
$user->delete();
|
||||
});
|
||||
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
|
||||
} catch (\Throwable $e) {
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('error', 'Gagal menghapus pengguna: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -47,6 +47,18 @@ class LoginController extends Controller
|
||||
/** @var \App\Models\User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
// Proteksi: Cek apakah akun Petugas Satpam berstatus Nonaktif
|
||||
$guard = $user->securityGuard ?: \App\Models\SecurityGuard::where('user_id', $user->id)->first();
|
||||
if ($guard && ! $guard->is_active && ! $user->isSuperAdmin()) {
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return back()->withErrors([
|
||||
'username' => 'Akun Petugas Satpam Anda berstatus Nonaktif. Silakan hubungi Administrator Pos Gerbang (PG) untuk mengaktifkan kembali.',
|
||||
])->onlyInput('username');
|
||||
}
|
||||
|
||||
if ($request->session()->has('url.intended')) {
|
||||
return redirect()->intended()
|
||||
->with('success', "Selamat datang kembali, {$user->name}!");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers\Hse;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Carbon\Carbon;
|
||||
use App\Models\Employee;
|
||||
use App\Models\EmployeeSimper;
|
||||
use App\Models\SimperType;
|
||||
@@ -508,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([
|
||||
@@ -617,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'));
|
||||
@@ -752,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'));
|
||||
@@ -802,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;
|
||||
@@ -833,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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -160,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') {
|
||||
@@ -180,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) {
|
||||
@@ -238,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') {
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1446,12 +1446,12 @@ class VehicleController extends Controller
|
||||
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
// Otomatis buatkan Master Template P2H baru jika belum ada
|
||||
$templateCode = $vehicle->unit_type ?: $vehicle->code;
|
||||
$templateCode = $vehicle->code;
|
||||
$template = P2hTemplate::firstOrCreate(
|
||||
['code' => $templateCode],
|
||||
[
|
||||
'name' => $vehicle->unit_type ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk {$vehicle->unit_type} (Kode: {$templateCode}).",
|
||||
'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,
|
||||
]
|
||||
);
|
||||
@@ -1471,18 +1471,30 @@ 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' => [$vehicle->isSupportCategory() ? 'nullable' : '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' => ['required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'numeric', 'min:0'],
|
||||
'current_km' => ['nullable', 'numeric', 'min:0'],
|
||||
'operational_group' => ['nullable', 'string', 'max:50'],
|
||||
'unit_category' => ['nullable', 'string', 'max:100'],
|
||||
'unit_type' => ['nullable', 'string', 'max:100'],
|
||||
@@ -1504,11 +1516,9 @@ 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->isSupportCategory()) {
|
||||
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']));
|
||||
|
||||
@@ -27,6 +27,12 @@ class CheckRole
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Proteksi: Cek apakah petugas satpam berstatus Nonaktif
|
||||
$guard = $user->securityGuard ?: \App\Models\SecurityGuard::where('user_id', $user->id)->first();
|
||||
if ($guard && ! $guard->is_active) {
|
||||
abort(403, 'Akses Ditolak: Akun Petugas Satpam Anda berstatus Nonaktif. Silakan hubungi Administrator PG.');
|
||||
}
|
||||
|
||||
// Cek via kolom role string atau Spatie hasAnyRole
|
||||
if (in_array($userRole, $roles) || (method_exists($user, 'hasAnyRole') && $user->hasAnyRole($roles))) {
|
||||
return $next($request);
|
||||
|
||||
@@ -32,7 +32,7 @@ class EmployeeSimper extends Model
|
||||
|
||||
public function employee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class);
|
||||
return $this->belongsTo(Employee::class)->withTrashed();
|
||||
}
|
||||
|
||||
public function simperType(): BelongsTo
|
||||
|
||||
@@ -49,7 +49,7 @@ class P2hRecord extends Model
|
||||
|
||||
public function employee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class);
|
||||
return $this->belongsTo(Employee::class)->withTrashed();
|
||||
}
|
||||
|
||||
public function template(): BelongsTo
|
||||
|
||||
@@ -98,6 +98,7 @@ class SimperType extends Model
|
||||
protected $appends = [
|
||||
'scopes',
|
||||
'category_scope_display',
|
||||
'short_scope_display',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -184,6 +185,34 @@ class SimperType extends Model
|
||||
return implode(', ', $formatted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Teks ringkas pendek untuk badge di UI (maksimal 2 kategori + counter jika panjang).
|
||||
*/
|
||||
public function getShortScopeDisplayAttribute(): string
|
||||
{
|
||||
$scopes = $this->scopes;
|
||||
|
||||
if (empty($scopes) || in_array(self::SCOPE_ALL, $scopes, true)) {
|
||||
return 'UNIVERSAL';
|
||||
}
|
||||
|
||||
if (count($scopes) === 1 && $scopes[0] === self::SCOPE_LIGHT_VEHICLE) {
|
||||
return 'LV';
|
||||
}
|
||||
|
||||
$formatted = array_map(function ($s) {
|
||||
if ($s === self::SCOPE_LIGHT_VEHICLE) return 'LV';
|
||||
if ($s === self::SCOPE_ALL) return 'Universal';
|
||||
return strtoupper(str_replace('_', ' ', $s));
|
||||
}, $scopes);
|
||||
|
||||
if (count($formatted) > 2) {
|
||||
return $formatted[0] . ', ' . $formatted[1] . ' (+' . (count($formatted) - 2) . ')';
|
||||
}
|
||||
|
||||
return implode(', ', $formatted);
|
||||
}
|
||||
|
||||
public function employeeSimpers(): HasMany
|
||||
{
|
||||
return $this->hasMany(EmployeeSimper::class);
|
||||
|
||||
@@ -57,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
|
||||
|
||||
@@ -68,7 +68,7 @@ class UnitTransfer extends Model
|
||||
*/
|
||||
public function transporterDriver(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class, 'transporter_driver_id');
|
||||
return $this->belongsTo(Employee::class, 'transporter_driver_id')->withTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+18
-9
@@ -33,17 +33,26 @@ class User extends Authenticatable
|
||||
});
|
||||
|
||||
static::deleting(function (User $user) {
|
||||
if ($user->employee) {
|
||||
if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
$employee = $user->employee ?: Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
$guard = $user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first();
|
||||
|
||||
if ($user->isForceDeleting()) {
|
||||
$employeeTrashed = $employee ?: Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
if ($employeeTrashed && ($employeeTrashed->activities()->exists() || $employeeTrashed->p2hRecords()->exists() || $employeeTrashed->supportTimesheets()->exists())) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
}
|
||||
$user->employee->delete();
|
||||
}
|
||||
if ($user->securityGuard) {
|
||||
if ($user->securityGuard->activities()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
$guardTrashed = $guard ?: SecurityGuard::withTrashed()->where('user_id', $user->id)->first();
|
||||
if ($guardTrashed && $guardTrashed->activities()->exists()) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
}
|
||||
} else {
|
||||
// Soft delete: cukup cascade soft delete data employee & securityGuard jika ada dan belum terhapus
|
||||
if ($employee && ! $employee->trashed()) {
|
||||
$employee->delete();
|
||||
}
|
||||
if ($guard && ! $guard->trashed()) {
|
||||
$guard->delete();
|
||||
}
|
||||
$user->securityGuard->delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ class VehicleActivity extends Model
|
||||
|
||||
public function driver(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Employee::class, 'driver_id');
|
||||
return $this->belongsTo(Employee::class, 'driver_id')->withTrashed();
|
||||
}
|
||||
|
||||
public function gate(): BelongsTo
|
||||
|
||||
@@ -149,8 +149,8 @@ class DatabaseBackupService
|
||||
*/
|
||||
public function createKmhBackup(?array $selectedTables = null, bool $includeMedia = false, ?string $customFilename = null): string
|
||||
{
|
||||
@set_time_limit(600);
|
||||
@ini_set('memory_limit', '512M');
|
||||
@set_time_limit(3600);
|
||||
@ini_set('memory_limit', '1024M');
|
||||
|
||||
if (!class_exists('ZipArchive')) {
|
||||
throw new RuntimeException('Ekstensi PHP ZipArchive diperlukan untuk memaketkan arsip.');
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,6 +14,102 @@ class KmhConverterService
|
||||
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.
|
||||
@@ -32,6 +128,9 @@ class KmhConverterService
|
||||
*/
|
||||
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.");
|
||||
@@ -81,9 +180,9 @@ class KmhConverterService
|
||||
$tempDir = storage_path('app/temp_converter');
|
||||
File::ensureDirectoryExists($tempDir);
|
||||
|
||||
// Bersihkan file sementara yang lebih tua dari 30 menit
|
||||
// Bersihkan file sementara yang lebih tua dari 1 jam (3600 detik)
|
||||
foreach (File::files($tempDir) as $f) {
|
||||
if ((time() - $f->getMTime()) > 1800) {
|
||||
if ((time() - $f->getMTime()) > 3600) {
|
||||
@unlink($f->getPathname());
|
||||
}
|
||||
}
|
||||
@@ -160,6 +259,9 @@ class KmhConverterService
|
||||
*/
|
||||
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}");
|
||||
|
||||
@@ -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,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).");
|
||||
|
||||
@@ -10,10 +10,10 @@ server {
|
||||
|
||||
client_max_body_size 500M;
|
||||
client_body_buffer_size 1M;
|
||||
client_body_timeout 600s;
|
||||
client_header_timeout 600s;
|
||||
send_timeout 600s;
|
||||
keepalive_timeout 600s;
|
||||
client_body_timeout 3600s;
|
||||
client_header_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
keepalive_timeout 3600s;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
@@ -61,8 +61,8 @@ server {
|
||||
fastcgi_hide_header X-Powered-By;
|
||||
fastcgi_buffers 16 16k;
|
||||
fastcgi_buffer_size 32k;
|
||||
fastcgi_read_timeout 600;
|
||||
fastcgi_send_timeout 600;
|
||||
fastcgi_read_timeout 3600;
|
||||
fastcgi_send_timeout 3600;
|
||||
}
|
||||
|
||||
location ~ /\.(?!well-known).* {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
upload_max_filesize = 500M
|
||||
post_max_size = 500M
|
||||
memory_limit = 1024M
|
||||
max_execution_time = 600
|
||||
max_input_time = 600
|
||||
max_execution_time = 3600
|
||||
max_input_time = 3600
|
||||
date.timezone = Asia/Jakarta
|
||||
expose_php = Off
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -235,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">
|
||||
@@ -1012,7 +1019,7 @@
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', form.action, true);
|
||||
xhr.timeout = 600000; // 10 Menit timeout untuk berkas backup besar
|
||||
xhr.timeout = 3600000; // 1 Jam timeout untuk berkas backup besar
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
|
||||
xhr.upload.onprogress = function(e) {
|
||||
@@ -1083,7 +1090,7 @@
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
}
|
||||
if (text) text.textContent = 'Mulai Pemulihan Sistem';
|
||||
document.getElementById('directRestoreErrorMessage').textContent = 'Waktu pengunggahan habis (Timeout 10 Menit). Silakan periksa kestabilan jaringan internet Anda.';
|
||||
document.getElementById('directRestoreErrorMessage').textContent = 'Waktu pengunggahan habis (Timeout 1 Jam). Silakan periksa kestabilan jaringan internet Anda.';
|
||||
document.getElementById('directRestoreError').classList.remove('hidden');
|
||||
};
|
||||
|
||||
@@ -1222,6 +1229,79 @@
|
||||
}
|
||||
}
|
||||
|
||||
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!');
|
||||
@@ -1252,7 +1332,7 @@
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', `{{ route('admin.backups.converter.inspect') }}`, true);
|
||||
xhr.timeout = 600000; // 10 Menit timeout
|
||||
xhr.timeout = 3600000; // 1 Jam timeout
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
xhr.setRequestHeader('Accept', 'application/json');
|
||||
|
||||
@@ -1331,7 +1411,7 @@
|
||||
xhr.ontimeout = function() {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError('Waktu pengunggahan habis (Timeout 10 Menit). Silakan periksa kestabilan jaringan internet Anda.');
|
||||
showConverterError('Waktu pengunggahan habis (Timeout 1 Jam). Silakan periksa kestabilan jaringan internet Anda.');
|
||||
};
|
||||
|
||||
xhr.send(formData);
|
||||
|
||||
@@ -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>
|
||||
@@ -250,13 +250,14 @@
|
||||
</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 }}"
|
||||
{{ $isChecked ? '' : 'disabled' }}
|
||||
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>
|
||||
@@ -365,16 +366,28 @@
|
||||
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;
|
||||
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 = '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
@@ -919,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">
|
||||
@@ -1200,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();
|
||||
@@ -1234,16 +1259,28 @@
|
||||
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;
|
||||
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 = '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,20 +657,14 @@
|
||||
<!-- Form Penolakan -->
|
||||
<form id="rejectForm" method="POST" action="" class="space-y-4">
|
||||
@csrf
|
||||
@if($currentGuard)
|
||||
<input type="hidden" name="security_guard_id" value="{{ $currentGuard->id }}">
|
||||
@elseif($guards->isNotEmpty())
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-700 mb-1">
|
||||
Petugas Satpam Pemeriksa <span class="text-rose-500">*</span>
|
||||
</label>
|
||||
<select name="security_guard_id" required class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-semibold focus:outline-none focus:border-rose-600">
|
||||
@foreach($guards as $g)
|
||||
<option value="{{ $g->id }}">{{ $g->name }} (Reg: {{ $g->badge_id }})</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</div>
|
||||
@endif
|
||||
<!-- 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>
|
||||
|
||||
@@ -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 -->
|
||||
|
||||
@@ -658,7 +658,6 @@
|
||||
}, 500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Panduan Halaman Modal
|
||||
function openGuideModal() {
|
||||
|
||||
@@ -529,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>
|
||||
@@ -883,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>
|
||||
@@ -1604,6 +1632,12 @@
|
||||
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');
|
||||
@@ -1654,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];
|
||||
|
||||
@@ -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
|
||||
@@ -873,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 = '';
|
||||
@@ -1020,5 +1053,103 @@
|
||||
text.innerHTML = `Armada luar (<strong>${displayName}</strong>) diberangkatkan dari <strong>${displayOrigin}</strong> → Menjemput alat berat di <strong>${originLoc}</strong> → Mengantarkannya ke tujuan <strong>${destLoc}</strong>.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Realtime Dropdown Lokasi Awal berdasarkan Ketikan
|
||||
*/
|
||||
function filterOriginLocationSelect(query) {
|
||||
const select = document.getElementById('origin_location');
|
||||
const clearBtn = document.getElementById('clearOriginLocationFilterBtn');
|
||||
if (!select) return;
|
||||
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
if (clearBtn) {
|
||||
clearBtn.classList.toggle('hidden', !q);
|
||||
}
|
||||
|
||||
let visibleCount = 0;
|
||||
let firstMatch = null;
|
||||
|
||||
Array.from(select.options).forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (opt.value === 'ALL') {
|
||||
opt.hidden = q.length > 0 && !opt.textContent.toLowerCase().includes(q);
|
||||
if (!opt.hidden && !firstMatch) firstMatch = opt;
|
||||
return;
|
||||
}
|
||||
const match = opt.textContent.toLowerCase().includes(q) || opt.value.toLowerCase().includes(q);
|
||||
opt.hidden = !match;
|
||||
if (match) {
|
||||
visibleCount++;
|
||||
if (!firstMatch) firstMatch = opt;
|
||||
}
|
||||
});
|
||||
|
||||
if (q && visibleCount === 1 && firstMatch) {
|
||||
select.value = firstMatch.value;
|
||||
onOriginLocationChanged(firstMatch.value);
|
||||
}
|
||||
}
|
||||
|
||||
function clearOriginLocationFilter() {
|
||||
const input = document.getElementById('originLocationSearch');
|
||||
if (input) input.value = '';
|
||||
filterOriginLocationSelect('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Realtime Dropdown Unit Alat Berat berdasarkan Ketikan Kode / Merek
|
||||
*/
|
||||
function filterHeavyUnitOptions(query) {
|
||||
const select = document.getElementById('vehicle_id');
|
||||
const clearBtn = document.getElementById('clearHeavyUnitFilterBtn');
|
||||
const badge = document.getElementById('unitCounterBadge');
|
||||
if (!select) return;
|
||||
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
if (clearBtn) {
|
||||
clearBtn.classList.toggle('hidden', !q);
|
||||
}
|
||||
|
||||
let visibleCount = 0;
|
||||
let firstMatch = null;
|
||||
|
||||
Array.from(select.options).forEach(opt => {
|
||||
if (!opt.value) {
|
||||
opt.hidden = false;
|
||||
return;
|
||||
}
|
||||
const code = (opt.getAttribute('data-code') || '').toLowerCase();
|
||||
const brand = (opt.getAttribute('data-brand') || '').toLowerCase();
|
||||
const cat = (opt.getAttribute('data-category') || '').toLowerCase();
|
||||
const text = opt.textContent.toLowerCase();
|
||||
|
||||
const match = text.includes(q) || code.includes(q) || brand.includes(q) || cat.includes(q);
|
||||
opt.hidden = !match;
|
||||
if (match) {
|
||||
visibleCount++;
|
||||
if (!firstMatch) firstMatch = opt;
|
||||
}
|
||||
});
|
||||
|
||||
if (badge) {
|
||||
badge.classList.remove('hidden');
|
||||
badge.textContent = q ? `${visibleCount} Unit Cocok` : `${visibleCount} Unit Tersedia`;
|
||||
}
|
||||
|
||||
if (q && visibleCount === 1 && firstMatch) {
|
||||
select.value = firstMatch.value;
|
||||
onHeavyUnitSelected(select);
|
||||
}
|
||||
}
|
||||
|
||||
function clearHeavyUnitFilter() {
|
||||
const input = document.getElementById('heavyUnitSearch');
|
||||
if (input) input.value = '';
|
||||
filterHeavyUnitOptions('');
|
||||
}
|
||||
</script>
|
||||
@endsection
|
||||
|
||||
@@ -654,6 +654,12 @@
|
||||
@endforeach
|
||||
</datalist>
|
||||
|
||||
<datalist id="divisionsDatalist">
|
||||
@foreach($availableDivisions ?? [] as $div)
|
||||
<option value="{{ $div }}">{{ $div }}</option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
|
||||
<!-- ========================================================================= -->
|
||||
<!-- MODAL: TAMBAH UNIT ALAT BERAT (HEAVY EQUIPMENT) -->
|
||||
<!-- ========================================================================= -->
|
||||
@@ -826,14 +832,21 @@
|
||||
<!-- Baris 7: Divisi & Kepemilikan Aset -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1">Divisi Penanggung Jawab</label>
|
||||
<select name="division"
|
||||
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition font-medium">
|
||||
<option value="">-- Pilih Divisi Penanggung Jawab --</option>
|
||||
@foreach($availableDivisions as $div)
|
||||
<option value="{{ $div }}" {{ old('division') === $div ? 'selected' : '' }}>{{ $div }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1 flex items-center justify-between">
|
||||
<span>Divisi Penanggung Jawab</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / filter</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-building absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<input type="text"
|
||||
name="division"
|
||||
id="addDivision"
|
||||
list="divisionsDatalist"
|
||||
value="{{ old('division') }}"
|
||||
placeholder="Ketik atau pilih divisi..."
|
||||
autocomplete="off"
|
||||
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition font-medium">
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1">Kepemilikan Aset (Owner)</label>
|
||||
@@ -894,6 +907,7 @@
|
||||
<form id="editVehicleForm" action="" method="POST" enctype="multipart/form-data" class="space-y-4">
|
||||
@csrf
|
||||
<input type="hidden" name="category" value="unit_support">
|
||||
<input type="hidden" name="brand_type" id="editBrandType" value="">
|
||||
|
||||
<!-- Foto Unit -->
|
||||
<div>
|
||||
@@ -1029,14 +1043,20 @@
|
||||
<!-- Baris 7: Divisi & Kepemilikan -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1">Divisi Penanggung Jawab</label>
|
||||
<select name="division" id="editDivision"
|
||||
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition font-medium">
|
||||
<option value="">-- Pilih Divisi Penanggung Jawab --</option>
|
||||
@foreach($availableDivisions as $div)
|
||||
<option value="{{ $div }}">{{ $div }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1 flex items-center justify-between">
|
||||
<span>Divisi Penanggung Jawab</span>
|
||||
<span class="text-[10px] text-emerald-700 font-semibold">Bisa ketik / filter</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<i class="fa-solid fa-building absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
|
||||
<input type="text"
|
||||
name="division"
|
||||
id="editDivision"
|
||||
list="divisionsDatalist"
|
||||
placeholder="Ketik atau pilih divisi..."
|
||||
autocomplete="off"
|
||||
class="w-full pl-9 pr-3.5 py-2.5 text-xs rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-2 focus:ring-[#1b5e20]/10 transition font-medium">
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-bold text-slate-800 mb-1">Kepemilikan Aset (Owner)</label>
|
||||
@@ -1561,8 +1581,11 @@
|
||||
|
||||
function openEditModal(v) {
|
||||
document.getElementById('editVehicleModal').classList.remove('hidden');
|
||||
document.getElementById('editVehicleForm').action = `/qma/vehicles/${v.id}`;
|
||||
document.getElementById('editVehicleForm').action = "{{ url('qma/vehicles') }}/" + v.id;
|
||||
document.getElementById('editCode').value = v.code || '';
|
||||
if (document.getElementById('editBrandType')) {
|
||||
document.getElementById('editBrandType').value = v.brand_type || '';
|
||||
}
|
||||
currentEditVehicleCode = (v.code || '').trim().toUpperCase();
|
||||
hideEditCodeError();
|
||||
|
||||
@@ -1606,26 +1629,9 @@
|
||||
document.getElementById('editFuelConsumption').value = v.fuel_consumption || '';
|
||||
}
|
||||
|
||||
const divSelect = document.getElementById('editDivision');
|
||||
if (divSelect) {
|
||||
if (v.division) {
|
||||
let found = false;
|
||||
for (let i = 0; i < divSelect.options.length; i++) {
|
||||
if (divSelect.options[i].value === v.division) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
const newOpt = document.createElement('option');
|
||||
newOpt.value = v.division;
|
||||
newOpt.textContent = v.division;
|
||||
divSelect.appendChild(newOpt);
|
||||
}
|
||||
divSelect.value = v.division;
|
||||
} else {
|
||||
divSelect.value = '';
|
||||
}
|
||||
const divInput = document.getElementById('editDivision');
|
||||
if (divInput) {
|
||||
divInput.value = v.division || '';
|
||||
}
|
||||
|
||||
const editPhotoPreview = document.getElementById('editPhotoPreview');
|
||||
|
||||
@@ -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');
|
||||
|
||||
+2
-1
@@ -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,6 +214,7 @@ 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');
|
||||
|
||||
@@ -310,4 +310,33 @@ class BackupAndRestoreTest extends TestCase
|
||||
'target_name' => 'backup_dari_pc.kmh',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_inspect_and_convert_server_backup_file(): void
|
||||
{
|
||||
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, 'test_server_conv.kmh');
|
||||
|
||||
// 1. Inspect server file via AJAX
|
||||
$inspectResponse = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'server_filename' => $filename,
|
||||
]);
|
||||
|
||||
$inspectResponse->assertStatus(200);
|
||||
$inspectResponse->assertJson([
|
||||
'success' => true,
|
||||
]);
|
||||
$token = $inspectResponse->json('data.token');
|
||||
$this->assertNotEmpty($token);
|
||||
|
||||
// 2. Convert using token to SQL
|
||||
$convResponse = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'token' => $token,
|
||||
'tables' => ['users'],
|
||||
'format' => 'sql',
|
||||
]);
|
||||
|
||||
$convResponse->assertStatus(200);
|
||||
$this->assertEquals('application/sql', $convResponse->headers->get('Content-Type'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -284,4 +284,97 @@ class HseEmployeeImportTest extends TestCase
|
||||
'simper_expired_at' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_import_restores_soft_deleted_user_and_employee_without_duplicate_error(): void
|
||||
{
|
||||
// Simulasi kondisi VPS: User dan Employee dengan NIK 1111 pernah dihapus ke Tong Sampah
|
||||
$user = User::create([
|
||||
'username' => '1111',
|
||||
'name' => 'Ruadi Lama',
|
||||
'email' => '[email protected]',
|
||||
'password' => Hash::make('password'),
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$employee = Employee::create([
|
||||
'nik' => '1111',
|
||||
'name' => 'Ruadi Lama',
|
||||
'unit_kerja' => 'Umum',
|
||||
'division' => 'GA',
|
||||
'position' => 'Staff',
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
|
||||
$user->delete(); // Soft delete ke Tong Sampah
|
||||
$employee->delete(); // Soft delete ke Tong Sampah
|
||||
|
||||
$this->assertSoftDeleted('users', ['username' => '1111']);
|
||||
$this->assertSoftDeleted('employees', ['nik' => '1111']);
|
||||
|
||||
// Impor file yang mengandung NIK 1111
|
||||
$csvContent = implode("\n", [
|
||||
'No,NIK,Nama Lengkap,Unit Kerja,Divisi,Jabatan,Operator Driver,Masa Berlaku SIMPER',
|
||||
'1,1111,Ruadi Baru Terpulihkan,Pembangkit,Mekanik,Staff,TIDAK,',
|
||||
]);
|
||||
|
||||
$file = UploadedFile::fake()->createWithContent('import_with_trashed.csv', $csvContent);
|
||||
|
||||
$response = $this->actingAs($this->hseAdmin)
|
||||
->post(route('hse.employees.import'), [
|
||||
'file' => $file,
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
// Pastikan dipulihkan dan tidak terjadi SQL duplicate entry error
|
||||
$this->assertNotSoftDeleted('users', ['username' => '1111']);
|
||||
$this->assertNotSoftDeleted('employees', ['nik' => '1111']);
|
||||
|
||||
$user->refresh();
|
||||
$employee->refresh();
|
||||
|
||||
$this->assertEquals('Ruadi Baru Terpulihkan', $user->name);
|
||||
$this->assertEquals('Ruadi Baru Terpulihkan', $employee->name);
|
||||
$this->assertEquals('Pembangkit', $employee->unit_kerja);
|
||||
}
|
||||
|
||||
public function test_import_updates_only_division_without_overwriting_other_existing_fields(): void
|
||||
{
|
||||
$existing = Employee::create([
|
||||
'nik' => 'KMH-DIV-001',
|
||||
'name' => 'Budi Santoso',
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => '-',
|
||||
'position' => 'Supervisor Listrik',
|
||||
'is_operator' => true,
|
||||
'simper_expired_at' => '2027-01-01',
|
||||
]);
|
||||
|
||||
// Excel hanya mengisi NIK, Nama, dan Divisi (kolom lainnya kosong/None)
|
||||
$csvContent = implode("\n", [
|
||||
'No,NIK,Nama Lengkap,Unit Kerja,Divisi,Jabatan,Operator Driver,Masa Berlaku SIMPER',
|
||||
'1,KMH-DIV-001,Budi Santoso,,Electrical & Instrumentation,,,',
|
||||
]);
|
||||
|
||||
$file = UploadedFile::fake()->createWithContent('update_division_only.csv', $csvContent);
|
||||
|
||||
$response = $this->actingAs($this->hseAdmin)
|
||||
->post(route('hse.employees.import'), [
|
||||
'file' => $file,
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
$existing->refresh();
|
||||
|
||||
// Divisi terupdate
|
||||
$this->assertEquals('Electrical & Instrumentation', $existing->division);
|
||||
|
||||
// Data lain yang tidak diisi di Excel tetap dipertahankan utuh
|
||||
$this->assertEquals('Pembangkit', $existing->unit_kerja);
|
||||
$this->assertEquals('Supervisor Listrik', $existing->position);
|
||||
$this->assertTrue((bool)$existing->is_operator);
|
||||
$this->assertEquals('2027-01-01 00:00:00', $existing->simper_expired_at);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,4 +425,131 @@ class HseSimperTypeTest extends TestCase
|
||||
$this->assertSoftDeleted('simper_types', ['id' => $simperType->id]);
|
||||
$this->assertSoftDeleted('employee_simpers', ['id' => $empSimper->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER tanpa memasukkan tanggal masa berlaku ditolak dengan pesan error.
|
||||
*/
|
||||
public function test_checking_simper_without_expiry_date_fails_validation(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-TEST',
|
||||
'name' => 'SIMPER Dump Truck',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-01',
|
||||
'name' => 'Operator Test',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => '',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('error');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER dengan tanggal masa berlaku di masa lampau ditolak.
|
||||
*/
|
||||
public function test_checking_simper_with_past_expiry_date_fails_validation(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-PAST',
|
||||
'name' => 'SIMPER Dump Truck',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-02',
|
||||
'name' => 'Operator Test Past',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => Carbon::yesterday()->toDateString(),
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('error');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencentang SIMPER dengan tanggal masa depan berhasil disimpan.
|
||||
*/
|
||||
public function test_checking_simper_with_future_expiry_date_succeeds(): void
|
||||
{
|
||||
$type = SimperType::create([
|
||||
'code' => 'SIMPER-DT-OK',
|
||||
'name' => 'SIMPER Dump Truck OK',
|
||||
'category_scope' => 'all',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$employee = Employee::create([
|
||||
'nik' => 'EMP-EXP-VALIDATE-03',
|
||||
'name' => 'Operator Test Future',
|
||||
'is_operator' => true,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
]);
|
||||
|
||||
$futureDate = Carbon::now()->addMonths(6)->toDateString();
|
||||
|
||||
$response = $this->actingAs($this->adminHse)
|
||||
->post(route('hse.employees.update', $employee->id), [
|
||||
'nik' => $employee->nik,
|
||||
'name' => $employee->name,
|
||||
'is_operator' => 1,
|
||||
'unit_kerja' => 'Pembangkit',
|
||||
'division' => 'Operasi',
|
||||
'position' => 'Operator',
|
||||
'simper_assignments' => [
|
||||
$type->id => [
|
||||
'enabled' => 1,
|
||||
'expired_at' => $futureDate,
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$response->assertSessionHas('success');
|
||||
$this->assertDatabaseHas('employee_simpers', [
|
||||
'employee_id' => $employee->id,
|
||||
'simper_type_id' => $type->id,
|
||||
'expired_at' => $futureDate . ' 00:00:00',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,6 +334,8 @@ class P2hInspectionTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Manitou MT-X 733',
|
||||
'unit_category' => 'Telehandler',
|
||||
'unit_type' => 'Telehandler',
|
||||
'operational_group' => 'HEAVY',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 0,
|
||||
]);
|
||||
|
||||
@@ -184,4 +184,31 @@ class QmaHeavyEquipmentThreeLevelNavigationTest extends TestCase
|
||||
$response->assertSee('EX-01');
|
||||
$response->assertSee('Power House');
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin QMA dapat mengedit data unit alat berat termasuk divisi penanggung jawab tanpa mereset atau menambah unit baru.
|
||||
*/
|
||||
public function test_qma_admin_can_update_unit_support_division_and_details(): void
|
||||
{
|
||||
$unit = Vehicle::where('code', 'DT-01')->firstOrFail();
|
||||
|
||||
$response = $this->actingAs($this->qmaAdmin)->post("/qma/vehicles/{$unit->id}", [
|
||||
'code' => 'DT-01',
|
||||
'category' => 'unit_support',
|
||||
'operational_group' => 'HAULING',
|
||||
'unit_type' => 'DUMP TRUCK',
|
||||
'division' => 'Civil & Dam Construction',
|
||||
'status' => 'Operation',
|
||||
'location' => 'Main Dam',
|
||||
'site_status' => 'inside_site',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasNoErrors();
|
||||
$response->assertRedirect();
|
||||
|
||||
$unit->refresh();
|
||||
$this->assertEquals('Civil & Dam Construction', $unit->division);
|
||||
$this->assertEquals('HAULING', $unit->operational_group);
|
||||
$this->assertEquals('DUMP TRUCK', $unit->unit_type);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,6 +155,7 @@ class QmaModuleTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Caterpillar D6R',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'unit_type' => 'Track-type Tractor',
|
||||
'brand' => 'Caterpillar',
|
||||
'model_number' => 'D6R XL',
|
||||
@@ -174,6 +175,7 @@ class QmaModuleTest extends TestCase
|
||||
'code' => 'DZ01',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'silo_document' => 'SILO-2026/01',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -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', [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\SecurityGuard;
|
||||
use App\Models\User;
|
||||
@@ -175,4 +176,98 @@ class SecurityGuardFilterTest extends TestCase
|
||||
$this->assertSoftDeleted('users', ['id' => $userId]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Memastikan petugas Satpam yang dinonaktifkan tidak dapat login dan ditolak middleware.
|
||||
*/
|
||||
public function test_deactivated_guard_cannot_login_and_blocked_by_middleware(): void
|
||||
{
|
||||
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-001')->first();
|
||||
$this->assertNotNull($guard);
|
||||
$user = $guard->user;
|
||||
$this->assertNotNull($user);
|
||||
|
||||
// 1. Nonaktifkan petugas satpam
|
||||
$guard->update(['is_active' => false]);
|
||||
|
||||
// Coba login -> Harus ditolak
|
||||
$loginResponse = $this->post(route('login'), [
|
||||
'username' => $user->username,
|
||||
'password' => 'password',
|
||||
]);
|
||||
$loginResponse->assertSessionHasErrors('username');
|
||||
$this->assertGuest();
|
||||
|
||||
// 2. Jika dalam sesi aktif tapi di-nonaktifkan -> Middleware tolak dengan 403
|
||||
$middlewareResponse = $this->actingAs($user)->get(route('pg.dashboard'));
|
||||
$middlewareResponse->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_admin_pg_can_edit_guard_badge_id_and_syncs_with_user_and_employee(): void
|
||||
{
|
||||
$guard = SecurityGuard::with('user')->where('badge_id', 'SEC-002')->first();
|
||||
$this->assertNotNull($guard);
|
||||
$this->assertNotNull($guard->user);
|
||||
|
||||
// Pastikan ada Employee dengan NIK lama
|
||||
$emp = Employee::firstOrCreate(
|
||||
['nik' => 'SEC-002'],
|
||||
[
|
||||
'user_id' => $guard->user_id,
|
||||
'name' => $guard->name,
|
||||
'employee_type' => 'Karyawan',
|
||||
'unit_kerja' => 'Private Guard',
|
||||
'division' => 'Private Guard',
|
||||
'position' => 'Anggota',
|
||||
]
|
||||
);
|
||||
|
||||
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
|
||||
'badge_id' => 'SEC-002-EDIT',
|
||||
'name' => 'Budi Santoso Diperbarui',
|
||||
'team' => 3,
|
||||
'password' => 'newpassword123',
|
||||
]);
|
||||
|
||||
$response->assertRedirect();
|
||||
$response->assertSessionHasNoErrors();
|
||||
|
||||
// Verifikasi SecurityGuard
|
||||
$guard->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $guard->badge_id);
|
||||
$this->assertEquals('Budi Santoso Diperbarui', $guard->name);
|
||||
$this->assertEquals(3, $guard->team);
|
||||
|
||||
// Verifikasi User login
|
||||
$guard->user->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $guard->user->username);
|
||||
$this->assertEquals('[email protected]', $guard->user->email);
|
||||
|
||||
// Verifikasi Employee NIK
|
||||
$emp->refresh();
|
||||
$this->assertEquals('SEC-002-EDIT', $emp->nik);
|
||||
$this->assertEquals('Budi Santoso Diperbarui', $emp->name);
|
||||
|
||||
// Verifikasi login dengan ID baru dan password baru
|
||||
$this->post('/logout');
|
||||
$loginResponse = $this->post('/login', [
|
||||
'username' => 'SEC-002-EDIT',
|
||||
'password' => 'newpassword123',
|
||||
]);
|
||||
$loginResponse->assertRedirect();
|
||||
$this->assertAuthenticatedAs($guard->user);
|
||||
}
|
||||
|
||||
public function test_editing_guard_with_duplicate_badge_id_is_rejected(): void
|
||||
{
|
||||
$guard = SecurityGuard::where('badge_id', 'SEC-002')->first();
|
||||
|
||||
$response = $this->actingAs($this->adminPg)->post(route('pg.guards.update', $guard->id), [
|
||||
'badge_id' => 'SEC-001', // sudah dipakai oleh guard 1
|
||||
'name' => 'Budi Duplicate',
|
||||
'team' => 2,
|
||||
]);
|
||||
|
||||
$response->assertSessionHasErrors('badge_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ class UnitSupportBusinessProcessTest extends TestCase
|
||||
->get(route('qma.vehicles.support'));
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertSee('TEST-CAT');
|
||||
$response->assertSee('Tambah Kategori Heavy Equipment');
|
||||
$response->assertSee('Tambah Unit');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class UserSoftDeleteAndProtectionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed();
|
||||
}
|
||||
|
||||
public function test_deleting_user_with_operational_history_soft_deletes_cleanly_without_500(): void
|
||||
{
|
||||
$superAdmin = User::where('username', 'superadmin')->first();
|
||||
|
||||
// Buat user & employee sukon/karyawan
|
||||
$user = User::factory()->create([
|
||||
'name' => 'Supri Driver',
|
||||
'username' => '123456',
|
||||
'email' => '[email protected]',
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$user->assignRole('employee');
|
||||
|
||||
$employee = Employee::create([
|
||||
'user_id' => $user->id,
|
||||
'nik' => '123456',
|
||||
'name' => 'Supri Driver',
|
||||
'employee_type' => 'Sukon',
|
||||
'division' => 'subkon',
|
||||
'position' => 'Driver',
|
||||
'is_operator' => true,
|
||||
]);
|
||||
|
||||
$gate = Gate::first() ?: Gate::create(['name' => 'Gate Utama', 'code' => 'GU-01']);
|
||||
$vehicle = Vehicle::first() ?: Vehicle::factory()->create();
|
||||
|
||||
// Buat aktivitas riwayat operasional kendaraan
|
||||
$activity = VehicleActivity::create([
|
||||
'transaction_no' => 'TRX-SUPRI-001',
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $employee->id,
|
||||
'gate_id' => $gate->id,
|
||||
'direction' => 'out',
|
||||
'previous_km' => 1000,
|
||||
'current_km' => 1050,
|
||||
'distance' => 50,
|
||||
'purpose' => 'Pengiriman Material',
|
||||
'recorded_at' => now(),
|
||||
'status' => 'approved',
|
||||
]);
|
||||
|
||||
// Super Admin menghapus akun user Supri dari menu Kelola Pengguna
|
||||
$response = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.users.destroy', $user->id));
|
||||
|
||||
// Harus berhasil redirect tanpa error 500
|
||||
$response->assertStatus(302);
|
||||
$response->assertRedirect(route('admin.users.index'));
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
// Pastikan User & Employee berstatus Soft Deleted (ada di tong sampah)
|
||||
$this->assertSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertSoftDeleted('employees', ['id' => $employee->id]);
|
||||
|
||||
// Pastikan riwayat aktivitas operasional tetap UTUH dan tidak hilang
|
||||
$this->assertDatabaseHas('vehicle_activities', [
|
||||
'id' => $activity->id,
|
||||
'driver_id' => $employee->id,
|
||||
]);
|
||||
|
||||
// Coba lakukan Hapus Permanen dari Tong Sampah -> Harus ditolak karena integritas audit
|
||||
$forceResponse = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.trash.force_delete', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$forceResponse->assertStatus(302);
|
||||
$forceResponse->assertSessionHas('error');
|
||||
|
||||
// User tetap ada di basis data (tidak terhapus permanen)
|
||||
$this->assertDatabaseHas('users', ['id' => $user->id]);
|
||||
|
||||
// Pulihkan akun dari Tong Sampah -> User & Employee harus aktif kembali beserta perannya
|
||||
$restoreResponse = $this->actingAs($superAdmin)
|
||||
->post(route('admin.trash.restore', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$restoreResponse->assertStatus(302);
|
||||
$restoreResponse->assertSessionHas('success');
|
||||
|
||||
$this->assertNotSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertNotSoftDeleted('employees', ['id' => $employee->id]);
|
||||
$this->assertTrue($user->fresh()->hasRole('employee'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user