feat: setup Docker production stack, Vite asset compilation, and resolve audit findings (P1/P2)
This commit is contained in:
@@ -72,11 +72,13 @@ class LoginController extends Controller
|
||||
private function redirectBasedOnRole($user): RedirectResponse
|
||||
{
|
||||
return match ($user->role) {
|
||||
'super_admin', 'superadmin', 'admin' => redirect()->route('superadmin.dashboard'),
|
||||
'hse_admin' => redirect()->route('hse.dashboard'),
|
||||
'qma_admin' => redirect()->route('qma.dashboard'),
|
||||
'pg_admin' => redirect()->route('pg.dashboard'),
|
||||
'gate_officer' => redirect()->route('pg.gate.inspection'),
|
||||
default => redirect()->route('qma.dashboard'),
|
||||
'employee' => redirect()->route('employee.dashboard'),
|
||||
default => redirect()->route('superadmin.dashboard'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Employee;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Vehicle;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan halaman dashboard utama karyawan / operator.
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
$employee = auth()->user()->employee;
|
||||
$totalSupport = Vehicle::unitSupports()->count();
|
||||
$totalLv = Vehicle::lightVehicles()->count();
|
||||
|
||||
return view('employee.dashboard', compact('employee', 'totalSupport', 'totalLv'));
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,10 @@ namespace App\Http\Controllers\Hse;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Employee;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmployeeController extends Controller
|
||||
@@ -36,9 +38,9 @@ class EmployeeController extends Controller
|
||||
$simperLogs = Employee::where('is_operator', true)
|
||||
->orderByRaw("CASE
|
||||
WHEN simper_expired_at IS NULL THEN 1
|
||||
WHEN simper_expired_at < '{$today}' THEN 0
|
||||
WHEN simper_expired_at < ? THEN 0
|
||||
ELSE 2
|
||||
END ASC, simper_expired_at ASC")
|
||||
END ASC, simper_expired_at ASC", [$today])
|
||||
->take(5)
|
||||
->get();
|
||||
|
||||
@@ -112,80 +114,38 @@ class EmployeeController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
$employees = $query->orderBy('name')->get();
|
||||
$employees = $query->orderBy('name')->paginate(20)->withQueryString();
|
||||
|
||||
return view('hse.employees_index', compact('employees'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan data karyawan baru beserta izin SIMPER (Form modal gambar 3).
|
||||
* Pendaftaran master karyawan baru dialihkan ke Super Admin.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'nik' => ['required', 'string', 'max:50', 'unique:employees,nik'],
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'unit_kerja' => ['required', 'string'],
|
||||
'division' => ['required', 'string'],
|
||||
'position' => ['required', 'string'],
|
||||
'is_operator' => ['required', 'in:1,0'],
|
||||
'simper_expired_at' => ['nullable', 'date'],
|
||||
], [
|
||||
'nik.required' => 'NIK wajib diisi.',
|
||||
'nik.unique' => 'NIK sudah terdaftar dalam sistem.',
|
||||
'name.required' => 'Nama karyawan wajib diisi.',
|
||||
'unit_kerja.required' => 'Unit kerja wajib dipilih.',
|
||||
'division.required' => 'Divisi wajib dipilih.',
|
||||
'position.required' => 'Posisi / Jabatan wajib diisi.',
|
||||
'is_operator.required' => 'Pilih apakah karyawan berstatus Operator / Driver.',
|
||||
]);
|
||||
|
||||
$isOperator = (bool) $validated['is_operator'];
|
||||
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null;
|
||||
|
||||
Employee::create([
|
||||
'nik' => $validated['nik'],
|
||||
'name' => $validated['name'],
|
||||
'unit_kerja' => $validated['unit_kerja'],
|
||||
'division' => $validated['division'],
|
||||
'position' => $validated['position'],
|
||||
'is_operator' => $isOperator,
|
||||
'simper_expired_at' => $simperExpiredAt,
|
||||
]);
|
||||
|
||||
return back()->with('success', "Data karyawan {$validated['name']} berhasil ditambahkan.");
|
||||
return back()->with('error', 'Pendaftaran master data karyawan baru hanya dapat dilakukan oleh Super Admin melalui menu Manajemen Akun.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Perpanjang atau perbarui data karyawan & SIMPER.
|
||||
* Perpanjang atau perbarui status driver & masa berlaku SIMPER karyawan.
|
||||
* Master data profil karyawan dikelola terpusat oleh Super Admin.
|
||||
*/
|
||||
public function update(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$employee = Employee::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'nik' => ['sometimes', 'required', 'string', 'max:50', 'unique:employees,nik,' . $employee->id],
|
||||
'name' => ['sometimes', 'required', 'string', 'max:100'],
|
||||
'unit_kerja' => ['sometimes', 'required', 'string'],
|
||||
'division' => ['sometimes', 'required', 'string'],
|
||||
'position' => ['sometimes', 'required', 'string'],
|
||||
'is_operator' => ['required', 'in:1,0'],
|
||||
'simper_expired_at' => ['nullable', 'date'],
|
||||
], [
|
||||
'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.',
|
||||
'name.required' => 'Nama lengkap wajib diisi.',
|
||||
'is_operator.required' => 'Status driver wajib dipilih.',
|
||||
]);
|
||||
|
||||
$isOperator = (bool) $validated['is_operator'];
|
||||
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? $employee->simper_expired_at) : null;
|
||||
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? null) : null;
|
||||
|
||||
$employee->update([
|
||||
'nik' => $validated['nik'] ?? $employee->nik,
|
||||
'name' => $validated['name'] ?? $employee->name,
|
||||
'unit_kerja' => $validated['unit_kerja'] ?? $employee->unit_kerja,
|
||||
'division' => $validated['division'] ?? $employee->division,
|
||||
'position' => $validated['position'] ?? $employee->position,
|
||||
'is_operator' => $isOperator,
|
||||
'simper_expired_at' => $simperExpiredAt,
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\P2h;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Employee;
|
||||
use App\Models\P2hRecord;
|
||||
use App\Models\P2hRecordItem;
|
||||
use App\Models\P2hTemplate;
|
||||
use App\Models\Vehicle;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class P2hFormController extends Controller
|
||||
{
|
||||
/**
|
||||
* Halaman katalog/pemilihan unit support untuk pengisian P2H.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = Vehicle::unitSupports()->where(function ($q) {
|
||||
$q->whereNotNull('parent_id')
|
||||
->orWhere(function ($sub) {
|
||||
$sub->whereNull('parent_id')->whereDoesntHave('units');
|
||||
});
|
||||
});
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = trim($request->input('search'));
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('code', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%")
|
||||
->orWhere('unit_category', 'like', "%{$search}%")
|
||||
->orWhere('location', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
if ($request->filled('unit_category')) {
|
||||
$query->where('unit_category', $request->input('unit_category'));
|
||||
}
|
||||
|
||||
$vehicles = $query->with('p2hTemplate')->orderBy('code')->paginate(32)->withQueryString();
|
||||
$categories = P2hTemplate::orderBy('name')->pluck('name');
|
||||
|
||||
$user = Auth::user();
|
||||
$employee = $user ? $user->employee : null;
|
||||
|
||||
return view('p2h.index', compact('vehicles', 'categories', 'employee'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan formulir pengisian P2H untuk unit support tertentu.
|
||||
*/
|
||||
public function show(Request $request, string $code): View|RedirectResponse
|
||||
{
|
||||
$vehicle = Vehicle::where('code', $code)
|
||||
->where('category', 'unit_support')
|
||||
->firstOrFail();
|
||||
|
||||
$user = Auth::user();
|
||||
$employee = $user->employee;
|
||||
|
||||
// Validasi identitas operator di sistem HSE
|
||||
$simperError = null;
|
||||
if ($user->isQmaAdmin() || $user->isSuperAdmin()) {
|
||||
$simperError = "Anda saat ini login sebagai Admin QMA. Formulir P2H lapangan dikhususkan untuk diisi langsung oleh Operator pemegang lisensi SIMPER aktif saat pra-operasi unit. Sebagai Admin QMA, wewenang Anda adalah memeriksa, memverifikasi, dan menyetujui checksheet yang telah disubmit operator melalui Menu QMA.";
|
||||
} elseif (!$employee) {
|
||||
$simperError = "Akun login Anda ({$user->name}) belum ditautkan dengan data Karyawan di database HSE. Silakan hubungi Divisi HSE.";
|
||||
} elseif (!$employee->is_operator) {
|
||||
$simperError = "Karyawan atas nama {$employee->name} (NIK: {$employee->nik} - {$employee->division}) terdaftar sebagai BUKAN OPERATOR/DRIVER dan tidak memiliki izin mengoperasikan alat berat. Silakan hubungi Divisi HSE.";
|
||||
} elseif (!$employee->hasValidSimper()) {
|
||||
$expDate = $employee->simper_expired_at ? $employee->simper_expired_at->format('d/m/Y') : 'Belum Terdaftar';
|
||||
$simperError = "SIMPER atas nama {$employee->name} (NIK: {$employee->nik}) telah KEDALUWARSA pada {$expDate}. Anda tidak diizinkan mengoperasikan alat berat. Silakan hubungi Divisi HSE.";
|
||||
}
|
||||
|
||||
// Tentukan template P2H yang digunakan
|
||||
$template = $vehicle->p2hTemplate;
|
||||
if (!$template && $vehicle->unit_category) {
|
||||
$template = P2hTemplate::where('name', 'like', "%{$vehicle->unit_category}%")
|
||||
->orWhere('code', 'like', "%{$vehicle->unit_category}%")
|
||||
->first();
|
||||
}
|
||||
|
||||
if (!$template) {
|
||||
// Ambil template default pertama jika belum terpetakan spesifik
|
||||
$template = P2hTemplate::first();
|
||||
}
|
||||
|
||||
$items = $template ? $template->items : collect();
|
||||
$groupedItems = [];
|
||||
foreach ($items as $item) {
|
||||
$groupedItems[$item->section][] = $item;
|
||||
}
|
||||
|
||||
return view('p2h.form', compact(
|
||||
'vehicle',
|
||||
'employee',
|
||||
'simperError',
|
||||
'template',
|
||||
'groupedItems'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan hasil pengisian formulir P2H ke database.
|
||||
*/
|
||||
public function store(Request $request, string $code): RedirectResponse
|
||||
{
|
||||
$vehicle = Vehicle::where('code', $code)
|
||||
->where('category', 'unit_support')
|
||||
->firstOrFail();
|
||||
|
||||
$user = Auth::user();
|
||||
$employee = $user->employee;
|
||||
|
||||
if ($user->isQmaAdmin() || $user->isSuperAdmin()) {
|
||||
return back()->with('error', 'Admin QMA tidak memiliki wewenang untuk mengisi formulir P2H operator. Formulir wajib diisi langsung oleh Operator alat berlisensi SIMPER aktif.');
|
||||
}
|
||||
|
||||
if (!$employee || !$employee->is_operator || !$employee->hasValidSimper()) {
|
||||
return back()->with('error', 'Validasi SIMPER gagal. Anda tidak memiliki wewenang untuk menyimpan P2H.');
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'template_id' => ['required', 'exists:p2h_templates,id'],
|
||||
'shift' => ['nullable', 'string'],
|
||||
'start_hm' => ['required', 'numeric', 'min:0'],
|
||||
'general_notes' => ['nullable', 'string', 'max:2000'],
|
||||
'items' => ['required', 'array'],
|
||||
'items.*.condition' => ['nullable', 'string', 'in:baik,rusak'],
|
||||
'items.*.answer' => ['nullable', 'string'],
|
||||
'items.*.notes' => ['nullable', 'string', 'max:500'],
|
||||
], [
|
||||
'start_hm.required' => 'Nilai Hour Meter (HM) wajib diisi.',
|
||||
'start_hm.numeric' => 'Nilai Hour Meter (HM) harus berupa angka valid.',
|
||||
'items.required' => 'Daftar butir pemeriksaan P2H tidak boleh kosong.',
|
||||
]);
|
||||
|
||||
$template = P2hTemplate::with('items')->findOrFail($validated['template_id']);
|
||||
$submittedItems = $validated['items'];
|
||||
|
||||
$trxNo = 'P2H-' . Carbon::now()->format('Ymd') . '-' . strtoupper(Str::random(5));
|
||||
$now = Carbon::now();
|
||||
|
||||
DB::transaction(function () use ($trxNo, $vehicle, $employee, $template, $validated, $submittedItems, $now) {
|
||||
$defectCount = 0;
|
||||
$itemsToInsert = [];
|
||||
|
||||
foreach ($template->items as $tItem) {
|
||||
$itemId = $tItem->id;
|
||||
$userAns = $submittedItems[$itemId] ?? null;
|
||||
|
||||
$condition = null;
|
||||
$answerVal = null;
|
||||
$notes = null;
|
||||
|
||||
if (in_array($tItem->question_type, ['choice', 'condition', 'Multiple choice: only one answer', 'Matrix'])) {
|
||||
// Pilihan Baik atau Rusak (default 'baik' jika belum terisi)
|
||||
$condition = isset($userAns['condition']) && $userAns['condition'] === 'rusak' ? 'rusak' : 'baik';
|
||||
if ($condition === 'rusak') {
|
||||
$defectCount++;
|
||||
}
|
||||
} elseif (in_array($tItem->question_type, ['number', 'Numerical Value'])) {
|
||||
$answerVal = $userAns['answer'] ?? $validated['start_hm'];
|
||||
} elseif (in_array($tItem->question_type, ['datetime', 'Datetime'])) {
|
||||
$answerVal = $userAns['answer'] ?? $now->format('Y-m-d H:i');
|
||||
} elseif (in_array($tItem->question_type, ['date', 'Date'])) {
|
||||
$answerVal = $userAns['answer'] ?? $now->format('Y-m-d');
|
||||
} else {
|
||||
$answerVal = $userAns['answer'] ?? null;
|
||||
}
|
||||
|
||||
if (!empty($userAns['notes'])) {
|
||||
$notes = trim($userAns['notes']);
|
||||
}
|
||||
|
||||
$itemsToInsert[] = [
|
||||
'template_item_id' => $tItem->id,
|
||||
'section' => $tItem->section,
|
||||
'title' => $tItem->title,
|
||||
'question_type' => $tItem->question_type,
|
||||
'condition_status' => $condition,
|
||||
'answer_value' => $answerVal,
|
||||
'notes' => $notes,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
$summaryCondition = ($defectCount > 0) ? 'has_defect' : 'good';
|
||||
|
||||
$record = P2hRecord::create([
|
||||
'transaction_no' => $trxNo,
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'employee_id' => $employee->id,
|
||||
'template_id' => $template->id,
|
||||
'shift' => !empty($validated['shift']) ? $validated['shift'] : 'Shift 1 (Siang)',
|
||||
'start_hm' => $validated['start_hm'],
|
||||
'start_time' => $now,
|
||||
'summary_condition' => $summaryCondition,
|
||||
'defect_count' => $defectCount,
|
||||
'general_notes' => $validated['general_notes'] ?? null,
|
||||
'validation_status' => 'pending', // Menunggu approval Admin QMA
|
||||
'inspected_at' => $now,
|
||||
]);
|
||||
|
||||
foreach ($itemsToInsert as $ins) {
|
||||
$ins['p2h_record_id'] = $record->id;
|
||||
P2hRecordItem::create($ins);
|
||||
}
|
||||
|
||||
// Perbarui HM unit di master data kendaraan jika lebih besar
|
||||
if ((float)$validated['start_hm'] > (float)$vehicle->current_km) {
|
||||
$vehicle->update(['current_km' => $validated['start_hm']]);
|
||||
}
|
||||
|
||||
// Jika ada kerusakan kritis, tandai status kendaraan
|
||||
if ($defectCount > 0 && $vehicle->status === 'Operation') {
|
||||
$vehicle->update(['status' => 'Breakdown']);
|
||||
}
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('p2h.form', ['code' => $code])
|
||||
->with('success', "Inspeksi P2H unit [{$vehicle->code}] berhasil dikirim dengan Nomor Transaksi {$trxNo}. Laporan saat ini berstatus 'Menunggu Approval' dari Admin QMA.");
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,8 @@ class SecurityGuardController extends Controller
|
||||
|
||||
$guards = $query->orderBy('team')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
->paginate(20)
|
||||
->withQueryString();
|
||||
|
||||
$gates = Gate::where('is_active', true)->orderBy('name')->get();
|
||||
|
||||
|
||||
@@ -19,6 +19,33 @@ use Illuminate\View\View;
|
||||
class VehicleActivityFormController extends Controller
|
||||
{
|
||||
|
||||
/**
|
||||
* Tampilkan katalog / daftar kendaraan ringan (LV) untuk keperluan mobilisasi karyawan.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = Vehicle::lightVehicles();
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = trim($request->input('search'));
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('code', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%")
|
||||
->orWhere('license_plate', 'like', "%{$search}%")
|
||||
->orWhere('ownership', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$vehicles = $query->orderBy('code')->paginate(24)->withQueryString();
|
||||
|
||||
$employee = null;
|
||||
if (auth()->check()) {
|
||||
$employee = auth()->user()->employee;
|
||||
}
|
||||
|
||||
return view('mobilisasi.index', compact('vehicles', 'employee'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form pencatatan aktivitas kendaraan saat scan QR code.
|
||||
*/
|
||||
@@ -71,6 +98,20 @@ class VehicleActivityFormController extends Controller
|
||||
} else {
|
||||
$verifiedDriver = $emp;
|
||||
}
|
||||
} elseif (auth()->check() && auth()->user()->isEmployee()) {
|
||||
$emp = auth()->user()->employee;
|
||||
if ($emp) {
|
||||
if (!$emp->is_operator) {
|
||||
$nikErrorTitle = 'Bukan Driver Terdaftar';
|
||||
$nikError = "Karyawan atas nama {$emp->name} (NIK: {$emp->nik} - {$emp->division}) terdaftar sebagai BUKAN DRIVER dan tidak memiliki izin mengemudi (SIMPER). Anda tidak diizinkan mengoperasikan kendaraan unit. Silakan hubungi Divisi HSE.";
|
||||
} elseif (!$emp->hasValidSimper()) {
|
||||
$nikErrorTitle = 'Peringatan: SIMPER Kedaluwarsa';
|
||||
$nikError = "SIMPER atas nama {$emp->name} (NIK: {$emp->nik} - {$emp->division}) telah KEDALUWARSA. Anda tidak diizinkan mengoperasikan kendaraan. Silakan hubungi Divisi HSE untuk perpanjangan masa berlaku SIMPER.";
|
||||
} else {
|
||||
$verifiedDriver = $emp;
|
||||
$inputNik = $emp->nik;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return view('public.vehicle_activity_form', compact(
|
||||
|
||||
@@ -108,13 +108,23 @@ class ActivityLogController extends Controller
|
||||
});
|
||||
}
|
||||
|
||||
$totalActivities = (clone $query)->count();
|
||||
$totalDistance = (clone $query)->sum('distance');
|
||||
$inCount = (clone $query)->where('direction', 'in')->count();
|
||||
$outCount = (clone $query)->where('direction', 'out')->count();
|
||||
$approvedCount = (clone $query)->where('validation_status', 'approved')->count();
|
||||
$pendingCount = (clone $query)->where('validation_status', 'pending')->count();
|
||||
$rejectedCount = (clone $query)->where('validation_status', 'rejected')->count();
|
||||
$stats = (clone $query)->selectRaw("
|
||||
COUNT(*) as total_activities,
|
||||
COALESCE(SUM(distance), 0) as total_distance,
|
||||
COUNT(CASE WHEN direction = 'in' THEN 1 END) as in_count,
|
||||
COUNT(CASE WHEN direction = 'out' THEN 1 END) as out_count,
|
||||
COUNT(CASE WHEN validation_status = 'approved' THEN 1 END) as approved_count,
|
||||
COUNT(CASE WHEN validation_status = 'pending' THEN 1 END) as pending_count,
|
||||
COUNT(CASE WHEN validation_status = 'rejected' THEN 1 END) as rejected_count
|
||||
")->first();
|
||||
|
||||
$totalActivities = (int) ($stats->total_activities ?? 0);
|
||||
$totalDistance = (float) ($stats->total_distance ?? 0);
|
||||
$inCount = (int) ($stats->in_count ?? 0);
|
||||
$outCount = (int) ($stats->out_count ?? 0);
|
||||
$approvedCount = (int) ($stats->approved_count ?? 0);
|
||||
$pendingCount = (int) ($stats->pending_count ?? 0);
|
||||
$rejectedCount = (int) ($stats->rejected_count ?? 0);
|
||||
|
||||
// Rekapitulasi per Kendaraan
|
||||
$vehicleSummaries = (clone $query)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Qma;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\P2hRecord;
|
||||
use App\Models\Vehicle;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class P2hInspectionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan riwayat dan log pemeriksaan P2H Unit Support untuk Admin QMA.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = P2hRecord::with(['vehicle', 'employee', 'template', 'validator']);
|
||||
|
||||
// Filter Status Approval
|
||||
if ($request->filled('validation_status')) {
|
||||
$query->where('validation_status', $request->input('validation_status'));
|
||||
}
|
||||
|
||||
// Filter Status Kelayakan (Kondisi)
|
||||
if ($request->filled('summary_condition')) {
|
||||
$query->where('summary_condition', $request->input('summary_condition'));
|
||||
}
|
||||
|
||||
// Filter Tanggal
|
||||
if ($request->filled('date')) {
|
||||
$query->whereDate('inspected_at', $request->input('date'));
|
||||
}
|
||||
|
||||
// Filter Pencarian Keyword (Nomor Transaksi, Kode Unit, Nama Operator, NIK)
|
||||
if ($request->filled('search')) {
|
||||
$search = trim($request->input('search'));
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('transaction_no', 'like', "%{$search}%")
|
||||
->orWhereHas('vehicle', fn($v) => $v->where('code', 'like', "%{$search}%")->orWhere('brand_type', 'like', "%{$search}%"))
|
||||
->orWhereHas('employee', fn($e) => $e->where('name', 'like', "%{$search}%")->orWhere('nik', 'like', "%{$search}%"));
|
||||
});
|
||||
}
|
||||
|
||||
$records = $query->orderByDesc('inspected_at')->paginate(15)->withQueryString();
|
||||
|
||||
// Statistik Ringkasan P2H
|
||||
$totalP2h = P2hRecord::count();
|
||||
$totalPending = P2hRecord::where('validation_status', 'pending')->count();
|
||||
$totalApproved = P2hRecord::where('validation_status', 'approved')->count();
|
||||
$totalRejected = P2hRecord::where('validation_status', 'rejected')->count();
|
||||
$totalDefects = P2hRecord::where('summary_condition', 'has_defect')->count();
|
||||
|
||||
return view('qma.p2h_index', compact(
|
||||
'records',
|
||||
'totalP2h',
|
||||
'totalPending',
|
||||
'totalApproved',
|
||||
'totalRejected',
|
||||
'totalDefects'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan Summary Pemeriksaan P2H Unit Support (Analitik, Rekapitulasi Alat Berat & Status).
|
||||
*/
|
||||
public function summary(Request $request): View
|
||||
{
|
||||
$today = Carbon::today()->toDateString();
|
||||
$startDate = $request->input('start_date', Carbon::now()->startOfMonth()->toDateString());
|
||||
$endDate = $request->input('end_date', $today);
|
||||
$vehicleId = $request->input('vehicle_id');
|
||||
$validationStatus = $request->input('validation_status');
|
||||
$shift = $request->input('shift');
|
||||
$search = trim($request->input('search', ''));
|
||||
|
||||
$query = P2hRecord::with(['vehicle', 'employee', 'template']);
|
||||
|
||||
if ($startDate && $endDate) {
|
||||
$start = Carbon::parse($startDate)->startOfDay();
|
||||
$end = Carbon::parse($endDate)->endOfDay();
|
||||
$query->whereBetween('inspected_at', [$start, $end]);
|
||||
} elseif ($startDate) {
|
||||
$query->where('inspected_at', '>=', Carbon::parse($startDate)->startOfDay());
|
||||
} elseif ($endDate) {
|
||||
$query->where('inspected_at', '<=', Carbon::parse($endDate)->endOfDay());
|
||||
}
|
||||
|
||||
if ($request->filled('vehicle_id')) {
|
||||
$query->where('vehicle_id', $vehicleId);
|
||||
}
|
||||
|
||||
if ($request->filled('validation_status')) {
|
||||
$query->where('validation_status', $validationStatus);
|
||||
}
|
||||
|
||||
if ($request->filled('shift')) {
|
||||
$query->where('shift', $shift);
|
||||
}
|
||||
|
||||
if ($search !== '') {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('transaction_no', 'like', "%{$search}%")
|
||||
->orWhereHas('vehicle', fn($v) => $v->where('code', 'like', "%{$search}%")->orWhere('brand_type', 'like', "%{$search}%"))
|
||||
->orWhereHas('employee', fn($e) => $e->where('name', 'like', "%{$search}%")->orWhere('nik', 'like', "%{$search}%"));
|
||||
});
|
||||
}
|
||||
|
||||
$records = $query->orderByDesc('inspected_at')->get();
|
||||
|
||||
// 4 KPI Metrik Utama
|
||||
$totalInspections = $records->count();
|
||||
$totalApproved = $records->where('validation_status', 'approved')->count();
|
||||
$totalPending = $records->where('validation_status', 'pending')->count();
|
||||
$totalRejected = $records->where('validation_status', 'rejected')->count();
|
||||
$totalDefects = $records->where('summary_condition', 'has_defect')->count();
|
||||
$totalNormal = $records->where('summary_condition', 'good')->count();
|
||||
$totalHm = $records->sum('start_hm');
|
||||
|
||||
// Rekapitulasi per Unit Support
|
||||
$unitSummary = $records->groupBy('vehicle_id')->map(function ($group) {
|
||||
$vehicle = $group->first()->vehicle;
|
||||
return [
|
||||
'vehicle' => $vehicle,
|
||||
'total' => $group->count(),
|
||||
'approved' => $group->where('validation_status', 'approved')->count(),
|
||||
'pending' => $group->where('validation_status', 'pending')->count(),
|
||||
'rejected' => $group->where('validation_status', 'rejected')->count(),
|
||||
'has_defect' => $group->where('summary_condition', 'has_defect')->count(),
|
||||
'good' => $group->where('summary_condition', 'good')->count(),
|
||||
'latest_hm' => $group->max('start_hm'),
|
||||
'latest_inspection' => $group->max('inspected_at'),
|
||||
];
|
||||
})->sortByDesc('total');
|
||||
|
||||
// Daftar Unit Support untuk opsi filter
|
||||
$supportVehicles = Vehicle::where('category', 'unit_support')->orderBy('code')->get();
|
||||
|
||||
return view('qma.p2h_summary', compact(
|
||||
'records',
|
||||
'totalInspections',
|
||||
'totalApproved',
|
||||
'totalPending',
|
||||
'totalRejected',
|
||||
'totalDefects',
|
||||
'totalNormal',
|
||||
'totalHm',
|
||||
'unitSummary',
|
||||
'supportVehicles',
|
||||
'startDate',
|
||||
'endDate'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan detail lembar pemeriksaan P2H (seluruh section & butir jawaban).
|
||||
*/
|
||||
public function show(int $id): View
|
||||
{
|
||||
$record = P2hRecord::with(['vehicle', 'employee', 'template', 'validator', 'items'])->findOrFail($id);
|
||||
|
||||
$groupedItems = [];
|
||||
foreach ($record->items as $item) {
|
||||
$groupedItems[$item->section][] = $item;
|
||||
}
|
||||
|
||||
return view('qma.p2h_show', compact('record', 'groupedItems'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Approval / Persetujuan lembar P2H oleh Admin QMA.
|
||||
*/
|
||||
public function approve(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$record = P2hRecord::with('vehicle')->findOrFail($id);
|
||||
|
||||
$record->update([
|
||||
'validation_status' => 'approved',
|
||||
'validated_by' => Auth::id(),
|
||||
'validated_at' => Carbon::now(),
|
||||
'validation_notes' => $request->input('validation_notes', 'Pemeriksaan P2H disetujui oleh QMA.'),
|
||||
]);
|
||||
|
||||
// Jika unit dinyatakan aman dan sebelumnya breakdown karena review, status unit disetujui operasi
|
||||
if (!$record->hasDefects() && $record->vehicle->status === 'Breakdown') {
|
||||
$record->vehicle->update(['status' => 'Operation']);
|
||||
}
|
||||
|
||||
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} berhasil DISETUJUI.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Penolakan lembar P2H oleh Admin QMA (misal data tidak valid atau unit dilarang beroperasi).
|
||||
*/
|
||||
public function reject(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'validation_notes' => ['required', 'string', 'max:1000'],
|
||||
], [
|
||||
'validation_notes.required' => 'Alasan penolakan / instruksi perbaikan wajib diisi.',
|
||||
]);
|
||||
|
||||
$record = P2hRecord::with('vehicle')->findOrFail($id);
|
||||
|
||||
$record->update([
|
||||
'validation_status' => 'rejected',
|
||||
'validated_by' => Auth::id(),
|
||||
'validated_at' => Carbon::now(),
|
||||
'validation_notes' => $request->input('validation_notes'),
|
||||
]);
|
||||
|
||||
// Kunci status kendaraan ke Breakdown atau Standby jika P2H ditolak
|
||||
$record->vehicle->update(['status' => 'Breakdown']);
|
||||
|
||||
return back()->with('success', "Inspeksi P2H [{$record->transaction_no}] untuk unit {$record->vehicle->code} DITOLAK. Status unit diubah ke Breakdown.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Qma;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\P2hTemplate;
|
||||
use App\Models\P2hTemplateItem;
|
||||
use App\Models\Vehicle;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class P2hTemplateController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan daftar Master Template Checksheet P2H Unit Support sesuai kategori aset.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = P2hTemplate::withCount(['items', 'vehicles', 'records']);
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = trim($request->input('search'));
|
||||
$query->where('name', 'like', "%{$search}%")
|
||||
->orWhere('code', 'like', "%{$search}%");
|
||||
}
|
||||
|
||||
$templates = $query->orderBy('name')->get();
|
||||
|
||||
return view('qma.p2h_templates', compact('templates'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan detail butir pertanyaan dalam template tertentu.
|
||||
*/
|
||||
public function show(int $id): View
|
||||
{
|
||||
$template = P2hTemplate::findOrFail($id);
|
||||
|
||||
// Pastikan seluruh nomor urut pertanyaan berurutan otomatis tanpa celah (1, 2, 3... N)
|
||||
$this->resequenceTemplate($template);
|
||||
|
||||
$template->load(['items' => fn($q) => $q->orderBy('sequence')]);
|
||||
|
||||
$groupedItems = [];
|
||||
foreach ($template->items as $item) {
|
||||
$groupedItems[$item->section][] = $item;
|
||||
}
|
||||
|
||||
// Ambil daftar unik nama section yang sudah ada untuk saran/opsi dropdown
|
||||
$availableSections = P2hTemplateItem::where('template_id', $template->id)
|
||||
->distinct()
|
||||
->pluck('section')
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return view('qma.p2h_template_detail', compact('template', 'groupedItems', 'availableSections'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Perbarui butir pertanyaan checksheet P2H yang sudah ada.
|
||||
*/
|
||||
public function updateItem(Request $request, int $templateId, int $itemId): RedirectResponse
|
||||
{
|
||||
$template = P2hTemplate::findOrFail($templateId);
|
||||
$item = P2hTemplateItem::where('template_id', $template->id)->findOrFail($itemId);
|
||||
|
||||
$allowedTypes = [
|
||||
'Multiple Lines Text Box',
|
||||
'Single Line Text Box',
|
||||
'Numerical Value',
|
||||
'Date',
|
||||
'Datetime',
|
||||
'Multiple choice: only one answer',
|
||||
'Multiple choice: multiple answers allowed',
|
||||
'Matrix',
|
||||
'choice',
|
||||
'condition',
|
||||
'number',
|
||||
'text',
|
||||
'datetime',
|
||||
'date',
|
||||
'textarea',
|
||||
];
|
||||
|
||||
$validated = $request->validate([
|
||||
'title' => 'required|string|max:255',
|
||||
'section' => 'required|string|max:100',
|
||||
'question_type' => ['required', 'string', 'max:50', \Illuminate\Validation\Rule::in($allowedTypes)],
|
||||
'sequence' => 'nullable|integer|min:1',
|
||||
]);
|
||||
|
||||
$oldSection = $item->section;
|
||||
$newSection = trim($validated['section']);
|
||||
|
||||
$item->update([
|
||||
'title' => trim($validated['title']),
|
||||
'section' => $newSection,
|
||||
'question_type' => $validated['question_type'],
|
||||
]);
|
||||
|
||||
if ($oldSection !== $newSection) {
|
||||
$targetMaxSeq = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $newSection)
|
||||
->where('id', '!=', $item->id)
|
||||
->max('sequence');
|
||||
|
||||
if ($targetMaxSeq) {
|
||||
P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('id', '!=', $item->id)
|
||||
->where('sequence', '>', $targetMaxSeq)
|
||||
->increment('sequence', 10);
|
||||
$item->update(['sequence' => $targetMaxSeq + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->resequenceTemplate($template);
|
||||
|
||||
return redirect()
|
||||
->route('qma.p2h.templates.show', $template->id)
|
||||
->with('success', "Butir pertanyaan '{$item->title}' berhasil diperbarui.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tambah butir pertanyaan baru ke dalam template checksheet.
|
||||
*/
|
||||
public function storeItem(Request $request, int $templateId): RedirectResponse
|
||||
{
|
||||
$template = P2hTemplate::findOrFail($templateId);
|
||||
|
||||
$allowedTypes = [
|
||||
'Multiple Lines Text Box',
|
||||
'Single Line Text Box',
|
||||
'Numerical Value',
|
||||
'Date',
|
||||
'Datetime',
|
||||
'Multiple choice: only one answer',
|
||||
'Multiple choice: multiple answers allowed',
|
||||
'Matrix',
|
||||
'choice',
|
||||
'condition',
|
||||
'number',
|
||||
'text',
|
||||
'datetime',
|
||||
'date',
|
||||
'textarea',
|
||||
];
|
||||
|
||||
// 1. Jika form mengirimkan daftar pertanyaan sekaligus (Tambah Section dengan List Pertanyaan)
|
||||
if ($request->has('questions') && is_array($request->input('questions'))) {
|
||||
$validated = $request->validate([
|
||||
'section' => 'required|string|max:100',
|
||||
'position_type' => 'nullable|string|in:end,start,after,before',
|
||||
'target_section' => 'nullable|string|max:100',
|
||||
'questions' => 'required|array|min:1',
|
||||
'questions.*.title' => 'required|string|max:255',
|
||||
'questions.*.question_type' => ['required', 'string', 'max:50', \Illuminate\Validation\Rule::in($allowedTypes)],
|
||||
'questions.*.sequence' => 'nullable|integer|min:1',
|
||||
]);
|
||||
|
||||
$section = trim($validated['section']);
|
||||
$positionType = $validated['position_type'] ?? 'end';
|
||||
$targetSection = !empty($validated['target_section']) ? trim($validated['target_section']) : null;
|
||||
|
||||
$validQuestions = array_values(array_filter($validated['questions'], fn($q) => !empty(trim($q['title'] ?? ''))));
|
||||
$n = count($validQuestions);
|
||||
|
||||
if ($n === 0) {
|
||||
return redirect()->back()->withErrors(['questions' => 'Minimal harus ada 1 pertanyaan yang terisi.']);
|
||||
}
|
||||
|
||||
\Illuminate\Support\Facades\DB::transaction(function () use ($template, $section, $positionType, $targetSection, $validQuestions, $n) {
|
||||
// Tentukan base sequence awal berdasarkan posisi penempatan
|
||||
if ($positionType === 'start') {
|
||||
// Geser semua item yang sudah ada
|
||||
P2hTemplateItem::where('template_id', $template->id)->increment('sequence', $n + 100);
|
||||
$startSeq = 1;
|
||||
} elseif ($positionType === 'after' && $targetSection) {
|
||||
$targetMaxSeq = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $targetSection)
|
||||
->max('sequence');
|
||||
|
||||
if ($targetMaxSeq) {
|
||||
P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('sequence', '>', $targetMaxSeq)
|
||||
->increment('sequence', $n + 100);
|
||||
$startSeq = $targetMaxSeq + 1;
|
||||
} else {
|
||||
$startSeq = (P2hTemplateItem::where('template_id', $template->id)->max('sequence') ?? 0) + 1;
|
||||
}
|
||||
} elseif ($positionType === 'before' && $targetSection) {
|
||||
$targetMinSeq = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $targetSection)
|
||||
->min('sequence');
|
||||
|
||||
if ($targetMinSeq) {
|
||||
P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('sequence', '>=', $targetMinSeq)
|
||||
->increment('sequence', $n + 100);
|
||||
$startSeq = $targetMinSeq;
|
||||
} else {
|
||||
$startSeq = (P2hTemplateItem::where('template_id', $template->id)->max('sequence') ?? 0) + 1;
|
||||
}
|
||||
} else {
|
||||
// Default 'end'
|
||||
$startSeq = (P2hTemplateItem::where('template_id', $template->id)->max('sequence') ?? 0) + 1;
|
||||
}
|
||||
|
||||
foreach ($validQuestions as $idx => $qData) {
|
||||
P2hTemplateItem::create([
|
||||
'template_id' => $template->id,
|
||||
'section' => $section,
|
||||
'title' => trim($qData['title']),
|
||||
'question_type' => $qData['question_type'],
|
||||
'sequence' => $startSeq + $idx,
|
||||
]);
|
||||
}
|
||||
|
||||
// Normalisasi ulang sequence otomatis berurutan dari section pertama hingga akhir
|
||||
$this->resequenceTemplate($template);
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('qma.p2h.templates.show', $template->id)
|
||||
->with('success', "Bagian '{$section}' dengan {$n} butir pertanyaan berhasil ditambahkan.");
|
||||
}
|
||||
|
||||
// 2. Format single question (form butir tunggal via modal tambah pertanyaan)
|
||||
$validated = $request->validate([
|
||||
'title' => 'required|string|max:255',
|
||||
'section' => 'required|string|max:100',
|
||||
'question_type' => ['required', 'string', 'max:50', \Illuminate\Validation\Rule::in($allowedTypes)],
|
||||
'sequence' => 'nullable|integer|min:1',
|
||||
]);
|
||||
|
||||
$section = trim($validated['section']);
|
||||
|
||||
\Illuminate\Support\Facades\DB::transaction(function () use ($template, $section, $validated) {
|
||||
$targetSectionMaxSeq = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $section)
|
||||
->max('sequence');
|
||||
|
||||
if ($targetSectionMaxSeq) {
|
||||
// Geser butir di section setelahnya agar pertanyaan ini diletakkan di akhir section terkait
|
||||
P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('sequence', '>', $targetSectionMaxSeq)
|
||||
->increment('sequence', 10);
|
||||
$seq = $targetSectionMaxSeq + 1;
|
||||
} else {
|
||||
$seq = (P2hTemplateItem::where('template_id', $template->id)->max('sequence') ?? 0) + 1;
|
||||
}
|
||||
|
||||
P2hTemplateItem::create([
|
||||
'template_id' => $template->id,
|
||||
'section' => $section,
|
||||
'title' => trim($validated['title']),
|
||||
'question_type' => $validated['question_type'],
|
||||
'sequence' => $seq,
|
||||
]);
|
||||
|
||||
$this->resequenceTemplate($template);
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('qma.p2h.templates.show', $template->id)
|
||||
->with('success', "Butir pertanyaan berhasil ditambahkan ke bagian '{$section}'.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Atur ulang urutan seluruh section dalam template checksheet.
|
||||
*/
|
||||
public function reorderSections(Request $request, int $templateId): RedirectResponse
|
||||
{
|
||||
$template = P2hTemplate::findOrFail($templateId);
|
||||
|
||||
$validated = $request->validate([
|
||||
'sections' => 'required|array|min:1',
|
||||
'sections.*' => 'required|string|max:100',
|
||||
]);
|
||||
|
||||
\Illuminate\Support\Facades\DB::transaction(function () use ($template, $validated) {
|
||||
$currentSequence = 1;
|
||||
|
||||
foreach ($validated['sections'] as $sectionName) {
|
||||
$items = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $sectionName)
|
||||
->orderBy('sequence')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$item->update(['sequence' => $currentSequence]);
|
||||
$currentSequence++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('qma.p2h.templates.show', $template->id)
|
||||
->with('success', 'Urutan section berhasil diperbarui.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus butir pertanyaan dari template checksheet.
|
||||
*/
|
||||
public function destroyItem(int $templateId, int $itemId): RedirectResponse
|
||||
{
|
||||
$template = P2hTemplate::findOrFail($templateId);
|
||||
$item = P2hTemplateItem::where('template_id', $template->id)->findOrFail($itemId);
|
||||
|
||||
$itemTitle = $item->title;
|
||||
$item->delete();
|
||||
|
||||
// Normalisasi ulang sequence otomatis agar tidak ada celah/lompatan nomor
|
||||
$this->resequenceTemplate($template);
|
||||
|
||||
return redirect()
|
||||
->route('qma.p2h.templates.show', $template->id)
|
||||
->with('success', "Butir pertanyaan '{$itemTitle}' berhasil dihapus.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Urutkan ulang sequence seluruh butir pertanyaan dalam template
|
||||
* agar berurutan secara konsisten dari section pertama hingga akhir (1, 2, 3... N).
|
||||
*/
|
||||
private function resequenceTemplate(P2hTemplate $template): void
|
||||
{
|
||||
$sections = P2hTemplateItem::where('template_id', $template->id)
|
||||
->select('section', \Illuminate\Support\Facades\DB::raw('MIN(sequence) as min_seq'))
|
||||
->groupBy('section')
|
||||
->orderBy('min_seq')
|
||||
->pluck('section');
|
||||
|
||||
$currentSeq = 1;
|
||||
foreach ($sections as $sectionName) {
|
||||
$items = P2hTemplateItem::where('template_id', $template->id)
|
||||
->where('section', $sectionName)
|
||||
->orderBy('sequence')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
if ($item->sequence !== $currentSeq) {
|
||||
$item->update(['sequence' => $currentSeq]);
|
||||
}
|
||||
$currentSeq++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,13 @@
|
||||
namespace App\Http\Controllers\Qma;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\P2hTemplate;
|
||||
use App\Models\Vehicle;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
|
||||
@@ -77,11 +81,11 @@ class VehicleController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Halaman khusus pengelolaan armada Kendaraan Berat (Unit Support / Alat Berat).
|
||||
* Halaman khusus pengelolaan Kategori Kendaraan Berat (Unit Support / Alat Berat).
|
||||
*/
|
||||
public function indexSupport(Request $request): View
|
||||
{
|
||||
$query = Vehicle::unitSupports();
|
||||
$query = Vehicle::unitSupportCategories()->withCount('units');
|
||||
|
||||
// Filter Status Operasional
|
||||
if ($request->filled('status')) {
|
||||
@@ -112,33 +116,202 @@ class VehicleController extends Controller
|
||||
$vehicles = $query->orderBy('code')->paginate(15)->withQueryString();
|
||||
|
||||
// Statistik Ringkasan Khusus Unit Support
|
||||
$totalSupport = Vehicle::unitSupports()->count();
|
||||
$totalOperation = Vehicle::unitSupports()->where('status', 'Operation')->count();
|
||||
$totalStandby = Vehicle::unitSupports()->where('status', 'Standby')->count();
|
||||
$totalBreakdown = Vehicle::unitSupports()->where('status', 'Breakdown')->count();
|
||||
$totalSupport = Vehicle::unitSupportCategories()->count();
|
||||
$totalUnits = Vehicle::unitSupportPhysical()->count();
|
||||
$totalOperation = Vehicle::unitSupportCategories()->where('status', 'Operation')->count();
|
||||
$totalStandby = Vehicle::unitSupportCategories()->where('status', 'Standby')->count();
|
||||
$totalBreakdown = Vehicle::unitSupportCategories()->where('status', 'Breakdown')->count();
|
||||
|
||||
// Daftar kategori alat berat yang terdaftar untuk opsi filter
|
||||
$availableCategories = Vehicle::unitSupports()
|
||||
$availableCategories = Vehicle::unitSupportCategories()
|
||||
->whereNotNull('unit_category')
|
||||
->distinct()
|
||||
->pluck('unit_category');
|
||||
|
||||
// Master data daftar divisi perusahaan (gabungan standar + data existing di Employee & Vehicle)
|
||||
$standardDivisions = collect([
|
||||
'Civil & Inviro',
|
||||
'GA',
|
||||
'HR',
|
||||
'INFORMATION & TECHNOLOGY',
|
||||
'K3',
|
||||
'Keuangan',
|
||||
'Logistik',
|
||||
'Mechanical',
|
||||
'Operasional',
|
||||
'PG',
|
||||
'Quality Management Asset (QMA)',
|
||||
]);
|
||||
|
||||
$availableDivisions = $standardDivisions
|
||||
->merge(Employee::whereNotNull('division')->where('division', '!=', '')->pluck('division'))
|
||||
->merge(Vehicle::whereNotNull('division')->where('division', '!=', '')->pluck('division'))
|
||||
->map(fn($d) => trim($d))
|
||||
->filter()
|
||||
->unique()
|
||||
->sort()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
// Daftar semua kode unit support untuk validasi unik langsung di form
|
||||
$existingCodes = Vehicle::unitSupports()->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
|
||||
|
||||
return view('qma.vehicles_support', compact(
|
||||
'vehicles',
|
||||
'totalSupport',
|
||||
'totalUnits',
|
||||
'totalOperation',
|
||||
'totalStandby',
|
||||
'totalBreakdown',
|
||||
'availableCategories',
|
||||
'availableDivisions',
|
||||
'existingCodes'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan data aset kendaraan baru (Kendaraan Ringan atau Kendaraan Berat).
|
||||
* Halaman daftar unit fisik berdasarkan kategori Unit Support yang dipilih.
|
||||
*/
|
||||
public function indexSupportUnits(Request $request, int $id): View
|
||||
{
|
||||
$category = Vehicle::unitSupportCategories()->withCount('units')->findOrFail($id);
|
||||
|
||||
$query = $category->units();
|
||||
|
||||
if ($request->filled('status')) {
|
||||
$query->where('status', $request->input('status'));
|
||||
}
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = trim($request->input('search'));
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('code', 'like', "%{$search}%")
|
||||
->orWhere('serial_number', 'like', "%{$search}%")
|
||||
->orWhere('license_plate', 'like', "%{$search}%")
|
||||
->orWhere('production_year', 'like', "%{$search}%")
|
||||
->orWhere('location', 'like', "%{$search}%")
|
||||
->orWhere('silo_document', 'like', "%{$search}%")
|
||||
->orWhere('kir_document', 'like', "%{$search}%")
|
||||
->orWhere('brand_type', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$units = $query->paginate(15)->withQueryString();
|
||||
|
||||
$totalUnits = $category->units()->count();
|
||||
$totalOperation = $category->units()->where('status', 'Operation')->count();
|
||||
$totalStandby = $category->units()->where('status', 'Standby')->count();
|
||||
$totalBreakdown = $category->units()->where('status', 'Breakdown')->count();
|
||||
$totalMaintenance = $category->units()->where('status', 'Maintenance')->count();
|
||||
|
||||
$nextUnitNumber = $category->getNextUnitNumber();
|
||||
$nextUnitCode = $category->getNextUnitCode();
|
||||
|
||||
$existingCodes = Vehicle::pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
|
||||
|
||||
// Master data lokasi penempatan (gabungan pos gerbang aktif & lokasi operasional proyek)
|
||||
$masterLocations = Gate::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->pluck('name')
|
||||
->merge(
|
||||
Vehicle::whereNotNull('location')
|
||||
->where('location', '!=', '')
|
||||
->pluck('location')
|
||||
)
|
||||
->map(fn($loc) => trim($loc))
|
||||
->filter()
|
||||
->unique()
|
||||
->sort()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return view('qma.vehicles_support_units', compact(
|
||||
'category',
|
||||
'units',
|
||||
'totalUnits',
|
||||
'totalOperation',
|
||||
'totalStandby',
|
||||
'totalBreakdown',
|
||||
'totalMaintenance',
|
||||
'nextUnitNumber',
|
||||
'nextUnitCode',
|
||||
'existingCodes',
|
||||
'masterLocations'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan penambahan unit fisik baru di bawah kategori Unit Support tertentu.
|
||||
*/
|
||||
public function storeSupportUnit(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$category = Vehicle::unitSupportCategories()->findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'unit_number' => ['nullable', 'string', 'max:20'],
|
||||
'code' => ['nullable', 'string', 'max:50'],
|
||||
'serial_number' => ['nullable', 'string', 'max:100'],
|
||||
'license_plate' => ['nullable', 'string', 'max:30'],
|
||||
'production_year' => ['nullable', 'integer', 'min:1980', 'max:' . (date('Y') + 1)],
|
||||
'status' => ['required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => ['nullable', 'numeric', 'min:0'],
|
||||
'location' => ['nullable', 'string', 'max:150'],
|
||||
'silo_document' => ['nullable', 'string', 'max:150'],
|
||||
'kir_document' => ['nullable', 'string', 'max:150'],
|
||||
'ownership' => ['nullable', 'string', 'max:150'],
|
||||
'division' => ['nullable', 'string', 'max:100'],
|
||||
]);
|
||||
|
||||
return DB::transaction(function () use ($request, $category) {
|
||||
// Tentukan nomor unit dan kode unit
|
||||
$rawUnitNumber = trim((string)$request->input('unit_number'));
|
||||
if ($rawUnitNumber !== '') {
|
||||
if (ctype_digit($rawUnitNumber)) {
|
||||
$unitNumber = str_pad($rawUnitNumber, 3, '0', STR_PAD_LEFT);
|
||||
} else {
|
||||
$unitNumber = $rawUnitNumber;
|
||||
}
|
||||
$code = strtoupper(trim($category->code . '-' . $unitNumber));
|
||||
} elseif ($request->filled('code')) {
|
||||
$code = strtoupper(trim($request->input('code')));
|
||||
} else {
|
||||
$code = $category->getNextUnitCode();
|
||||
}
|
||||
|
||||
// Validasi unik dengan lock for update
|
||||
if (Vehicle::where('code', $code)->lockForUpdate()->exists()) {
|
||||
return back()->withInput()->with('error', "Kode unit [{$code}] sudah terdaftar di sistem. Silakan gunakan nomor urut lain.");
|
||||
}
|
||||
|
||||
$unit = Vehicle::create([
|
||||
'code' => $code,
|
||||
'category' => 'unit_support',
|
||||
'parent_id' => $category->id,
|
||||
'p2h_template_id' => $category->p2h_template_id,
|
||||
'brand_type' => $category->brand_type,
|
||||
'unit_category' => $category->unit_category,
|
||||
'unit_type' => $category->unit_type,
|
||||
'brand' => $category->brand,
|
||||
'model_number' => $category->model_number,
|
||||
'license_plate' => $request->input('license_plate'),
|
||||
'serial_number' => $request->input('serial_number'),
|
||||
'production_year' => $request->input('production_year'),
|
||||
'status' => $request->input('status', 'Operation'),
|
||||
'current_km' => $request->input('current_km', 0),
|
||||
'location' => $request->input('location', $category->location),
|
||||
'ownership' => $request->input('ownership', $category->ownership),
|
||||
'division' => $request->input('division', $category->division),
|
||||
'fuel_consumption' => $category->fuel_consumption,
|
||||
'silo_document' => $request->input('silo_document'),
|
||||
'kir_document' => $request->input('kir_document'),
|
||||
]);
|
||||
|
||||
return back()->with('success', "Unit fisik [{$unit->code}] berhasil ditambahkan ke kategori {$category->unit_category}.");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan data aset kendaraan baru (Kendaraan Ringan atau Kategori Kendaraan Berat).
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
@@ -149,10 +322,11 @@ class VehicleController extends Controller
|
||||
'category' => ['required', 'in:light_vehicle,unit_support'],
|
||||
'brand_type' => ['required', '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' => ['required', 'numeric', 'min:0'],
|
||||
'status' => [$category === 'unit_support' ? 'nullable' : 'required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => [$category === 'unit_support' ? 'nullable' : 'required', 'numeric', 'min:0'],
|
||||
];
|
||||
|
||||
// Atribut opsional spesifik Unit Support (Kendaraan Berat)
|
||||
@@ -180,29 +354,51 @@ class VehicleController extends Controller
|
||||
'status.required' => 'Status operasional wajib dipilih.',
|
||||
]);
|
||||
|
||||
if ($category === 'unit_support') {
|
||||
$validated['status'] = $validated['status'] ?? 'Operation';
|
||||
$validated['current_km'] = $validated['current_km'] ?? 0;
|
||||
}
|
||||
|
||||
$vehicle = Vehicle::create($validated);
|
||||
|
||||
$categoryLabel = $vehicle->isLightVehicle() ? 'Light Vehicle (LV)' : 'Unit Support';
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
// Otomatis buatkan Master Template P2H baru (default kosong tanpa butir pertanyaan)
|
||||
$template = P2hTemplate::firstOrCreate(
|
||||
['code' => $vehicle->code],
|
||||
[
|
||||
'name' => $vehicle->unit_category ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk kategori {$vehicle->brand_type} (Kode: {$vehicle->code}).",
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
$vehicle->update(['p2h_template_id' => $template->id]);
|
||||
}
|
||||
|
||||
$categoryLabel = $vehicle->isLightVehicle() ? 'Light Vehicle (LV)' : 'Kategori Unit Support';
|
||||
|
||||
return back()->with('success', "Data {$categoryLabel} [{$vehicle->code}] berhasil ditambahkan ke sistem.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Perbarui data aset kendaraan (LV atau Unit Support).
|
||||
* Jika kode Kategori Unit Support diubah, otomatis sinkronisasikan kode seluruh unit fisik di bawahnya serta Master Template P2H.
|
||||
*/
|
||||
public function update(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$vehicle = Vehicle::findOrFail($id);
|
||||
$oldCode = $vehicle->code;
|
||||
$newCode = strtoupper(trim($request->input('code')));
|
||||
|
||||
$rules = [
|
||||
'code' => ['required', 'string', 'max:50', Rule::unique('vehicles', 'code')->ignore($vehicle->id)],
|
||||
'category' => ['required', 'in:light_vehicle,unit_support'],
|
||||
'brand_type' => ['required', 'string', 'max:150'],
|
||||
'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' => ['required', 'numeric', 'min:0'],
|
||||
'status' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
|
||||
'current_km' => [$vehicle->isSupportCategory() ? 'nullable' : 'required', 'numeric', 'min:0'],
|
||||
'unit_category' => ['nullable', 'string', 'max:100'],
|
||||
'unit_type' => ['nullable', 'string', 'max:100'],
|
||||
'brand' => ['nullable', 'string', 'max:100'],
|
||||
@@ -223,7 +419,48 @@ class VehicleController extends Controller
|
||||
'current_km.required' => 'Nilai KM / HM wajib diisi.',
|
||||
]);
|
||||
|
||||
$vehicle->update($validated);
|
||||
DB::transaction(function () use ($vehicle, $validated, $oldCode, $newCode) {
|
||||
$vehicle->update($validated);
|
||||
|
||||
// Jika ini kategori Unit Support, sinkronkan Master Template P2H dan unit-unit fisik di bawahnya
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
$template = $vehicle->p2hTemplate ?: P2hTemplate::where('code', $oldCode)->first();
|
||||
if ($template) {
|
||||
$template->update([
|
||||
'code' => $newCode,
|
||||
'name' => $vehicle->unit_category ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk kategori {$vehicle->brand_type} (Kode: {$newCode}).",
|
||||
]);
|
||||
if ($vehicle->p2h_template_id !== $template->id) {
|
||||
$vehicle->update(['p2h_template_id' => $template->id]);
|
||||
}
|
||||
} else {
|
||||
$template = P2hTemplate::firstOrCreate(
|
||||
['code' => $newCode],
|
||||
[
|
||||
'name' => $vehicle->unit_category ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk kategori {$vehicle->brand_type} (Kode: {$newCode}).",
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
$vehicle->update(['p2h_template_id' => $template->id]);
|
||||
}
|
||||
|
||||
if ($oldCode !== $newCode) {
|
||||
$childUnits = $vehicle->units()->lockForUpdate()->get();
|
||||
foreach ($childUnits as $child) {
|
||||
if (str_starts_with($child->code, $oldCode . '-')) {
|
||||
$suffix = substr($child->code, strlen($oldCode . '-'));
|
||||
$child->code = $newCode . '-' . $suffix;
|
||||
} else {
|
||||
$child->code = $newCode . '-' . $child->code;
|
||||
}
|
||||
$child->p2h_template_id = $template->id;
|
||||
$child->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return back()->with('success', "Data unit kendaraan [{$vehicle->code}] berhasil diperbarui.");
|
||||
}
|
||||
@@ -240,9 +477,30 @@ class VehicleController extends Controller
|
||||
return back()->with('error', "Unit {$vehicle->code} tidak dapat dihapus karena telah memiliki catatan riwayat pergerakan di pos gerbang.");
|
||||
}
|
||||
|
||||
// Cegah jika memiliki catatan P2H
|
||||
if ($vehicle->p2hRecords()->exists()) {
|
||||
return back()->with('error', "Aset {$vehicle->code} tidak dapat dihapus karena telah memiliki riwayat inspeksi P2H.");
|
||||
}
|
||||
|
||||
// Jika kategori memiliki unit fisik yang punya P2H atau riwayat aktivitas
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
foreach ($vehicle->units as $u) {
|
||||
if ($u->activities()->exists() || $u->p2hRecords()->exists()) {
|
||||
return back()->with('error', "Kategori {$vehicle->code} tidak dapat dihapus karena unit fisik [{$u->code}] di bawahnya telah memiliki riwayat data operasional.");
|
||||
}
|
||||
}
|
||||
|
||||
// Hapus juga master template jika belum ada riwayat inspeksi
|
||||
$template = $vehicle->p2hTemplate ?: P2hTemplate::where('code', $vehicle->code)->first();
|
||||
if ($template && !$template->records()->exists()) {
|
||||
$template->items()->delete();
|
||||
$template->delete();
|
||||
}
|
||||
}
|
||||
|
||||
$code = $vehicle->code;
|
||||
$vehicle->delete();
|
||||
|
||||
return back()->with('success', "Unit kendaraan {$code} berhasil dihapus dari sistem.");
|
||||
return back()->with('success', "Unit/Kategori kendaraan {$code} berhasil dihapus dari sistem.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\SuperAdmin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan dashboard utama Super Admin (halaman kosong / persiapan awal).
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
return view('superadmin.dashboard');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\SuperAdmin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Gate;
|
||||
use App\Models\User;
|
||||
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;
|
||||
|
||||
class UserController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan halaman utama Super Admin: Manajemen Akun & Hak Akses Seluruh Modul.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$roleFilter = $request->query('role');
|
||||
$search = trim((string) $request->query('search', ''));
|
||||
|
||||
$query = User::with(['gate', 'securityGuard.gate', 'employee'])->latest();
|
||||
|
||||
if ($roleFilter && $roleFilter !== 'all') {
|
||||
if ($roleFilter === 'admin_group') {
|
||||
$query->whereIn('role', ['super_admin', 'superadmin', 'admin', 'hse_admin', 'qma_admin', 'pg_admin']);
|
||||
} elseif ($roleFilter === 'super_admin') {
|
||||
$query->whereIn('role', ['super_admin', 'superadmin', 'admin']);
|
||||
} else {
|
||||
$query->where('role', $roleFilter);
|
||||
}
|
||||
}
|
||||
|
||||
if ($search !== '') {
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('name', 'like', "%{$search}%")
|
||||
->orWhere('username', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$users = $query->paginate(15)->withQueryString();
|
||||
|
||||
// Ringkasan Statistik Pengguna
|
||||
$stats = [
|
||||
'total' => User::count(),
|
||||
'super_admin' => User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count(),
|
||||
'hse_admin' => User::where('role', 'hse_admin')->count(),
|
||||
'qma_admin' => User::where('role', 'qma_admin')->count(),
|
||||
'pg_admin' => User::where('role', 'pg_admin')->count(),
|
||||
'gate_officer' => User::where('role', 'gate_officer')->count(),
|
||||
'employee' => User::where('role', 'employee')->count(),
|
||||
];
|
||||
|
||||
// Daftar Gerbang Aktif untuk Pilihan Pos Satpam
|
||||
$gates = Gate::where('is_active', true)->orderBy('name')->get();
|
||||
|
||||
return view('superadmin.roles_index', compact('users', 'stats', 'gates', 'roleFilter', 'search'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan akun admin / pengguna baru.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'username' => ['required', 'string', 'max:50', 'regex:/^[a-zA-Z0-9._-]+$/', 'unique:users,username'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
|
||||
'password' => ['nullable', 'string', 'min:6'],
|
||||
'role' => ['required', 'string', Rule::in(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'])],
|
||||
'gate_id' => ['nullable', 'exists:gates,id'],
|
||||
], [
|
||||
'username.unique' => 'Username tersebut sudah digunakan oleh akun lain.',
|
||||
'username.regex' => 'Username hanya boleh berupa huruf, angka, titik (.), tanda hubung (-) dan garis bawah (_).',
|
||||
'email.unique' => 'Email tersebut sudah terdaftar di sistem.',
|
||||
'password.min' => 'Password minimal terdiri dari 6 karakter.',
|
||||
'role.in' => 'Pilihan role tidak valid.',
|
||||
]);
|
||||
|
||||
// Jika bukan gate_officer, kosongkan gate_id
|
||||
if ($validated['role'] !== 'gate_officer') {
|
||||
$validated['gate_id'] = null;
|
||||
}
|
||||
|
||||
// Default password ke 'password' jika kosong atau tidak diisi
|
||||
$rawPassword = !empty($validated['password']) ? $validated['password'] : 'password';
|
||||
$validated['password'] = Hash::make($rawPassword);
|
||||
|
||||
$user = User::create($validated);
|
||||
|
||||
// Jika role adalah 'employee', buat juga record master Employee (Unit Kerja, Divisi, Jabatan Wajib Diisi)
|
||||
if ($validated['role'] === 'employee') {
|
||||
$empData = $request->validate([
|
||||
'unit_kerja' => ['required', 'string', 'max:100'],
|
||||
'division' => ['required', 'string', 'max:100'],
|
||||
'position' => ['required', 'string', 'max:100'],
|
||||
], [
|
||||
'unit_kerja.required' => 'Unit kerja wajib dipilih untuk karyawan.',
|
||||
'division.required' => 'Divisi wajib dipilih untuk karyawan.',
|
||||
'position.required' => 'Jabatan wajib diisi untuk karyawan.',
|
||||
]);
|
||||
|
||||
$nik = $validated['username'];
|
||||
|
||||
\App\Models\Employee::create([
|
||||
'user_id' => $user->id,
|
||||
'nik' => $nik,
|
||||
'name' => $validated['name'],
|
||||
'unit_kerja' => $empData['unit_kerja'],
|
||||
'division' => $empData['division'],
|
||||
'position' => $empData['position'],
|
||||
'is_operator' => false, // Default bukan driver, akan diatur oleh Admin HSE
|
||||
'simper_expired_at' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
return redirect()->route('superadmin.roles.index')
|
||||
->with('success', "Akun '{$validated['name']}' dengan role '{$validated['role']}' berhasil dibuat.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Perbarui data akun pengguna.
|
||||
*/
|
||||
public function update(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'username' => ['required', 'string', 'max:50', 'regex:/^[a-zA-Z0-9._-]+$/', Rule::unique('users', 'username')->ignore($user->id)],
|
||||
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)],
|
||||
'password' => ['nullable', 'string', 'min:6'],
|
||||
'role' => ['required', 'string', Rule::in(['super_admin', 'hse_admin', 'qma_admin', 'pg_admin', 'gate_officer', 'employee'])],
|
||||
'gate_id' => ['nullable', 'exists:gates,id'],
|
||||
], [
|
||||
'username.unique' => 'Username tersebut sudah digunakan oleh akun lain.',
|
||||
'username.regex' => 'Username hanya boleh berupa huruf, angka, titik (.), tanda hubung (-) dan garis bawah (_).',
|
||||
'email.unique' => 'Email tersebut sudah terdaftar di sistem.',
|
||||
'password.min' => 'Password baru minimal terdiri dari 6 karakter.',
|
||||
]);
|
||||
|
||||
// Keamanan: Cegah super admin terakhir mengubah rolenya sendiri menjadi role biasa
|
||||
if ($user->id === Auth::id() && $validated['role'] !== 'super_admin') {
|
||||
$superAdminCount = User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count();
|
||||
if ($superAdminCount <= 1) {
|
||||
return back()->with('error', 'Gagal: Anda adalah satu-satunya Super Admin aktif di sistem.');
|
||||
}
|
||||
}
|
||||
|
||||
if ($validated['role'] !== 'gate_officer') {
|
||||
$validated['gate_id'] = null;
|
||||
}
|
||||
|
||||
if (!empty($validated['password'])) {
|
||||
$validated['password'] = Hash::make($validated['password']);
|
||||
} else {
|
||||
unset($validated['password']);
|
||||
}
|
||||
|
||||
$user->update($validated);
|
||||
|
||||
// Jika user ini adalah karyawan, sinkronkan nama, NIK (dari username), dan data kerjanya (wajib diisi)
|
||||
if ($user->role === 'employee' || $user->employee) {
|
||||
$unitKerja = $request->input('employee_unit_kerja') ?? $request->input('unit_kerja');
|
||||
$division = $request->input('employee_division') ?? $request->input('division');
|
||||
$position = $request->input('employee_position') ?? $request->input('position');
|
||||
|
||||
if ($user->role === 'employee' && (empty($unitKerja) || empty($division) || empty($position))) {
|
||||
return back()->withErrors([
|
||||
'employee_unit_kerja' => 'Unit kerja, divisi, dan jabatan wajib diisi untuk akun karyawan.',
|
||||
])->withInput();
|
||||
}
|
||||
|
||||
$empFields = [
|
||||
'name' => $user->name,
|
||||
'nik' => $user->username,
|
||||
];
|
||||
if (!empty($unitKerja)) {
|
||||
$empFields['unit_kerja'] = $unitKerja;
|
||||
}
|
||||
if (!empty($division)) {
|
||||
$empFields['division'] = $division;
|
||||
}
|
||||
if (!empty($position)) {
|
||||
$empFields['position'] = $position;
|
||||
}
|
||||
|
||||
if ($user->employee) {
|
||||
$user->employee->update($empFields);
|
||||
} else {
|
||||
$empFields['user_id'] = $user->id;
|
||||
$empFields['is_operator'] = false;
|
||||
$empFields['simper_expired_at'] = null;
|
||||
\App\Models\Employee::create($empFields);
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()->route('superadmin.roles.index')
|
||||
->with('success', "Data akun '{$user->name}' berhasil diperbarui.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus akun pengguna.
|
||||
*/
|
||||
public function destroy(int $id): RedirectResponse
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
// Keamanan 1: Cegah Super Admin menghapus akunnya sendiri
|
||||
if ($user->id === Auth::id()) {
|
||||
return back()->with('error', 'Operasi ditolak: Anda tidak dapat menghapus akun Anda sendiri.');
|
||||
}
|
||||
|
||||
// Keamanan 2: Cegah menghapus jika merupakan super admin terakhir
|
||||
if ($user->isSuperAdmin()) {
|
||||
$superAdminCount = User::whereIn('role', ['super_admin', 'superadmin', 'admin'])->count();
|
||||
if ($superAdminCount <= 1) {
|
||||
return back()->with('error', 'Operasi ditolak: Akun Super Admin terakhir tidak boleh dihapus.');
|
||||
}
|
||||
}
|
||||
|
||||
// Keamanan 3: Cegah penghapusan jika Karyawan memiliki riwayat aktivitas atau P2H
|
||||
if ($user->employee) {
|
||||
if ($user->employee->activities()->exists()) {
|
||||
return back()->with('error', "Operasi ditolak: Akun '{$user->name}' tidak dapat dihapus karena memiliki riwayat log pergerakan kendaraan di pos gerbang.");
|
||||
}
|
||||
if ($user->employee->p2hRecords()->exists()) {
|
||||
return back()->with('error', "Operasi ditolak: Akun '{$user->name}' tidak dapat dihapus karena memiliki riwayat checksheet inspeksi keselamatan P2H.");
|
||||
}
|
||||
}
|
||||
|
||||
// Keamanan 4: Cegah penghapusan jika Petugas Satpam memiliki riwayat validasi pos gerbang
|
||||
if ($user->securityGuard) {
|
||||
if ($user->securityGuard->activities()->exists()) {
|
||||
return back()->with('error', "Operasi ditolak: Petugas Satpam '{$user->name}' tidak dapat dihapus karena telah memvalidasi aktivitas kendaraan di pos gerbang.");
|
||||
}
|
||||
}
|
||||
|
||||
$userName = $user->name;
|
||||
DB::transaction(function () use ($user) {
|
||||
if ($user->employee) {
|
||||
$user->employee->delete();
|
||||
}
|
||||
if ($user->securityGuard) {
|
||||
$user->securityGuard->delete();
|
||||
}
|
||||
$user->delete();
|
||||
});
|
||||
|
||||
return redirect()->route('superadmin.roles.index')
|
||||
->with('success', "Akun '{$userName}' telah berhasil dihapus dari sistem.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset password akun pengguna menjadi default "password".
|
||||
*/
|
||||
public function resetPassword(int $id): RedirectResponse
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
$user->update([
|
||||
'password' => Hash::make('password'),
|
||||
]);
|
||||
|
||||
return redirect()->route('superadmin.roles.index')
|
||||
->with('success', "Password akun '{$user->name}' berhasil direset ke default ('password').");
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,8 @@ class CheckRole
|
||||
|
||||
$userRole = $request->user()->role;
|
||||
|
||||
// Role 'admin' selalu memiliki hak akses penuh
|
||||
if ($userRole === 'admin' || in_array($userRole, $roles)) {
|
||||
// Role 'super_admin' dan 'admin' selalu memiliki hak akses penuh ke seluruh modul
|
||||
if (in_array($userRole, ['super_admin', 'superadmin', 'admin']) || in_array($userRole, $roles)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user