From 1590c5f1c61178c178fed5ea994544a99afcae53 Mon Sep 17 00:00:00 2001 From: Ray1111-aa Date: Tue, 20 Oct 2026 20:15:24 +0700 Subject: [PATCH] feat(qma): implement unit position tracking, gate auto-sync, history log, and exports --- .../Pg/GateInspectionController.php | 43 +- .../Qma/UnitManagementController.php | 413 +++++++ app/Models/User.php | 5 + app/Models/Vehicle.php | 60 + app/Models/VehicleActivity.php | 6 + app/Models/VehicleLocationHistory.php | 63 + ...on_histories_and_update_vehicles_table.php | 56 + resources/views/layouts/app.blade.php | 18 + resources/views/qma/unit_management.blade.php | 1045 +++++++++++++++++ routes/web.php | 8 + tests/Feature/QmaUnitManagementTest.php | 419 +++++++ 11 files changed, 2133 insertions(+), 3 deletions(-) create mode 100644 app/Http/Controllers/Qma/UnitManagementController.php create mode 100644 app/Models/VehicleLocationHistory.php create mode 100644 database/migrations/2026_10_20_000002_create_vehicle_location_histories_and_update_vehicles_table.php create mode 100644 resources/views/qma/unit_management.blade.php create mode 100644 tests/Feature/QmaUnitManagementTest.php diff --git a/app/Http/Controllers/Pg/GateInspectionController.php b/app/Http/Controllers/Pg/GateInspectionController.php index dbcbb1b..f394b06 100644 --- a/app/Http/Controllers/Pg/GateInspectionController.php +++ b/app/Http/Controllers/Pg/GateInspectionController.php @@ -6,6 +6,7 @@ use App\Http\Controllers\Controller; use App\Models\Gate; use App\Models\SecurityGuard; use App\Models\VehicleActivity; +use App\Models\VehicleLocationHistory; use Carbon\Carbon; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; @@ -115,13 +116,16 @@ class GateInspectionController extends Controller } } - $activity = VehicleActivity::with('vehicle')->findOrFail($id); + $activity = VehicleActivity::with(['vehicle', 'gate'])->findOrFail($id); if ($activity->validation_status !== 'pending') { return back()->with('error', 'Aktivitas ini sudah pernah divalidasi sebelumnya.'); } - DB::transaction(function () use ($guardId, $activity) { + $guard = SecurityGuard::find($guardId); + $guardName = $guard?->name ?? ($user?->name ?? 'Petugas Pos Gerbang'); + + DB::transaction(function () use ($guardId, $guardName, $activity, $user) { // 1. Update status aktivitas menjadi approved $activity->update([ 'validation_status' => 'approved', @@ -129,9 +133,42 @@ class GateInspectionController extends Controller 'validated_at' => Carbon::now(), ]); - // 2. Update odometer master kendaraan + // 2. Tentukan posisi site (in = inside_site, out = outside_site) + $isEntering = strtolower($activity->direction) === 'in'; + $siteStatus = $isEntering ? 'inside_site' : 'outside_site'; + $gateName = $activity->gate?->name ?? 'Pos Gerbang'; + + $detailLocation = $isEntering + ? $gateName + : ($activity->purpose ? 'Luar Site - ' . $activity->purpose : 'Luar Area Proyek'); + + $directionLabel = $isEntering ? 'Masuk' : 'Keluar'; + $note = "{$directionLabel} perlintasan {$gateName} (Trx: {$activity->transaction_no})"; + if (!$isEntering && $activity->purpose) { + $note .= " - Keperluan: {$activity->purpose}"; + } + + // 3. Update odometer dan status posisi master kendaraan $activity->vehicle->update([ 'current_km' => $activity->current_km, + 'site_status' => $siteStatus, + 'location' => $detailLocation, + 'location_updated_at' => Carbon::now(), + 'location_updated_by' => $guardName, + 'location_note' => $note, + ]); + + // 4. Catat riwayat perubahan posisi kendaraan (Audit Trail) + VehicleLocationHistory::create([ + 'vehicle_id' => $activity->vehicle_id, + 'site_status' => $siteStatus, + 'location' => $detailLocation, + 'note' => $note, + 'source' => 'gate_crossing', + 'vehicle_activity_id' => $activity->id, + 'user_id' => $user?->id, + 'user_name' => $guardName, + 'recorded_at' => Carbon::now(), ]); }); diff --git a/app/Http/Controllers/Qma/UnitManagementController.php b/app/Http/Controllers/Qma/UnitManagementController.php new file mode 100644 index 0000000..0501df4 --- /dev/null +++ b/app/Http/Controllers/Qma/UnitManagementController.php @@ -0,0 +1,413 @@ +orderBy('name')->pluck('name')->all(); + + $dbLocations = Vehicle::whereNotNull('location') + ->where('location', '!=', '') + ->pluck('location') + ->merge( + VehicleLocationHistory::whereNotNull('location') + ->where('location', '!=', '') + ->pluck('location') + ) + ->map(fn($l) => trim($l)) + ->filter() + ->unique() + ->values() + ->all(); + + return collect(array_merge( + self::PRESET_INSIDE_LOCATIONS, + self::PRESET_OUTSIDE_LOCATIONS, + $gateNames, + $dbLocations + ))->unique()->sort()->values()->all(); + } + + /** + * Query builder helper dengan filter aktif. + */ + private function getFilteredQuery(Request $request): Builder + { + $query = Vehicle::trackableUnits()->with(['parent']); + + // Filter Kategori (all, light_vehicle, unit_support) + if ($request->filled('category') && $request->input('category') !== 'all') { + $query->where('category', $request->input('category')); + } + + // Filter Status Posisi Site (all, inside_site, outside_site) + if ($request->filled('site_status') && $request->input('site_status') !== 'all') { + $query->where('site_status', $request->input('site_status')); + } + + // Filter Status Operasional (Operation, Standby, Breakdown, Maintenance) + if ($request->filled('status') && $request->input('status') !== 'all') { + $query->where('status', $request->input('status')); + } + + // Filter Kata Kunci Pencarian (Kode, Plat, Tipe, Lokasi, No Seri) + if ($request->filled('search')) { + $search = trim($request->input('search')); + $query->where(function (Builder $q) use ($search) { + $q->where('code', 'like', "%{$search}%") + ->orWhere('brand_type', 'like', "%{$search}%") + ->orWhere('license_plate', 'like', "%{$search}%") + ->orWhere('serial_number', 'like', "%{$search}%") + ->orWhere('location', 'like', "%{$search}%") + ->orWhere('location_note', 'like', "%{$search}%") + ->orWhere('division', 'like', "%{$search}%"); + }); + } + + // Urutkan: Terakhir diperbarui posisinya lebih dulu, lalu kode + return $query->orderByRaw("COALESCE(location_updated_at, updated_at) DESC")->orderBy('code'); + } + + /** + * Tampilkan halaman utama Manajemen Unit & Tracking Posisi. + */ + public function index(Request $request): View + { + $query = $this->getFilteredQuery($request); + $units = $query->paginate(15)->withQueryString(); + + // KPI Ringkasan + $baseQuery = Vehicle::trackableUnits(); + $totalUnits = (clone $baseQuery)->count(); + $insideCount = (clone $baseQuery)->where('site_status', 'inside_site')->count(); + $outsideCount = (clone $baseQuery)->where('site_status', 'outside_site')->count(); + $operationCount = (clone $baseQuery)->where('status', 'Operation')->count(); + $breakdownCount = (clone $baseQuery)->where('status', 'Breakdown')->count(); + + // Preset lokasi untuk datalist HTML + $locationSuggestions = self::getAllLocationSuggestions(); + $insidePresets = self::PRESET_INSIDE_LOCATIONS; + $outsidePresets = self::PRESET_OUTSIDE_LOCATIONS; + + return view('qma.unit_management', compact( + 'units', + 'totalUnits', + 'insideCount', + 'outsideCount', + 'operationCount', + 'breakdownCount', + 'locationSuggestions', + 'insidePresets', + 'outsidePresets' + )); + } + + /** + * Update posisi unit secara manual oleh Admin QMA dengan pencatatan audit log riwayat. + */ + public function updateLocation(Request $request, int $id): RedirectResponse|JsonResponse + { + $vehicle = Vehicle::trackableUnits()->findOrFail($id); + + $validated = $request->validate([ + 'site_status' => ['required', 'in:inside_site,outside_site'], + 'location' => ['required', 'string', 'max:255'], + 'note' => ['nullable', 'string', 'max:1000'], + ], [ + 'site_status.required' => 'Pilih status posisi unit (Di Dalam Site atau Di Luar Site).', + 'site_status.in' => 'Status posisi tidak valid.', + 'location.required' => 'Detail lokasi penempatan wajib diisi.', + 'location.max' => 'Detail lokasi maksimal 255 karakter.', + ]); + + $updaterName = auth()->user()?->name ?? 'Admin QMA'; + $location = trim($validated['location']); + $note = !empty($validated['note']) ? trim($validated['note']) : null; + + DB::transaction(function () use ($vehicle, $validated, $location, $note, $updaterName) { + // 1. Update data master posisi kendaraan + $vehicle->update([ + 'site_status' => $validated['site_status'], + 'location' => $location, + 'location_updated_at' => Carbon::now(), + 'location_updated_by' => $updaterName, + 'location_note' => $note, + ]); + + // 2. Simpan jejak riwayat pergerakan (audit trail) + VehicleLocationHistory::create([ + 'vehicle_id' => $vehicle->id, + 'site_status' => $validated['site_status'], + 'location' => $location, + 'note' => $note, + 'source' => 'manual', + 'user_id' => auth()->id(), + 'user_name' => $updaterName, + 'recorded_at' => Carbon::now(), + ]); + }); + + $statusText = $validated['site_status'] === 'inside_site' ? 'Di Dalam Site' : 'Di Luar Site'; + $msg = "Posisi unit {$vehicle->code} berhasil diperbarui: {$statusText} ({$location})."; + + if ($request->wantsJson()) { + return response()->json([ + 'success' => true, + 'message' => $msg, + 'vehicle' => $vehicle->fresh(), + ]); + } + + return back()->with('success', $msg); + } + + /** + * Ambil riwayat pergerakan posisi suatu unit (JSON) untuk modal timeline / audit trail. + */ + public function history(int $id): JsonResponse + { + $vehicle = Vehicle::trackableUnits()->findOrFail($id); + + $histories = $vehicle->locationHistories() + ->with(['user', 'activity.gate']) + ->latest('recorded_at') + ->take(50) + ->get(); + + $items = $histories->map(function (VehicleLocationHistory $h) { + return [ + 'id' => $h->id, + 'site_status' => $h->site_status, + 'site_status_label' => $h->site_status_label, + 'location' => $h->location, + 'note' => $h->note ?: '-', + 'source' => $h->source, + 'source_label' => $h->source_label, + 'updater' => $h->user_name ?: ($h->user?->name ?? 'Sistem'), + 'recorded_at' => $h->recorded_at ? $h->recorded_at->translatedFormat('d M Y, H:i') : '-', + 'time_ago' => $h->recorded_at ? $h->recorded_at->diffForHumans() : '-', + 'trx_no' => $h->activity?->transaction_no ?? null, + ]; + }); + + return response()->json([ + 'vehicle' => [ + 'id' => $vehicle->id, + 'code' => $vehicle->code, + 'brand_type' => $vehicle->brand_type, + 'license_plate' => $vehicle->license_plate ?: '-', + 'category' => $vehicle->isLightVehicle() ? 'Light Vehicle' : 'Unit Support', + 'photo_url' => $vehicle->photo_url, + 'site_status' => $vehicle->site_status ?? 'inside_site', + 'site_status_label' => $vehicle->site_status_label, + 'location' => $vehicle->location ?: 'Belum diisi', + 'location_updated_at' => $vehicle->location_updated_at ? $vehicle->location_updated_at->translatedFormat('d M Y, H:i') : '-', + 'location_updated_by' => $vehicle->location_updated_by ?: '-', + ], + 'count' => $histories->count(), + 'histories' => $items, + ]); + } + + /** + * Ekspor data monitoring posisi unit ke format Excel (.xlsx). + */ + public function exportExcel(Request $request): Response + { + $units = $this->getFilteredQuery($request)->get(); + + $metaLines = [ + 'Laporan Monitoring & Tracking Posisi Unit (QMA)', + 'Filter Kategori: ' . ($request->filled('category') && $request->input('category') !== 'all' ? ($request->input('category') === 'light_vehicle' ? 'Light Vehicle' : 'Unit Support') : 'Semua Unit'), + 'Filter Posisi Site: ' . ($request->filled('site_status') && $request->input('site_status') !== 'all' ? ($request->input('site_status') === 'inside_site' ? 'Di Dalam Site' : 'Di Luar Site') : 'Semua Posisi'), + 'Waktu Ekspor: ' . Carbon::now()->translatedFormat('d F Y, H:i') . ' WIB', + ]; + + $headers = [ + 'NO' => 6, + 'KODE UNIT' => 14, + 'KATEGORI' => 16, + 'MEREK / MODEL' => 28, + 'PLAT / NO SERI' => 18, + 'STATUS SITE' => 16, + 'DETAIL LOKASI' => 26, + 'STATUS OPR' => 14, + 'UPDATE TERAKHIR' => 20, + 'PETUGAS UPDATE' => 22, + 'CATATAN' => 32, + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $catLabel = $u->isLightVehicle() ? 'Light Vehicle' : 'Unit Support'; + $plateOrSn = $u->license_plate ?: ($u->serial_number ?: '-'); + $updatedAt = $u->location_updated_at ? $u->location_updated_at->format('d/m/Y H:i') : ($u->updated_at ? $u->updated_at->format('d/m/Y H:i') : '-'); + + $rows[] = [ + $idx + 1, + $u->code, + $catLabel, + $u->brand_type ?: '-', + $plateOrSn, + $u->site_status_label, + $u->location ?: '-', + $u->status ?: 'Standby', + $updatedAt, + $u->location_updated_by ?: '-', + $u->location_note ?: '-', + ]; + } + + $alignments = [ + 'NO' => 'center', + 'KODE UNIT' => 'center', + 'KATEGORI' => 'center', + 'PLAT / NO SERI' => 'center', + 'STATUS SITE' => 'center', + 'STATUS OPR' => 'center', + 'UPDATE TERAKHIR' => 'center', + ]; + + $xlsxContent = SimpleXlsxExporter::create( + 'DATA MONITORING POSISI UNIT KERINCI HYDROPOWER', + $metaLines, + $headers, + $rows, + $alignments + ); + + $fileName = 'Manajemen_Posisi_Unit_' . Carbon::now()->format('Ymd_His') . '.xlsx'; + + return response($xlsxContent, 200, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="' . $fileName . '"', + 'Content-Length' => strlen($xlsxContent), + 'Cache-Control' => 'max-age=0', + ]); + } + + /** + * Ekspor data monitoring posisi unit ke format PDF. + */ + public function exportPdf(Request $request): Response + { + $units = $this->getFilteredQuery($request)->get(); + + $metaLeft = [ + 'Sub-Sistem' => 'Quality Management Asset (QMA)', + 'Kategori' => $request->filled('category') && $request->input('category') !== 'all' ? ($request->input('category') === 'light_vehicle' ? 'Light Vehicle' : 'Unit Support') : 'Semua Unit', + 'Status Posisi' => $request->filled('site_status') && $request->input('site_status') !== 'all' ? ($request->input('site_status') === 'inside_site' ? 'Di Dalam Site' : 'Di Luar Site') : 'Semua Posisi', + ]; + + $metaRight = [ + 'Waktu Cetak' => Carbon::now()->translatedFormat('d F Y, H:i') . ' WIB', + 'Dicetak Oleh' => auth()->user()?->name ?? 'Admin QMA', + 'Total Armada' => $units->count() . ' Unit Terdata', + ]; + + $columns = [ + ['title' => 'NO', 'width' => 10, 'align' => 'C', 'bold' => true], + ['title' => 'KODE', 'width' => 20, 'align' => 'C', 'bold' => true], + ['title' => 'KATEGORI', 'width' => 26, 'align' => 'C'], + ['title' => 'MEREK / TIPE', 'width' => 50, 'align' => 'L', 'max_char' => 32], + ['title' => 'PLAT / SERI', 'width' => 28, 'align' => 'C'], + ['title' => 'POSISI SITE', 'width' => 30, 'align' => 'C', 'is_status' => true], + ['title' => 'DETAIL LOKASI', 'width' => 45, 'align' => 'L', 'max_char' => 28], + ['title' => 'STATUS', 'width' => 26, 'align' => 'C', 'is_status' => true], + ['title' => 'UPDATE', 'width' => 32, 'align' => 'C'], + ]; + + $rows = []; + foreach ($units as $idx => $u) { + $catLabel = $u->isLightVehicle() ? 'Light Vehicle' : 'Unit Support'; + $plateOrSn = $u->license_plate ?: ($u->serial_number ?: '-'); + $updatedAt = $u->location_updated_at ? $u->location_updated_at->format('d/m/Y H:i') : ($u->updated_at ? $u->updated_at->format('d/m/Y H:i') : '-'); + + $rows[] = [ + $idx + 1, + $u->code, + $catLabel, + $u->brand_type ?: '-', + $plateOrSn, + $u->site_status_label, + $u->location ?: '-', + $u->status ?: 'Standby', + $updatedAt, + ]; + } + + $subtitle = 'Monitoring Posisi Armada LV & Unit Support Proyek Kerinci Hydropower'; + $pdfBinary = QmaTablePdfExporter::generate( + 'Laporan Monitoring Posisi Unit', + $subtitle, + 'SISTEM QMA RKM-KMH', + $metaLeft, + $metaRight, + $columns, + $rows + ); + + $fileName = 'Laporan_Posisi_Unit_' . Carbon::now()->format('Ymd_His') . '.pdf'; + + return response($pdfBinary, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="' . $fileName . '"', + 'Content-Length' => strlen($pdfBinary), + 'Cache-Control' => 'private, max-age=0, must-revalidate', + 'Pragma' => 'public', + ]); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 1000393..4c82c76 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -183,6 +183,11 @@ class User extends Authenticatable return null; } + public function locationHistories(): HasMany + { + return $this->hasMany(VehicleLocationHistory::class); + } + public function isEmployee(): bool { if ($this->isSuperAdmin()) { diff --git a/app/Models/Vehicle.php b/app/Models/Vehicle.php index 49ca044..62c4d38 100644 --- a/app/Models/Vehicle.php +++ b/app/Models/Vehicle.php @@ -32,6 +32,10 @@ class Vehicle extends Model 'model_number', 'production_year', 'location', + 'site_status', + 'location_updated_at', + 'location_updated_by', + 'location_note', 'fuel_consumption', 'silo_document', 'stnk_document', @@ -44,12 +48,29 @@ class Vehicle extends Model 'fuel_consumption' => 'decimal:2', 'production_year' => 'integer', 'parent_id' => 'integer', + 'location_updated_at' => 'datetime', ]; protected $appends = [ 'photo_url', + 'site_status_label', ]; + public function isInsideSite(): bool + { + return ($this->site_status ?? 'inside_site') === 'inside_site'; + } + + public function isOutsideSite(): bool + { + return ($this->site_status ?? 'inside_site') === 'outside_site'; + } + + public function getSiteStatusLabelAttribute(): string + { + return $this->isOutsideSite() ? 'Di Luar Site' : 'Di Dalam Site'; + } + public function isLightVehicle(): bool { return $this->category === 'light_vehicle'; @@ -103,6 +124,35 @@ class Vehicle extends Model return $query->where('category', 'unit_support')->whereNotNull('parent_id'); } + /** + * Scope untuk seluruh unit operasional yang dapat dilacak posisinya: + * - Seluruh Light Vehicle + * - Seluruh Unit Support fisik (anak kategori) ATAU kategori tunggal yang belum memiliki anak unit + */ + public function scopeTrackableUnits(Builder $query): Builder + { + return $query->where(function (Builder $q) { + $q->where('category', 'light_vehicle') + ->orWhere(function (Builder $sq) { + $sq->where('category', 'unit_support') + ->where(function (Builder $sub) { + $sub->whereNotNull('parent_id') + ->orWhereDoesntHave('units'); + }); + }); + }); + } + + public function scopeInsideSite(Builder $query): Builder + { + return $query->where('site_status', 'inside_site'); + } + + public function scopeOutsideSite(Builder $query): Builder + { + return $query->where('site_status', 'outside_site'); + } + public function parent(): BelongsTo { return $this->belongsTo(Vehicle::class, 'parent_id'); @@ -167,6 +217,16 @@ class Vehicle extends Model return $this->hasOne(VehicleActivity::class)->latestOfMany('recorded_at'); } + public function locationHistories(): HasMany + { + return $this->hasMany(VehicleLocationHistory::class)->orderByDesc('recorded_at'); + } + + public function latestLocationHistory(): HasOne + { + return $this->hasOne(VehicleLocationHistory::class)->latestOfMany('recorded_at'); + } + /** * Tentukan arah gerbang berikutnya yang sah: * - 'ANY' jika belum pernah ada riwayat (kendaraan baru) diff --git a/app/Models/VehicleActivity.php b/app/Models/VehicleActivity.php index 5d35914..f02d684 100644 --- a/app/Models/VehicleActivity.php +++ b/app/Models/VehicleActivity.php @@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; class VehicleActivity extends Model { @@ -69,6 +70,11 @@ class VehicleActivity extends Model return $this->belongsTo(User::class, 'corrected_by_user_id'); } + public function locationHistories(): HasMany + { + return $this->hasMany(VehicleLocationHistory::class, 'vehicle_activity_id'); + } + public function isPending(): bool { return $this->validation_status === 'pending'; diff --git a/app/Models/VehicleLocationHistory.php b/app/Models/VehicleLocationHistory.php new file mode 100644 index 0000000..0fb7007 --- /dev/null +++ b/app/Models/VehicleLocationHistory.php @@ -0,0 +1,63 @@ + 'datetime', + ]; + + public function vehicle(): BelongsTo + { + return $this->belongsTo(Vehicle::class); + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + public function activity(): BelongsTo + { + return $this->belongsTo(VehicleActivity::class, 'vehicle_activity_id'); + } + + public function isInsideSite(): bool + { + return $this->site_status === 'inside_site'; + } + + public function isOutsideSite(): bool + { + return $this->site_status === 'outside_site'; + } + + public function getSiteStatusLabelAttribute(): string + { + return $this->site_status === 'outside_site' ? 'Di Luar Site' : 'Di Dalam Site'; + } + + public function getSourceLabelAttribute(): string + { + return $this->source === 'gate_crossing' ? 'Pos Gerbang (Otomatis)' : 'Manual QMA'; + } +} diff --git a/database/migrations/2026_10_20_000002_create_vehicle_location_histories_and_update_vehicles_table.php b/database/migrations/2026_10_20_000002_create_vehicle_location_histories_and_update_vehicles_table.php new file mode 100644 index 0000000..7c56589 --- /dev/null +++ b/database/migrations/2026_10_20_000002_create_vehicle_location_histories_and_update_vehicles_table.php @@ -0,0 +1,56 @@ +string('site_status')->default('inside_site')->after('status'); + $table->timestamp('location_updated_at')->nullable()->after('location'); + $table->string('location_updated_by')->nullable()->after('location_updated_at'); + $table->text('location_note')->nullable()->after('location_updated_by'); + }); + + // 2. Buat tabel riwayat perubahan posisi unit (audit trail log) + Schema::create('vehicle_location_histories', function (Blueprint $table) { + $table->id(); + $table->foreignId('vehicle_id')->constrained('vehicles')->cascadeOnDelete(); + $table->string('site_status')->default('inside_site'); // 'inside_site' atau 'outside_site' + $table->string('location'); // Detail lokasi penempatan + $table->text('note')->nullable(); // Catatan pergerakan / keperluan + $table->string('source')->default('manual'); // 'manual' (input user QMA) atau 'gate_crossing' (otomatis pos gerbang) + $table->foreignId('vehicle_activity_id')->nullable()->constrained('vehicle_activities')->nullOnDelete(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('user_name')->nullable(); // Snapshot nama pengubah posisi + $table->timestamp('recorded_at')->useCurrent(); + $table->timestamps(); + + $table->index(['vehicle_id', 'recorded_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('vehicle_location_histories'); + + Schema::table('vehicles', function (Blueprint $table) { + $table->dropColumn([ + 'site_status', + 'location_updated_at', + 'location_updated_by', + 'location_note', + ]); + }); + } +}; diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 65a31cd..3f7b354 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -306,6 +306,14 @@ @endcan + @can('qma.vehicles.view') + + + Manajemen Unit + + @endcan + @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @php $isActivityRoute = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @@ -620,6 +628,14 @@ @endcan + @can('qma.vehicles.view') + + + Manajemen Unit + + @endcan + @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @php $isActivityRouteMob = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); @@ -792,6 +808,8 @@ Unit Support @elseif(request()->routeIs('qma.vehicles.*')) Data Kendaraan + @elseif(request()->routeIs('qma.unit_management.*')) + Manajemen Unit @elseif(request()->routeIs('qma.activity.log')) Timesheet LV @elseif(request()->routeIs('qma.p2h.summary')) diff --git a/resources/views/qma/unit_management.blade.php b/resources/views/qma/unit_management.blade.php new file mode 100644 index 0000000..2d4f816 --- /dev/null +++ b/resources/views/qma/unit_management.blade.php @@ -0,0 +1,1045 @@ +@extends('layouts.app') + +@section('title', 'Manajemen Unit - Admin QMA | PT Kerinci Merangin Hidro') + +@section('content') +
+ + +
+
+
+ + MANAJEMEN QMA + + + +
+

+ Manajemen Unit +

+

+ Monitoring posisi terkini, tracking pergerakan, dan audit log riwayat lokasi armada LV & Unit Support. +

+
+ + +
+ + +
+
+ + +
+ +
+
+

Total Unit

+

{{ number_format($totalUnits, 0, ',', '.') }}

+ Armada Aktif Terdata +
+
+ +
+
+ + +
+
+

Di Dalam Site

+

{{ number_format($insideCount, 0, ',', '.') }}

+ + + Area Proyek KMH + +
+
+ +
+
+ + +
+
+

Di Luar Site

+

{{ number_format($outsideCount, 0, ',', '.') }}

+ + + Dinas / Luar Area + +
+
+ +
+
+ + +
+
+

Siap Operasi

+

{{ number_format($operationCount, 0, ',', '.') }}

+ Status Operation +
+
+ +
+
+ + +
+
+

Breakdown

+

{{ number_format($breakdownCount, 0, ',', '.') }}

+ Butuh Perbaikan +
+
+ +
+
+
+ + +
+ +
+ + + +
+ Menampilkan {{ $units->total() }} unit terdaftar +
+
+ + +
+ @if(request('category')) + + @endif + + +
+ + + + +
+ + +
+ +
+ + +
+ +
+ + +
+ + + @if(request('search') || (request('site_status') && request('site_status') !== 'all') || (request('status') && request('status') !== 'all') || (request('category') && request('category') !== 'all')) + + + + @endif +
+
+
+ + + @if(session('success')) +
+
+ + {{ session('success') }} +
+ +
+ @endif + + @if(session('error')) +
+
+ + {{ session('error') }} +
+ +
+ @endif + + +
+
+ + + + + + + + + + + + + + + + @forelse($units as $idx => $u) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @empty + + + + @endforelse + +
NOFOTOKODE & TIPE UNITPLAT / NO SERIPOSISI SITEDETAIL LOKASIUPDATE TERAKHIRSTATUS OPRAKSI
+ {{ $units->firstItem() + $idx }} + + @if($u->photo_url) + + @else +
+ +
+ @endif +
+
+ + {{ $u->code }} + + @if($u->isLightVehicle()) + + LV + + @else + + Support + + @endif +
+
+ {{ $u->brand_type ?: 'Unit Tanpa Merek' }} +
+
+ {{ $u->division ?: ($u->ownership ?: 'Operasional KMH') }} +
+
+ @if($u->license_plate) + {{ $u->license_plate }} + @elseif($u->serial_number) + SN: {{ $u->serial_number }} + @else + - + @endif + + @if($u->site_status === 'outside_site') + + + Di Luar Site + + @else + + + Di Dalam Site + + @endif + +
+ + + {{ $u->location ?: 'Belum ditentukan' }} + +
+ @if($u->location_note) +

+ "{{ $u->location_note }}" +

+ @endif +
+ @php + $time = $u->location_updated_at ?? $u->updated_at; + @endphp + @if($time) +
+ {{ $time->diffForHumans() }} +
+
+ {{ $time->translatedFormat('d M Y, H:i') }} +
+ @if($u->location_updated_by) +
+ + {{ $u->location_updated_by }} +
+ @endif + @else + - + @endif +
+ @if($u->status === 'Operation') + + Operation + + @elseif($u->status === 'Standby') + + Standby + + @elseif($u->status === 'Breakdown') + + Breakdown + + @else + + {{ $u->status }} + + @endif + +
+ + @can('qma.vehicles.edit') + + @endcan + + + +
+
+ +

Tidak ada data unit yang sesuai kriteria

+

Coba sesuaikan filter pencarian atau reset filter di atas.

+ @if(request()->anyFilled(['search', 'site_status', 'status', 'category'])) + + @endif +
+
+ + + @if($units->hasPages()) +
+
+ Menampilkan data {{ $units->firstItem() }} sampai {{ $units->lastItem() }} dari total {{ $units->total() }} unit +
+
+ {{ $units->links() }} +
+
+ @endif +
+ +
+ + + + + + + + + @foreach($locationSuggestions as $loc) + + + + + + + + + + + + + + + + + + + + +@endsection + +@push('scripts') + +@endpush diff --git a/routes/web.php b/routes/web.php index 818e93a..552d140 100644 --- a/routes/web.php +++ b/routes/web.php @@ -17,6 +17,7 @@ use App\Http\Controllers\Public\VehicleActivityFormController; use App\Http\Controllers\Qma\ActivityLogController; use App\Http\Controllers\Qma\P2hInspectionController; use App\Http\Controllers\Qma\P2hTemplateController; +use App\Http\Controllers\Qma\UnitManagementController; use App\Http\Controllers\Qma\VehicleController; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; @@ -91,6 +92,13 @@ Route::middleware('auth')->group(function () { Route::get('/activity-summary/export-excel', [ActivityLogController::class, 'exportSummaryExcel'])->name('activity.summary.export_excel')->middleware('permission:qma.summary.view'); Route::get('/activity-summary/export-pdf', [ActivityLogController::class, 'exportSummaryPdf'])->name('activity.summary.export_pdf')->middleware('permission:qma.summary.view'); + // Manajemen Unit (Tracking & Monitoring Posisi LV & Unit Support) + Route::get('/unit-management', [UnitManagementController::class, 'index'])->name('unit_management.index')->middleware('permission:qma.vehicles.view'); + Route::post('/unit-management/{id}/location', [UnitManagementController::class, 'updateLocation'])->name('unit_management.update_location')->middleware('permission:qma.vehicles.edit'); + Route::get('/unit-management/{id}/history', [UnitManagementController::class, 'history'])->name('unit_management.history')->middleware('permission:qma.vehicles.view'); + Route::get('/unit-management/export-excel', [UnitManagementController::class, 'exportExcel'])->name('unit_management.export_excel')->middleware('permission:qma.vehicles.view'); + Route::get('/unit-management/export-pdf', [UnitManagementController::class, 'exportPdf'])->name('unit_management.export_pdf')->middleware('permission:qma.vehicles.view'); + // Log Pemeriksaan P2H Unit Support & Approval Admin QMA Route::get('/p2h-records', [P2hInspectionController::class, 'index'])->name('p2h.index')->middleware('permission:qma.p2h.view|qma.vehicles.view'); Route::get('/p2h-records/export-excel', [P2hInspectionController::class, 'exportExcel'])->name('p2h.export_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view'); diff --git a/tests/Feature/QmaUnitManagementTest.php b/tests/Feature/QmaUnitManagementTest.php new file mode 100644 index 0000000..f91c478 --- /dev/null +++ b/tests/Feature/QmaUnitManagementTest.php @@ -0,0 +1,419 @@ + 'qma.vehicles.view', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'qma.vehicles.edit', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'gate.inspect', 'guard_name' => 'web']); + + $qmaRole = Role::firstOrCreate(['name' => 'qma_admin', 'guard_name' => 'web']); + $qmaRole->givePermissionTo(['qma.vehicles.view', 'qma.vehicles.edit']); + + $gateRole = Role::firstOrCreate(['name' => 'gate_officer', 'guard_name' => 'web']); + $gateRole->givePermissionTo(['gate.inspect']); + + $this->gate = Gate::firstOrCreate( + ['code' => 'GATE-01'], + ['name' => 'Pos Gerbang Beringin Tunggal', 'is_active' => true] + ); + + $this->guard = SecurityGuard::firstOrCreate( + ['badge_id' => 'SEC-001'], + ['name' => 'Budi Santoso', 'is_active' => true] + ); + + $this->qmaAdmin = User::firstOrCreate( + ['username' => 'qma_admin_test'], + [ + 'name' => 'Admin QMA Test', + 'email' => 'qma_admin_test@kmh.co.id', + 'role' => 'qma_admin', + 'password' => bcrypt('password'), + ] + ); + $this->qmaAdmin->assignRole('qma_admin'); + + $this->gateOfficer = User::firstOrCreate( + ['username' => 'satpam_test'], + [ + 'name' => 'Petugas Gerbang Test', + 'email' => 'satpam_test@kmh.co.id', + 'role' => 'gate_officer', + 'gate_id' => $this->gate->id, + 'password' => bcrypt('password'), + ] + ); + $this->gateOfficer->assignRole('gate_officer'); + } + + /** + * User yang belum login diarahkan ke halaman login. + */ + public function test_unauthenticated_user_is_redirected_to_login(): void + { + $response = $this->get(route('qma.unit_management.index')); + $response->assertRedirect(route('login')); + } + + /** + * Admin QMA dapat membuka halaman Manajemen Unit dan melihat daftar unit serta KPI ringkasan. + */ + public function test_qma_admin_can_view_unit_management_page(): void + { + $lv = Vehicle::create([ + 'code' => 'LV-TEST-01', + 'category' => 'light_vehicle', + 'brand_type' => 'Toyota Hilux 4x4', + 'license_plate' => 'BH 1234 KM', + 'status' => 'Operation', + 'site_status' => 'inside_site', + 'location' => 'Main Dam', + 'current_km' => 15000, + ]); + + $support = Vehicle::create([ + 'code' => 'EX-TEST-01', + 'category' => 'unit_support', + 'brand_type' => 'Komatsu PC200', + 'status' => 'Operation', + 'site_status' => 'outside_site', + 'location' => 'Kota Bangko', + ]); + + $response = $this->actingAs($this->qmaAdmin)->get(route('qma.unit_management.index')); + + $response->assertStatus(200); + $response->assertSee('Manajemen Unit'); + $response->assertSee('LV-TEST-01'); + $response->assertSee('EX-TEST-01'); + $response->assertSee('Main Dam'); + $response->assertSee('Kota Bangko'); + $response->assertSee('Di Dalam Site'); + $response->assertSee('Di Luar Site'); + } + + /** + * Filter kategori dan posisi site bekerja dengan benar. + */ + public function test_unit_management_filtering_by_category_and_site_status(): void + { + Vehicle::create([ + 'code' => 'LV-INSIDE', + 'category' => 'light_vehicle', + 'brand_type' => 'Hilux', + 'site_status' => 'inside_site', + 'location' => 'Powerhouse', + 'status' => 'Operation', + ]); + + Vehicle::create([ + 'code' => 'LV-OUTSIDE', + 'category' => 'light_vehicle', + 'brand_type' => 'Fortuner', + 'site_status' => 'outside_site', + 'location' => 'Kota Jambi', + 'status' => 'Operation', + ]); + + // Filter inside_site + $resInside = $this->actingAs($this->qmaAdmin) + ->get(route('qma.unit_management.index', ['site_status' => 'inside_site'])); + + $resInside->assertStatus(200); + $resInside->assertSee('LV-INSIDE'); + $resInside->assertDontSee('LV-OUTSIDE'); + + // Filter outside_site + $resOutside = $this->actingAs($this->qmaAdmin) + ->get(route('qma.unit_management.index', ['site_status' => 'outside_site'])); + + $resOutside->assertStatus(200); + $resOutside->assertSee('LV-OUTSIDE'); + $resOutside->assertDontSee('LV-INSIDE'); + } + + /** + * Admin QMA dapat memperbarui posisi unit secara manual dan audit riwayat tersimpan. + */ + public function test_manual_update_location_updates_vehicle_and_creates_history(): void + { + $vehicle = Vehicle::create([ + 'code' => 'LV-UPDATE-01', + 'category' => 'light_vehicle', + 'brand_type' => 'Triton 4x4', + 'site_status' => 'inside_site', + 'location' => 'Workshop GA', + 'status' => 'Operation', + ]); + + $response = $this->actingAs($this->qmaAdmin) + ->post(route('qma.unit_management.update_location', $vehicle->id), [ + 'site_status' => 'outside_site', + 'location' => 'Bengkel Rekanan Bangko', + 'note' => 'Perbaikan radiator dan ganti oli', + ]); + + $response->assertRedirect(); + $response->assertSessionHas('success'); + + // Verifikasi update master kendaraan + $vehicle->refresh(); + $this->assertEquals('outside_site', $vehicle->site_status); + $this->assertEquals('Bengkel Rekanan Bangko', $vehicle->location); + $this->assertEquals('Admin QMA Test', $vehicle->location_updated_by); + $this->assertEquals('Perbaikan radiator dan ganti oli', $vehicle->location_note); + $this->assertNotNull($vehicle->location_updated_at); + + // Verifikasi pembuatan riwayat audit + $this->assertDatabaseHas('vehicle_location_histories', [ + 'vehicle_id' => $vehicle->id, + 'site_status' => 'outside_site', + 'location' => 'Bengkel Rekanan Bangko', + 'note' => 'Perbaikan radiator dan ganti oli', + 'source' => 'manual', + 'user_name' => 'Admin QMA Test', + ]); + } + + /** + * Endpoint API riwayat mengembalikan format JSON lengkap dengan timeline logs. + */ + public function test_unit_history_endpoint_returns_json_history(): void + { + $vehicle = Vehicle::create([ + 'code' => 'LV-HIST-01', + 'category' => 'light_vehicle', + 'brand_type' => 'Pajero Sport', + 'site_status' => 'outside_site', + 'location' => 'Mess Kumun', + 'status' => 'Operation', + ]); + + VehicleLocationHistory::create([ + 'vehicle_id' => $vehicle->id, + 'site_status' => 'inside_site', + 'location' => 'Adit 1', + 'note' => 'Inspeksi terowongan', + 'source' => 'manual', + 'user_id' => $this->qmaAdmin->id, + 'user_name' => 'Admin QMA Test', + 'recorded_at' => Carbon::now()->subHours(2), + ]); + + VehicleLocationHistory::create([ + 'vehicle_id' => $vehicle->id, + 'site_status' => 'outside_site', + 'location' => 'Mess Kumun', + 'note' => 'Istirahat driver', + 'source' => 'manual', + 'user_id' => $this->qmaAdmin->id, + 'user_name' => 'Admin QMA Test', + 'recorded_at' => Carbon::now(), + ]); + + $response = $this->actingAs($this->qmaAdmin) + ->get(route('qma.unit_management.history', $vehicle->id)); + + $response->assertStatus(200); + $response->assertJsonStructure([ + 'vehicle' => ['id', 'code', 'brand_type', 'site_status', 'location'], + 'count', + 'histories' => [ + '*' => ['id', 'site_status', 'site_status_label', 'location', 'note', 'source', 'source_label', 'updater', 'recorded_at'] + ], + ]); + + $this->assertEquals(2, $response->json('count')); + } + + /** + * Integrasi otomatis: Saat aktivitas gerbang arah Masuk (IN) disetujui Satpam, + * kendaraan otomatis berubah status menjadi inside_site dengan lokasi nama gerbang. + */ + public function test_gate_inspection_approval_in_updates_vehicle_to_inside_site_and_records_history(): void + { + $vehicle = Vehicle::create([ + 'code' => 'LV-GATE-IN', + 'category' => 'light_vehicle', + 'brand_type' => 'Hilux Double Cabin', + 'site_status' => 'outside_site', + 'location' => 'Luar Site - Kota Bangko', + 'status' => 'Operation', + 'current_km' => 20000, + ]); + + $driver = Employee::firstOrCreate( + ['nik' => 'KMH-DVR-001'], + ['name' => 'Ahmad Driver', 'is_operator' => true, 'is_active' => true] + ); + + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-IN-001', + 'vehicle_id' => $vehicle->id, + 'driver_id' => $driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'in', + 'previous_km' => 20000, + 'current_km' => 20050, + 'distance' => 50, + 'purpose' => 'Kembali dari mobilisasi Bangko', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'pending', + ]); + + // Satpam menyetujui aktivitas gerbang + $response = $this->actingAs($this->gateOfficer)->post("/pg/gate-inspection/{$activity->id}/approve", [ + 'security_guard_id' => $this->guard->id, + ]); + + $response->assertRedirect(); + + // Verifikasi posisi kendaraan berubah otomatis menjadi inside_site + $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->assertStringContainsString('TRX-IN-001', $vehicle->location_note); + + // Verifikasi riwayat tersimpan otomatis bersumber gate_crossing + $this->assertDatabaseHas('vehicle_location_histories', [ + 'vehicle_id' => $vehicle->id, + 'site_status' => 'inside_site', + 'location' => $this->gate->name, + 'source' => 'gate_crossing', + 'vehicle_activity_id' => $activity->id, + 'user_name' => $this->guard->name, + ]); + } + + /** + * Integrasi otomatis: Saat aktivitas gerbang arah Keluar (OUT) disetujui Satpam, + * kendaraan otomatis berubah status menjadi outside_site dengan lokasi Luar Site - [Tujuan]. + */ + public function test_gate_inspection_approval_out_updates_vehicle_to_outside_site_and_records_history(): void + { + $vehicle = Vehicle::create([ + 'code' => 'LV-GATE-OUT', + 'category' => 'light_vehicle', + 'brand_type' => 'Fortuner 4x4', + 'site_status' => 'inside_site', + 'location' => 'Workshop GA', + 'status' => 'Operation', + 'current_km' => 30000, + ]); + + $driver = Employee::firstOrCreate( + ['nik' => 'KMH-DVR-002'], + ['name' => 'Bambang Driver', 'is_operator' => true, 'is_active' => true] + ); + + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-OUT-002', + 'vehicle_id' => $vehicle->id, + 'driver_id' => $driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 30000, + 'current_km' => 30010, + 'distance' => 10, + 'purpose' => 'Antar Dokumen ke Kantor Jambi', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'pending', + ]); + + // Satpam menyetujui aktivitas gerbang + $response = $this->actingAs($this->gateOfficer)->post("/pg/gate-inspection/{$activity->id}/approve", [ + 'security_guard_id' => $this->guard->id, + ]); + + $response->assertRedirect(); + + // Verifikasi posisi kendaraan berubah otomatis menjadi outside_site + $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); + + // Verifikasi riwayat tersimpan otomatis + $this->assertDatabaseHas('vehicle_location_histories', [ + 'vehicle_id' => $vehicle->id, + 'site_status' => 'outside_site', + 'location' => 'Luar Site - Antar Dokumen ke Kantor Jambi', + 'source' => 'gate_crossing', + 'vehicle_activity_id' => $activity->id, + ]); + } + + /** + * Admin QMA dapat mengekspor data posisi ke Excel (.xlsx). + */ + public function test_export_excel_returns_valid_xlsx_stream(): void + { + Vehicle::create([ + 'code' => 'LV-EXP-01', + 'category' => 'light_vehicle', + 'brand_type' => 'Hilux', + 'site_status' => 'inside_site', + 'location' => 'Main Dam', + 'status' => 'Operation', + ]); + + $response = $this->actingAs($this->qmaAdmin)->get(route('qma.unit_management.export_excel')); + + $response->assertStatus(200); + $this->assertTrue(str_contains( + $response->headers->get('content-type') ?? '', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + )); + } + + /** + * Admin QMA dapat mengekspor data posisi ke format PDF. + */ + public function test_export_pdf_returns_valid_pdf_stream(): void + { + Vehicle::create([ + 'code' => 'LV-EXP-02', + 'category' => 'light_vehicle', + 'brand_type' => 'Strada Triton', + 'site_status' => 'outside_site', + 'location' => 'Kota Bangko', + 'status' => 'Operation', + ]); + + $response = $this->actingAs($this->qmaAdmin)->get(route('qma.unit_management.export_pdf')); + + $response->assertStatus(200); + $this->assertTrue(str_contains( + $response->headers->get('content-type') ?? '', + 'application/pdf' + )); + } +}