feat(qma): implement unit position tracking, gate auto-sync, history log, and exports

This commit is contained in:
Ray1111-aa
2026-10-20 20:15:24 +07:00
parent e45f6ce581
commit 1590c5f1c6
11 changed files with 2133 additions and 3 deletions
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Models\Gate; use App\Models\Gate;
use App\Models\SecurityGuard; use App\Models\SecurityGuard;
use App\Models\VehicleActivity; use App\Models\VehicleActivity;
use App\Models\VehicleLocationHistory;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; 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') { if ($activity->validation_status !== 'pending') {
return back()->with('error', 'Aktivitas ini sudah pernah divalidasi sebelumnya.'); 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 // 1. Update status aktivitas menjadi approved
$activity->update([ $activity->update([
'validation_status' => 'approved', 'validation_status' => 'approved',
@@ -129,9 +133,42 @@ class GateInspectionController extends Controller
'validated_at' => Carbon::now(), '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([ $activity->vehicle->update([
'current_km' => $activity->current_km, '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(),
]); ]);
}); });
@@ -0,0 +1,413 @@
<?php
namespace App\Http\Controllers\Qma;
use App\Http\Controllers\Controller;
use App\Models\Gate;
use App\Models\Vehicle;
use App\Models\VehicleLocationHistory;
use App\Services\QmaTablePdfExporter;
use App\Services\SimpleXlsxExporter;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class UnitManagementController extends Controller
{
/**
* Preset lokasi bawaan di dalam dan di luar site proyek Kerinci Hydropower.
*/
public const PRESET_INSIDE_LOCATIONS = [
'Main Dam',
'Adit 1',
'Adit 2',
'Adit 3',
'Powerhouse',
'Regulating Weir',
'Vertical Shaft',
'Workshop GA',
'Workshop Mekanik',
'Batching Plant',
'Crusher Plant',
'Dermaga Jakon',
'Bendungan Bedeng 6',
'CCR DAM',
'Crest DAM',
];
public const PRESET_OUTSIDE_LOCATIONS = [
'Kota Bangko',
'Kota Jambi',
'Mess Kumun',
'Mess Kerinci',
'Bengkel Rekanan Bangko',
'Bengkel Resmi Padang',
'Perjalanan Dinas Luar Kota',
'Bandara Depati Parbo',
'Pelabuhan Teluk Bayur',
];
/**
* Dapatkan daftar saran lokasi gabungan (preset + gerbang aktif + lokasi riwayat tersimpan).
*/
public static function getAllLocationSuggestions(): array
{
$gateNames = Gate::where('is_active', true)->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',
]);
}
}
+5
View File
@@ -183,6 +183,11 @@ class User extends Authenticatable
return null; return null;
} }
public function locationHistories(): HasMany
{
return $this->hasMany(VehicleLocationHistory::class);
}
public function isEmployee(): bool public function isEmployee(): bool
{ {
if ($this->isSuperAdmin()) { if ($this->isSuperAdmin()) {
+60
View File
@@ -32,6 +32,10 @@ class Vehicle extends Model
'model_number', 'model_number',
'production_year', 'production_year',
'location', 'location',
'site_status',
'location_updated_at',
'location_updated_by',
'location_note',
'fuel_consumption', 'fuel_consumption',
'silo_document', 'silo_document',
'stnk_document', 'stnk_document',
@@ -44,12 +48,29 @@ class Vehicle extends Model
'fuel_consumption' => 'decimal:2', 'fuel_consumption' => 'decimal:2',
'production_year' => 'integer', 'production_year' => 'integer',
'parent_id' => 'integer', 'parent_id' => 'integer',
'location_updated_at' => 'datetime',
]; ];
protected $appends = [ protected $appends = [
'photo_url', '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 public function isLightVehicle(): bool
{ {
return $this->category === 'light_vehicle'; return $this->category === 'light_vehicle';
@@ -103,6 +124,35 @@ class Vehicle extends Model
return $query->where('category', 'unit_support')->whereNotNull('parent_id'); 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 public function parent(): BelongsTo
{ {
return $this->belongsTo(Vehicle::class, 'parent_id'); return $this->belongsTo(Vehicle::class, 'parent_id');
@@ -167,6 +217,16 @@ class Vehicle extends Model
return $this->hasOne(VehicleActivity::class)->latestOfMany('recorded_at'); 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: * Tentukan arah gerbang berikutnya yang sah:
* - 'ANY' jika belum pernah ada riwayat (kendaraan baru) * - 'ANY' jika belum pernah ada riwayat (kendaraan baru)
+6
View File
@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class VehicleActivity extends Model class VehicleActivity extends Model
{ {
@@ -69,6 +70,11 @@ class VehicleActivity extends Model
return $this->belongsTo(User::class, 'corrected_by_user_id'); 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 public function isPending(): bool
{ {
return $this->validation_status === 'pending'; return $this->validation_status === 'pending';
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class VehicleLocationHistory extends Model
{
use HasFactory;
protected $fillable = [
'vehicle_id',
'site_status',
'location',
'note',
'source',
'vehicle_activity_id',
'user_id',
'user_name',
'recorded_at',
];
protected $casts = [
'recorded_at' => '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';
}
}
@@ -0,0 +1,56 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// 1. Tambahkan kolom status posisi di dalam/luar site pada tabel vehicles
Schema::table('vehicles', function (Blueprint $table) {
$table->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',
]);
});
}
};
+18
View File
@@ -306,6 +306,14 @@
</div> </div>
@endcan @endcan
@can('qma.vehicles.view')
<a href="{{ route('qma.unit_management.index') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('qma.unit_management.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-map-location-dot text-base w-5 text-center"></i>
<span>Manajemen Unit</span>
</a>
@endcan
@if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view']))
@php @php
$isActivityRoute = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); $isActivityRoute = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show');
@@ -620,6 +628,14 @@
</div> </div>
@endcan @endcan
@can('qma.vehicles.view')
<a href="{{ route('qma.unit_management.index') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('qma.unit_management.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-map-location-dot text-base w-5 text-center"></i>
<span>Manajemen Unit</span>
</a>
@endcan
@if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view'])) @if(auth()->user()->canAny(['qma.logs.view', 'qma.p2h.view']))
@php @php
$isActivityRouteMob = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show'); $isActivityRouteMob = request()->routeIs('qma.activity.log') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show');
@@ -792,6 +808,8 @@
Unit Support Unit Support
@elseif(request()->routeIs('qma.vehicles.*')) @elseif(request()->routeIs('qma.vehicles.*'))
Data Kendaraan Data Kendaraan
@elseif(request()->routeIs('qma.unit_management.*'))
Manajemen Unit
@elseif(request()->routeIs('qma.activity.log')) @elseif(request()->routeIs('qma.activity.log'))
Timesheet LV Timesheet LV
@elseif(request()->routeIs('qma.p2h.summary')) @elseif(request()->routeIs('qma.p2h.summary'))
File diff suppressed because it is too large Load Diff
+8
View File
@@ -17,6 +17,7 @@ use App\Http\Controllers\Public\VehicleActivityFormController;
use App\Http\Controllers\Qma\ActivityLogController; use App\Http\Controllers\Qma\ActivityLogController;
use App\Http\Controllers\Qma\P2hInspectionController; use App\Http\Controllers\Qma\P2hInspectionController;
use App\Http\Controllers\Qma\P2hTemplateController; use App\Http\Controllers\Qma\P2hTemplateController;
use App\Http\Controllers\Qma\UnitManagementController;
use App\Http\Controllers\Qma\VehicleController; use App\Http\Controllers\Qma\VehicleController;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route; 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-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'); 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 // 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', [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'); Route::get('/p2h-records/export-excel', [P2hInspectionController::class, 'exportExcel'])->name('p2h.export_excel')->middleware('permission:qma.p2h.view|qma.vehicles.view');
+419
View File
@@ -0,0 +1,419 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\Gate;
use App\Models\SecurityGuard;
use App\Models\User;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use App\Models\VehicleLocationHistory;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class QmaUnitManagementTest extends TestCase
{
use RefreshDatabase;
protected User $qmaAdmin;
protected User $gateOfficer;
protected Gate $gate;
protected SecurityGuard $guard;
protected function setUp(): void
{
parent::setUp();
// Siapkan permission dan role untuk testing
Permission::firstOrCreate(['name' => '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' => '[email protected]',
'role' => 'qma_admin',
'password' => bcrypt('password'),
]
);
$this->qmaAdmin->assignRole('qma_admin');
$this->gateOfficer = User::firstOrCreate(
['username' => 'satpam_test'],
[
'name' => 'Petugas Gerbang Test',
'email' => '[email protected]',
'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'
));
}
}