feat(timesheet): dynamically filter operators by equipment SIMPER in QMA heavy equipment timesheet

This commit is contained in:
Ray1111-aa
2026-10-28 14:18:47 +07:00
parent 852404be32
commit 68ff69e8e4
5 changed files with 279 additions and 22 deletions
@@ -147,6 +147,7 @@ class SupportTimesheetController extends Controller
$q->whereNotNull('parent_id')
->orWhereDoesntHave('units');
})
->with(['parent.requiredSimperType', 'requiredSimperType'])
->orderBy('code')
->get();
@@ -154,6 +155,18 @@ class SupportTimesheetController extends Controller
->orderBy('name')
->get(['id', 'nik', 'name', 'position', 'is_operator', 'employee_type', 'simper_expired_at']);
// Pemetaan kualifikasi SIMPER: Unit ID => Daftar Operator ID yang memiliki izin SIMPER sah
$unitOperatorsMap = [];
foreach ($unitSupports as $u) {
$eligibleIds = [];
foreach ($operators as $op) {
if ($op->hasValidSimperForVehicle($u)) {
$eligibleIds[] = $op->id;
}
}
$unitOperatorsMap[$u->id] = $eligibleIds;
}
$shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions();
@@ -178,6 +191,7 @@ class SupportTimesheetController extends Controller
'breakdownCount',
'unitSupports',
'operators',
'unitOperatorsMap',
'shifts',
'activityTypes',
'locationSuggestions',
@@ -254,8 +268,15 @@ class SupportTimesheetController extends Controller
'activity_type.required' => 'Kategori pekerjaan wajib diisi.',
]);
$vehicle = Vehicle::findOrFail($validated['vehicle_id']);
$operator = Employee::findOrFail($validated['operator_id']);
$vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
$operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
if (!$operator->hasValidSimperForVehicle($vehicle)) {
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
return back()
->withInput()
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
}
$startMeter = (float) $validated['start_meter'];
$endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null
@@ -401,6 +422,18 @@ class SupportTimesheetController extends Controller
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang';
$vehicle = Vehicle::with(['parent.requiredSimperType', 'requiredSimperType'])->findOrFail($validated['vehicle_id']);
$operator = Employee::with(['simpers.simperType'])->findOrFail($validated['operator_id']);
if ((int) $timesheet->operator_id !== (int) $operator->id || (int) $timesheet->vehicle_id !== (int) $vehicle->id) {
if (!$operator->hasValidSimperForVehicle($vehicle)) {
$unitLabel = trim("{$vehicle->code} " . ($vehicle->brand_type ?? ''));
return back()
->withInput()
->with('error', "Operator {$operator->name} ({$operator->nik}) tidak memiliki izin SIMPER yang aktif/sah untuk mengoperasikan unit {$unitLabel}.");
}
}
$timesheet->update([
'vehicle_id' => $validated['vehicle_id'],
'operator_id' => $validated['operator_id'],
+31 -8
View File
@@ -140,11 +140,12 @@ class Employee extends Model
return $this->hasValidSimper();
}
// 1. Jika kendaraan mensyaratkan spesifik required_simper_type_id
if ($vehicle->required_simper_type_id) {
// 1. Jika kendaraan atau parent category kendaraan mensyaratkan spesifik required_simper_type_id
$requiredTypeId = $vehicle->required_simper_type_id ?? $vehicle->parent?->required_simper_type_id;
if ($requiredTypeId) {
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->get();
foreach ($simpers as $s) {
if ($s->simper_type_id === $vehicle->required_simper_type_id && $s->isValid()) {
if ($s->simper_type_id === $requiredTypeId && $s->isValid()) {
return true;
}
}
@@ -159,23 +160,45 @@ class Employee extends Model
}
if ($vehicle->isUnitSupport()) {
$catName = $vehicle->unit_category ?: $vehicle->parent?->unit_category;
$brandName = $vehicle->brand_type ?: $vehicle->parent?->brand_type;
// Cek apakah personil memiliki izin SIMPER dengan scope kategori alat berat ini (misal: 'Dump Truck', 'Excavator', dll.)
if ($vehicle->unit_category && $this->hasValidSimperForScope($vehicle->unit_category)) {
if ($catName && $this->hasValidSimperForScope($catName)) {
return true;
}
if ($vehicle->brand_type && $this->hasValidSimperForScope($vehicle->brand_type)) {
if ($brandName && $this->hasValidSimperForScope($brandName)) {
return true;
}
if ($vehicle->is_timesheet_mobile) {
// Cek jika brand type mengandung kategori spesifik yang dimiliki SIMPER personil
if ($brandName) {
$simpers = $this->relationLoaded('simpers') ? $this->simpers : $this->simpers()->with('simperType')->get();
foreach ($simpers as $s) {
if ($s->isValid() && $s->simperType) {
foreach ($s->simperType->scopes as $scope) {
if (!in_array($scope, [SimperType::SCOPE_ALL, SimperType::SCOPE_LIGHT_VEHICLE, SimperType::SCOPE_UNIT_SUPPORT_MOBILE, SimperType::SCOPE_UNIT_SUPPORT_HEAVY], true)) {
if (stripos($brandName, $scope) !== false) {
return true;
}
}
}
}
}
}
$isMobile = $vehicle->is_timesheet_mobile
|| ($vehicle->parent && $vehicle->parent->is_timesheet_mobile)
|| str_starts_with(strtoupper($vehicle->code), 'DT')
|| (stripos($catName ?? '', 'Dump Truck') !== false);
if ($isMobile) {
return $this->hasValidSimperForType('SIMPER-DT')
|| $this->hasValidSimperForType('SIMPER-HEAVY')
|| $this->hasValidSimperForScope('unit_support_mobile')
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
}
return $this->hasValidSimperForType('SIMPER-HEAVY')
|| $this->hasValidSimperForType('SIMPER-DT')
|| $this->hasValidSimperForScope('unit_support_heavy')
|| $this->hasValidSimperForScope(SimperType::SCOPE_ALL);
}
+80 -12
View File
@@ -571,7 +571,7 @@
id="addOperatorSelect"
required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="">-- Pilih Operator --</option>
<option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
@foreach($operators as $op)
@php
$opType = $op->employee_type ?: 'Karyawan';
@@ -587,7 +587,7 @@
@endforeach
</select>
<p id="addOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
<span>Total personil: {{ count($operators) }}</span>
<span>Total personil: - (Pilih unit terlebih dahulu)</span>
<span class="text-emerald-700 font-semibold" id="addOperatorCurrentFilterText">Filter: Semua</span>
</p>
</div>
@@ -903,7 +903,7 @@
id="editOperatorSelect"
required
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 focus:outline-none focus:border-[#1b5e20] focus:ring-1 focus:ring-[#1b5e20] transition">
<option value="">-- Pilih Operator --</option>
<option value="">-- Pilih Heavy Equipment Terlebih Dahulu --</option>
@foreach($operators as $op)
@php
$opType = $op->employee_type ?: 'Karyawan';
@@ -919,7 +919,7 @@
@endforeach
</select>
<p id="editOperatorCountHelp" class="text-[10px] text-slate-400 mt-1 flex items-center justify-between">
<span>Total personil: {{ count($operators) }}</span>
<span>Total personil: - (Pilih unit terlebih dahulu)</span>
<span class="text-emerald-700 font-semibold" id="editOperatorCurrentFilterText">Filter: Semua</span>
</p>
</div>
@@ -1175,13 +1175,17 @@
<script>
window.unitSupportsData = @json($unitSupports);
window.allOperatorsData = @json($operators);
window.unitOperatorsMap = @json($unitOperatorsMap);
// Filter Segmented Operator (Semua / Karyawan / Sukon)
// Filter Segmented Operator (Semua / Karyawan / Sukon) & Sinkronisasi Kualifikasi SIMPER Alat Berat
function filterOperatorSelect(type, mode, preserveSelectedId) {
const selectId = mode === 'edit' ? 'editOperatorSelect' : 'addOperatorSelect';
const select = document.getElementById(selectId);
if (!select) return;
type = type || 'all';
select.setAttribute('data-active-filter', type);
// Update button states
const types = ['all', 'Karyawan', 'Sukon'];
types.forEach(t => {
@@ -1201,36 +1205,91 @@
filterText.textContent = `Filter: ${type === 'all' ? 'Semua' : type}`;
}
const vehSelect = document.getElementById(`${mode}VehicleSelect`);
const selectedVehicleId = vehSelect ? vehSelect.value : null;
const currentVal = preserveSelectedId !== undefined ? String(preserveSelectedId) : select.value;
const options = select.querySelectorAll('option');
let visibleCount = 0;
// 1. Jika belum ada unit Heavy Equipment yang dipilih
if (!selectedVehicleId) {
options.forEach(opt => {
if (!opt.value) {
opt.textContent = '-- Pilih Heavy Equipment Terlebih Dahulu --';
opt.hidden = false;
} else {
opt.hidden = true;
}
});
select.value = '';
const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
if (countHelp) {
const spanFirst = countHelp.querySelector('span:first-child');
if (spanFirst) {
spanFirst.textContent = 'Total personil: - (Pilih unit terlebih dahulu)';
spanFirst.className = 'text-slate-400';
}
}
return;
}
// 2. Dapatkan daftar ID operator yang kualifikasi SIMPER-nya aktif untuk unit ini
const eligibleMap = window.unitOperatorsMap || {};
const eligibleIds = eligibleMap[selectedVehicleId] || [];
const eligibleSet = new Set(eligibleIds.map(String));
if (preserveSelectedId !== undefined && preserveSelectedId !== null && preserveSelectedId !== '') {
eligibleSet.add(String(preserveSelectedId));
}
const hasEligible = eligibleSet.size > 0;
options.forEach(opt => {
if (!opt.value) {
if (!hasEligible) {
opt.textContent = '-- Tidak ada operator dengan SIMPER untuk unit ini --';
} else {
opt.textContent = `-- Pilih Operator (${eligibleSet.size} Memenuhi SIMPER) --`;
}
opt.hidden = false;
return;
}
const opId = String(opt.value);
const isEligible = eligibleSet.has(opId);
const optType = opt.getAttribute('data-type') || 'Karyawan';
let match = false;
let typeMatch = false;
if (type === 'all') {
match = true;
typeMatch = true;
} else if (type === 'Karyawan') {
match = optType === 'Karyawan';
typeMatch = optType === 'Karyawan';
} else if (type === 'Sukon') {
match = optType === 'Sukon';
typeMatch = optType === 'Sukon';
} else {
match = optType.toLowerCase() === type.toLowerCase();
typeMatch = optType.toLowerCase() === type.toLowerCase();
}
const match = isEligible && typeMatch;
opt.hidden = !match;
if (match) visibleCount++;
});
// Update total count
// Update total count & status
const countHelp = document.getElementById(`${mode}OperatorCountHelp`);
if (countHelp) {
const spanFirst = countHelp.querySelector('span:first-child');
if (spanFirst) spanFirst.textContent = `Total personil: ${visibleCount}`;
if (spanFirst) {
if (!hasEligible) {
spanFirst.textContent = 'Total personil: 0 (Tidak ada SIMPER yang cocok)';
spanFirst.className = 'text-rose-600 font-semibold';
} else {
spanFirst.textContent = `Total personil: ${visibleCount} dari ${eligibleSet.size} operator SIMPER aktif`;
spanFirst.className = 'text-slate-500';
}
}
}
// Restore or reset selection
@@ -1241,6 +1300,8 @@
} else if (preserveSelectedId === undefined) {
select.value = '';
}
} else {
select.value = '';
}
}
@@ -1498,6 +1559,7 @@
vehicleSelect.innerHTML = '<option value="" disabled selected>-- Pilih Lokasi Kerja Terlebih Dahulu --</option>';
if (counterBadge) counterBadge.classList.add('hidden');
if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
return;
} else if (selectedLoc === 'ALL' || selectedLoc === '__CUSTOM__') {
filteredUnits = allUnits;
@@ -1566,6 +1628,7 @@
} else {
defaultPrompt.selected = true;
if (previewEl) previewEl.classList.add('hidden');
filterOperatorSelect('all', prefix);
}
}
@@ -1620,6 +1683,11 @@
if (locSelect && locSelect.value === 'ALL' && finalLoc && !finalLoc.value) {
finalLoc.value = unitLocation;
}
// Otomatis filter operator sesuai izin SIMPER aktif untuk alat berat ini
const opSelect = document.getElementById(`${prefix}OperatorSelect`);
const currentOpFilter = opSelect ? (opSelect.getAttribute('data-active-filter') || 'all') : 'all';
filterOperatorSelect(currentOpFilter, prefix);
}
function updateMeterUnitLabels(prefix) {
@@ -139,6 +139,11 @@ class PhotoUploadAndCompressionTest extends TestCase
$deleteResponse->assertRedirect();
$this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]);
// Foto tetap dipertahankan saat soft delete agar dapat dipulihkan dari Trash/Recycle Bin
Storage::disk('public')->assertExists($photoPath);
// Ketika dihapus permanen melalui TrashService, file fisik baru terhapus
app(\App\Services\TrashService::class)->forceDeleteItem('vehicles', $vehicle->id);
Storage::disk('public')->assertMissing($photoPath);
}
+128
View File
@@ -3,6 +3,8 @@
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\EmployeeSimper;
use App\Models\SimperType;
use App\Models\UnitSupportTimesheet;
use App\Models\User;
use App\Models\Vehicle;
@@ -47,6 +49,7 @@ class QmaSupportTimesheetTest extends TestCase
$this->supportUnit = Vehicle::create([
'code' => 'EX01',
'category' => 'unit_support',
'unit_category' => 'Excavator',
'brand_type' => 'Komatsu PC200-8 Excavator',
'status' => 'Operation',
'site_status' => 'inside_site',
@@ -61,6 +64,7 @@ class QmaSupportTimesheetTest extends TestCase
'department' => 'Civil Construction',
'is_operator' => true,
'is_driver' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
}
@@ -547,4 +551,128 @@ class QmaSupportTimesheetTest extends TestCase
$responseKaryawan->assertSee('TS-KARYAWAN-001');
$responseKaryawan->assertDontSee('TS-SUKON-001');
}
/**
* Index memuat peta kualifikasi operator per alat berat (unitOperatorsMap).
*/
public function test_index_passes_unit_operators_map_matching_equipment_simper(): void
{
$simperEx = SimperType::create([
'code' => 'SIMPER-EXCAVATOR',
'name' => 'SIMPER Alat Excavator',
'category_scope' => 'Excavator',
'is_active' => true,
]);
$simperDt = SimperType::create([
'code' => 'SIMPER-DT-ONLY',
'name' => 'SIMPER Khusus DT',
'category_scope' => 'unit_support_mobile',
'is_active' => true,
]);
$opEx = Employee::create([
'nik' => 'OP-EX-001',
'name' => 'Operator Khusus Excavator',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opEx->id,
'simper_type_id' => $simperEx->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$opDt = Employee::create([
'nik' => 'OP-DT-001',
'name' => 'Driver Khusus Dump Truck',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opDt->id,
'simper_type_id' => $simperDt->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$unitDumpTruck = Vehicle::create([
'code' => 'DT99',
'category' => 'unit_support',
'unit_category' => 'Dump Truck',
'brand_type' => 'Mitsubishi Fuso 220PS',
'is_timesheet_mobile' => true,
'status' => 'Operation',
'site_status' => 'inside_site',
'location' => 'Adit 1',
'current_km' => 500.0,
]);
$response = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.index'));
$response->assertStatus(200);
$response->assertViewHas('unitOperatorsMap');
$map = $response->viewData('unitOperatorsMap');
$this->assertIsArray($map);
// Unit EX01 harus memuat $opEx dan TIDAK memuat $opDt
$this->assertContains($opEx->id, $map[$this->supportUnit->id]);
$this->assertNotContains($opDt->id, $map[$this->supportUnit->id]);
// Unit DT99 harus memuat $opDt dan TIDAK memuat $opEx
$this->assertContains($opDt->id, $map[$unitDumpTruck->id]);
$this->assertNotContains($opEx->id, $map[$unitDumpTruck->id]);
}
/**
* Operator dengan SIMPER Dump Truck ditolak saat menginput timesheet alat berat Excavator.
*/
public function test_store_fails_when_dump_truck_operator_attempts_excavator_timesheet(): void
{
$simperDt = SimperType::create([
'code' => 'SIMPER-DT-ONLY2',
'name' => 'SIMPER Khusus DT 2',
'category_scope' => 'unit_support_mobile',
'is_active' => true,
]);
$opDt = Employee::create([
'nik' => 'OP-DT-002',
'name' => 'Driver DT Saja',
'is_operator' => true,
'simper_expired_at' => Carbon::now()->addYear(),
]);
EmployeeSimper::create([
'employee_id' => $opDt->id,
'simper_type_id' => $simperDt->id,
'expired_at' => Carbon::now()->addYear(),
'status' => 'active',
]);
$data = [
'vehicle_id' => $this->supportUnit->id, // Excavator
'operator_id' => $opDt->id,
'date' => Carbon::today()->toDateString(),
'shift' => 'Shift Siang',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1258.00,
'location' => 'Main Dam',
'activity_type' => 'Galian Material',
'status' => 'Operation',
];
$response = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $data);
$response->assertRedirect();
$response->assertSessionHas('error');
$this->assertDatabaseMissing('unit_support_timesheets', [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $opDt->id,
]);
}
}