feat(qma): implement unit support timesheet input, vehicle meter & location sync, and exports

This commit is contained in:
Ray1111-aa
2026-10-20 20:46:48 +07:00
parent fb67d7c63d
commit 0cd02a17cd
9 changed files with 2154 additions and 2 deletions
@@ -0,0 +1,502 @@
<?php
namespace App\Http\Controllers\Qma;
use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\UnitSupportTimesheet;
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\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class SupportTimesheetController extends Controller
{
public const PRESET_ACTIVITIES = [
'Galian Material',
'Timbunan / Compacting',
'Loading Material',
'Hauling Material',
'Lifting / Erection',
'Drilling / Pengeboran',
'Pembersihan / Land Clearing',
'Perbaikan Jalan Proyek',
'Mobilisasi Alat / Material',
'Standby / Siaga',
'Lainnya',
];
public const SHIFTS = [
'Shift 1 (Siang)',
'Shift 2 (Malam)',
'Non-Shift',
];
/**
* Helper query builder untuk memfilter timesheet unit support.
*/
private function getFilteredQuery(Request $request): Builder
{
$query = UnitSupportTimesheet::with(['vehicle', 'operator', 'createdByUser'])
->orderByDesc('date')
->orderByDesc('id');
// Filter Rentang Tanggal
if ($request->filled('start_date') && $request->filled('end_date')) {
$query->whereBetween('date', [$request->input('start_date'), $request->input('end_date')]);
} elseif ($request->filled('start_date')) {
$query->where('date', '>=', $request->input('start_date'));
} elseif ($request->filled('end_date')) {
$query->where('date', '<=', $request->input('end_date'));
}
// Filter Unit
if ($request->filled('vehicle_id')) {
$query->where('vehicle_id', $request->input('vehicle_id'));
}
// Filter Operator
if ($request->filled('operator_id')) {
$query->where('operator_id', $request->input('operator_id'));
}
// Filter Shift
if ($request->filled('shift')) {
$query->where('shift', $request->input('shift'));
}
// Filter Status Operasi
if ($request->filled('status')) {
$query->where('status', $request->input('status'));
}
// Filter Pencarian Kata Kunci
if ($request->filled('search')) {
$search = trim($request->input('search'));
$query->where(function (Builder $q) use ($search) {
$q->where('timesheet_no', 'like', "%{$search}%")
->orWhere('location', 'like', "%{$search}%")
->orWhere('activity_type', 'like', "%{$search}%")
->orWhere('task_description', 'like', "%{$search}%")
->orWhere('notes', 'like', "%{$search}%")
->orWhereHas('vehicle', function (Builder $vq) use ($search) {
$vq->where('code', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('license_plate', 'like', "%{$search}%")
->orWhere('serial_number', 'like', "%{$search}%");
})
->orWhereHas('operator', function (Builder $oq) use ($search) {
$oq->where('name', 'like', "%{$search}%")
->orWhere('nik', 'like', "%{$search}%");
});
});
}
return $query;
}
/**
* Tampilkan halaman utama Timesheet Unit Support.
*/
public function index(Request $request): View
{
$today = Carbon::today()->toDateString();
$startDate = $request->input('start_date', $today);
$endDate = $request->input('end_date', $today);
// Jika user belum mengisi filter tanggal dan ingin semua, bisa dikosongkan.
// Tapi default awal memuat hari ini agar cepat dan relevan.
$query = $this->getFilteredQuery($request);
$timesheets = $query->paginate(15)->withQueryString();
// KPI Ringkasan Data Terfilter
$statsQuery = clone $this->getFilteredQuery($request);
$totalEntries = (clone $statsQuery)->count();
$totalOperatingHours = (clone $statsQuery)->sum('operating_hours');
$totalFuelLiters = (clone $statsQuery)->sum('fuel_liters');
$activeUnitsCount = (clone $statsQuery)->distinct('vehicle_id')->count('vehicle_id');
$breakdownCount = (clone $statsQuery)->where('status', 'Breakdown')->count();
// Data Master untuk Form & Filter
$unitSupports = Vehicle::unitSupports()
->where(function (Builder $q) {
$q->whereNotNull('parent_id')
->orWhereDoesntHave('units');
})
->orderBy('code')
->get();
$operators = Employee::where('is_active', true)
->orderBy('name')
->get(['id', 'nik', 'name', 'position', 'is_operator']);
$shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions();
return view('qma.support_timesheet', compact(
'timesheets',
'startDate',
'endDate',
'totalEntries',
'totalOperatingHours',
'totalFuelLiters',
'activeUnitsCount',
'breakdownCount',
'unitSupports',
'operators',
'shifts',
'activityTypes',
'locationSuggestions'
));
}
/**
* Simpan entri timesheet baru yang diinput oleh Admin QMA.
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'vehicle_id' => ['required', 'exists:vehicles,id'],
'operator_id' => ['required', 'exists:employees,id'],
'date' => ['required', 'date'],
'shift' => ['required', 'string', 'max:30'],
'meter_type' => ['required', 'in:HM,KM'],
'start_time' => ['nullable', 'date_format:H:i'],
'end_time' => ['nullable', 'date_format:H:i'],
'start_meter' => ['required', 'numeric', 'min:0'],
'end_meter' => ['required', 'numeric', 'gte:start_meter'],
'standby_hours' => ['nullable', 'numeric', 'min:0'],
'breakdown_hours' => ['nullable', 'numeric', 'min:0'],
'location' => ['required', 'string', 'max:255'],
'activity_type' => ['required', 'string', 'max:100'],
'task_description' => ['nullable', 'string', 'max:1000'],
'fuel_liters' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', 'in:Operation,Standby,Breakdown,Maintenance'],
'notes' => ['nullable', 'string', 'max:1000'],
], [
'vehicle_id.required' => 'Pilih unit support yang beroperasi.',
'operator_id.required' => 'Pilih pengemudi / operator unit.',
'date.required' => 'Tanggal operasional wajib diisi.',
'end_meter.gte' => 'Angka meter akhir (End Meter) tidak boleh lebih kecil dari meter awal.',
'location.required' => 'Lokasi kerja wajib ditentukan.',
'activity_type.required' => 'Jenis aktivitas / pekerjaan wajib dipilih.',
]);
$vehicle = Vehicle::findOrFail($validated['vehicle_id']);
$operator = Employee::findOrFail($validated['operator_id']);
$startMeter = (float) $validated['start_meter'];
$endMeter = (float) $validated['end_meter'];
$operatingHours = max(0, $endMeter - $startMeter);
$timesheetNo = UnitSupportTimesheet::generateTimesheetNo(Carbon::parse($validated['date']));
$updaterName = auth()->user()?->name ?? 'Admin QMA';
DB::transaction(function () use (
$validated,
$vehicle,
$operator,
$timesheetNo,
$operatingHours,
$endMeter,
$updaterName
) {
// 1. Simpan Data Timesheet Unit Support
$timesheet = UnitSupportTimesheet::create([
'timesheet_no' => $timesheetNo,
'vehicle_id' => $vehicle->id,
'operator_id' => $operator->id,
'date' => $validated['date'],
'shift' => $validated['shift'],
'meter_type' => $validated['meter_type'],
'start_time' => $validated['start_time'] ?? null,
'end_time' => $validated['end_time'] ?? null,
'start_meter' => $validated['start_meter'],
'end_meter' => $validated['end_meter'],
'operating_hours' => $operatingHours,
'standby_hours' => $validated['standby_hours'] ?? 0,
'breakdown_hours' => $validated['breakdown_hours'] ?? 0,
'location' => trim($validated['location']),
'activity_type' => trim($validated['activity_type']),
'task_description' => $validated['task_description'] ?? null,
'fuel_liters' => $validated['fuel_liters'] ?? null,
'status' => $validated['status'],
'notes' => $validated['notes'] ?? null,
'created_by_user_id' => auth()->id(),
]);
// 2. Sinkronisasi Master Kendaraan (Odometer & Posisi di Manajemen Unit)
$updateData = [
'status' => $validated['status'],
'site_status' => 'inside_site',
'location' => trim($validated['location']),
'location_updated_at' => Carbon::now(),
'location_updated_by' => $updaterName,
'location_note' => "Timesheet {$timesheetNo} ({$validated['activity_type']}) - Operator: {$operator->name}",
];
if ($endMeter > (float) $vehicle->current_km) {
$updateData['current_km'] = $endMeter;
}
$vehicle->update($updateData);
// 3. Catat Riwayat Pergerakan Posisi Unit (Audit Trail)
VehicleLocationHistory::create([
'vehicle_id' => $vehicle->id,
'site_status' => 'inside_site',
'location' => trim($validated['location']),
'note' => "Timesheet {$timesheetNo} ({$validated['activity_type']}) - Operator: {$operator->name}",
'source' => 'manual',
'user_id' => auth()->id(),
'user_name' => $updaterName,
'recorded_at' => Carbon::now(),
]);
});
return back()->with('success', "Timesheet {$timesheetNo} untuk unit {$vehicle->code} berhasil disimpan.");
}
/**
* Perbarui entri timesheet unit support.
*/
public function update(Request $request, int $id): RedirectResponse
{
$timesheet = UnitSupportTimesheet::findOrFail($id);
$validated = $request->validate([
'vehicle_id' => ['required', 'exists:vehicles,id'],
'operator_id' => ['required', 'exists:employees,id'],
'date' => ['required', 'date'],
'shift' => ['required', 'string', 'max:30'],
'meter_type' => ['required', 'in:HM,KM'],
'start_time' => ['nullable', 'date_format:H:i'],
'end_time' => ['nullable', 'date_format:H:i'],
'start_meter' => ['required', 'numeric', 'min:0'],
'end_meter' => ['required', 'numeric', 'gte:start_meter'],
'standby_hours' => ['nullable', 'numeric', 'min:0'],
'breakdown_hours' => ['nullable', 'numeric', 'min:0'],
'location' => ['required', 'string', 'max:255'],
'activity_type' => ['required', 'string', 'max:100'],
'task_description' => ['nullable', 'string', 'max:1000'],
'fuel_liters' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', 'in:Operation,Standby,Breakdown,Maintenance'],
'notes' => ['nullable', 'string', 'max:1000'],
]);
$startMeter = (float) $validated['start_meter'];
$endMeter = (float) $validated['end_meter'];
$operatingHours = max(0, $endMeter - $startMeter);
$timesheet->update([
'vehicle_id' => $validated['vehicle_id'],
'operator_id' => $validated['operator_id'],
'date' => $validated['date'],
'shift' => $validated['shift'],
'meter_type' => $validated['meter_type'],
'start_time' => $validated['start_time'] ?? null,
'end_time' => $validated['end_time'] ?? null,
'start_meter' => $validated['start_meter'],
'end_meter' => $validated['end_meter'],
'operating_hours' => $operatingHours,
'standby_hours' => $validated['standby_hours'] ?? 0,
'breakdown_hours' => $validated['breakdown_hours'] ?? 0,
'location' => trim($validated['location']),
'activity_type' => trim($validated['activity_type']),
'task_description' => $validated['task_description'] ?? null,
'fuel_liters' => $validated['fuel_liters'] ?? null,
'status' => $validated['status'],
'notes' => $validated['notes'] ?? null,
]);
return back()->with('success', "Timesheet {$timesheet->timesheet_no} berhasil diperbarui.");
}
/**
* Hapus entri timesheet unit support.
*/
public function destroy(int $id): RedirectResponse
{
$timesheet = UnitSupportTimesheet::findOrFail($id);
$no = $timesheet->timesheet_no;
$timesheet->delete();
return back()->with('success', "Timesheet {$no} berhasil dihapus.");
}
/**
* Ekspor data timesheet unit support ke format Excel (.xlsx).
*/
public function exportExcel(Request $request): Response
{
$timesheets = $this->getFilteredQuery($request)->get();
$metaLines = [
'Laporan Timesheet Operasional Unit Support (Alat Berat)',
'Periode: ' . ($request->filled('start_date') ? Carbon::parse($request->input('start_date'))->format('d/m/Y') : 'Semua') . ' s/d ' . ($request->filled('end_date') ? Carbon::parse($request->input('end_date'))->format('d/m/Y') : 'Semua'),
'Waktu Ekspor: ' . Carbon::now()->translatedFormat('d F Y, H:i') . ' WIB',
'Total Record: ' . $timesheets->count() . ' Entri Timesheet',
];
$headers = [
'NO' => 6,
'NO TIMESHEET' => 20,
'TANGGAL' => 14,
'SHIFT' => 18,
'KODE UNIT' => 14,
'MEREK / MODEL' => 26,
'OPERATOR' => 24,
'NIK' => 16,
'SATUAN' => 10,
'START' => 14,
'END' => 14,
'JAM OPERASI' => 14,
'STANDBY' => 12,
'BREAKDOWN' => 12,
'LOKASI KERJA' => 22,
'AKTIVITAS' => 24,
'SOLAR (L)' => 12,
'STATUS' => 14,
'CATATAN' => 30,
];
$rows = [];
foreach ($timesheets as $idx => $ts) {
$rows[] = [
$idx + 1,
$ts->timesheet_no,
$ts->date ? $ts->date->format('d/m/Y') : '-',
$ts->shift,
$ts->vehicle?->code ?: '-',
$ts->vehicle?->brand_type ?: '-',
$ts->operator?->name ?: '-',
$ts->operator?->nik ?: '-',
$ts->meter_type,
number_format($ts->start_meter, 2, ',', '.'),
number_format($ts->end_meter, 2, ',', '.'),
number_format($ts->operating_hours, 2, ',', '.'),
number_format($ts->standby_hours, 2, ',', '.'),
number_format($ts->breakdown_hours, 2, ',', '.'),
$ts->location,
$ts->activity_type,
$ts->fuel_liters ? number_format($ts->fuel_liters, 2, ',', '.') : '-',
$ts->status,
$ts->notes ?: ($ts->task_description ?: '-'),
];
}
$alignments = [
'NO' => 'center',
'NO TIMESHEET' => 'center',
'TANGGAL' => 'center',
'SHIFT' => 'center',
'KODE UNIT' => 'center',
'NIK' => 'center',
'SATUAN' => 'center',
'START' => 'right',
'END' => 'right',
'JAM OPERASI' => 'right',
'STANDBY' => 'right',
'BREAKDOWN' => 'right',
'SOLAR (L)' => 'right',
'STATUS' => 'center',
];
$xlsxContent = SimpleXlsxExporter::create(
'LAPORAN TIMESHEET OPERASIONAL UNIT SUPPORT',
$metaLines,
$headers,
$rows,
$alignments
);
$fileName = 'Timesheet_Unit_Support_' . 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 timesheet unit support ke format PDF.
*/
public function exportPdf(Request $request): Response
{
$timesheets = $this->getFilteredQuery($request)->get();
$metaLeft = [
'Sub-Sistem' => 'Quality Management Asset (QMA)',
'Modul' => 'Timesheet Operasional Unit Support',
'Periode' => ($request->filled('start_date') ? Carbon::parse($request->input('start_date'))->format('d/m/Y') : 'Semua') . ' s/d ' . ($request->filled('end_date') ? Carbon::parse($request->input('end_date'))->format('d/m/Y') : 'Semua'),
];
$metaRight = [
'Waktu Cetak' => Carbon::now()->translatedFormat('d F Y, H:i') . ' WIB',
'Dicetak Oleh' => auth()->user()?->name ?? 'Admin QMA',
'Total Record' => $timesheets->count() . ' Entri Timesheet',
];
$columns = [
['title' => 'NO', 'width' => 10, 'align' => 'C', 'bold' => true],
['title' => 'TANGGAL', 'width' => 20, 'align' => 'C'],
['title' => 'KODE', 'width' => 18, 'align' => 'C', 'bold' => true],
['title' => 'TIPE ALAT', 'width' => 38, 'align' => 'L', 'max_char' => 25],
['title' => 'OPERATOR', 'width' => 35, 'align' => 'L', 'max_char' => 22],
['title' => 'SHIFT', 'width' => 25, 'align' => 'C'],
['title' => 'START', 'width' => 18, 'align' => 'R'],
['title' => 'END', 'width' => 18, 'align' => 'R'],
['title' => 'JAM (HM)', 'width' => 18, 'align' => 'R', 'bold' => true],
['title' => 'LOKASI KERJA', 'width' => 40, 'align' => 'L', 'max_char' => 26],
['title' => 'STATUS', 'width' => 25, 'align' => 'C', 'is_status' => true],
];
$rows = [];
foreach ($timesheets as $idx => $ts) {
$rows[] = [
$idx + 1,
$ts->date ? $ts->date->format('d/m/Y') : '-',
$ts->vehicle?->code ?: '-',
$ts->vehicle?->brand_type ?: '-',
$ts->operator?->name ?: '-',
$ts->shift,
number_format($ts->start_meter, 1, ',', '.'),
number_format($ts->end_meter, 1, ',', '.'),
number_format($ts->operating_hours, 1, ',', '.') . ' ' . $ts->meter_type,
$ts->location,
$ts->status,
];
}
$subtitle = 'Monitoring Jam Operasi Alat Berat & Unit Support Proyek Kerinci Hydropower';
$pdfBinary = QmaTablePdfExporter::generate(
'Laporan Timesheet Unit Support',
$subtitle,
'SISTEM QMA RKM-KMH',
$metaLeft,
$metaRight,
$columns,
$rows
);
$fileName = 'Laporan_Timesheet_Unit_Support_' . 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
@@ -82,6 +82,11 @@ class Employee extends Model
return $this->hasMany(P2hRecord::class, 'employee_id')->orderByDesc('inspected_at'); return $this->hasMany(P2hRecord::class, 'employee_id')->orderByDesc('inspected_at');
} }
public function supportTimesheets(): HasMany
{
return $this->hasMany(UnitSupportTimesheet::class, 'operator_id')->orderByDesc('date');
}
public function user(): BelongsTo public function user(): BelongsTo
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class UnitSupportTimesheet extends Model
{
use HasFactory;
protected $fillable = [
'timesheet_no',
'vehicle_id',
'operator_id',
'date',
'shift',
'meter_type',
'start_time',
'end_time',
'start_meter',
'end_meter',
'operating_hours',
'standby_hours',
'breakdown_hours',
'location',
'activity_type',
'task_description',
'fuel_liters',
'status',
'notes',
'created_by_user_id',
];
protected $casts = [
'date' => 'date',
'start_meter' => 'decimal:2',
'end_meter' => 'decimal:2',
'operating_hours' => 'decimal:2',
'standby_hours' => 'decimal:2',
'breakdown_hours' => 'decimal:2',
'fuel_liters' => 'decimal:2',
];
public function vehicle(): BelongsTo
{
return $this->belongsTo(Vehicle::class);
}
public function operator(): BelongsTo
{
return $this->belongsTo(Employee::class, 'operator_id');
}
public function createdByUser(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by_user_id');
}
/**
* Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001).
*/
public static function generateTimesheetNo(?Carbon $date = null): string
{
$d = $date ?: Carbon::today();
$dateStr = $d->format('Ymd');
$prefix = "TS-US-{$dateStr}-";
$last = self::where('timesheet_no', 'like', "{$prefix}%")
->orderByDesc('id')
->first();
$seq = 1;
if ($last && preg_match('/-(\d+)$/', $last->timesheet_no, $matches)) {
$seq = ((int) $matches[1]) + 1;
}
return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
}
}
+10
View File
@@ -227,6 +227,16 @@ class Vehicle extends Model
return $this->hasOne(VehicleLocationHistory::class)->latestOfMany('recorded_at'); return $this->hasOne(VehicleLocationHistory::class)->latestOfMany('recorded_at');
} }
public function supportTimesheets(): HasMany
{
return $this->hasMany(UnitSupportTimesheet::class)->orderByDesc('date')->orderByDesc('id');
}
public function latestSupportTimesheet(): HasOne
{
return $this->hasOne(UnitSupportTimesheet::class)->latestOfMany('date');
}
/** /**
* 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)
@@ -0,0 +1,52 @@
<?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
{
Schema::create('unit_support_timesheets', function (Blueprint $table) {
$table->id();
$table->string('timesheet_no', 60)->unique();
$table->foreignId('vehicle_id')->constrained('vehicles')->restrictOnDelete();
$table->foreignId('operator_id')->constrained('employees')->restrictOnDelete();
$table->date('date');
$table->string('shift', 30)->default('Shift 1 (Siang)'); // Shift 1 (Siang), Shift 2 (Malam), Non-Shift
$table->string('meter_type', 10)->default('HM'); // 'HM' (Hour Meter) atau 'KM' (Odometer)
$table->time('start_time')->nullable();
$table->time('end_time')->nullable();
$table->decimal('start_meter', 12, 2);
$table->decimal('end_meter', 12, 2);
$table->decimal('operating_hours', 10, 2); // end_meter - start_meter
$table->decimal('standby_hours', 10, 2)->default(0);
$table->decimal('breakdown_hours', 10, 2)->default(0);
$table->string('location', 255);
$table->string('activity_type', 100); // Galian, Timbunan, Loading, Hauling, Lifting, dll.
$table->text('task_description')->nullable();
$table->decimal('fuel_liters', 10, 2)->nullable();
$table->string('status', 30)->default('Operation'); // Operation, Standby, Breakdown, Maintenance
$table->text('notes')->nullable();
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
// Index performa query & pelaporan
$table->index(['date', 'shift']);
$table->index(['vehicle_id', 'date']);
$table->index(['operator_id', 'date']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('unit_support_timesheets');
}
};
+14 -2
View File
@@ -316,7 +316,7 @@
@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.support_timesheet.*') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show');
@endphp @endphp
<!-- Dropdown Menu: Log Aktifitas --> <!-- Dropdown Menu: Log Aktifitas -->
<div> <div>
@@ -337,6 +337,11 @@
class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.activity.log') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}"> class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.activity.log') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}">
<span>Timesheet LV</span> <span>Timesheet LV</span>
</a> </a>
<a href="{{ route('qma.support_timesheet.index') }}"
class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.support_timesheet.*') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}">
<span>Timesheet Unit Support</span>
</a>
@endcan @endcan
@can('qma.p2h.view') @can('qma.p2h.view')
@@ -638,7 +643,7 @@
@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.support_timesheet.*') || request()->routeIs('qma.p2h.index') || request()->routeIs('qma.p2h.show');
@endphp @endphp
<div> <div>
<button type="button" <button type="button"
@@ -657,6 +662,11 @@
class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.activity.log') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}"> class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.activity.log') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}">
<span>Timesheet LV</span> <span>Timesheet LV</span>
</a> </a>
<a href="{{ route('qma.support_timesheet.index') }}"
class="block px-3.5 py-2 text-xs rounded-xl transition {{ request()->routeIs('qma.support_timesheet.*') ? 'bg-[#1b5e20] text-white font-bold shadow-sm' : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100 font-medium' }}">
<span>Timesheet Unit Support</span>
</a>
@endcan @endcan
@can('qma.p2h.view') @can('qma.p2h.view')
@@ -812,6 +822,8 @@
Manajemen Unit Manajemen Unit
@elseif(request()->routeIs('qma.activity.log')) @elseif(request()->routeIs('qma.activity.log'))
Timesheet LV Timesheet LV
@elseif(request()->routeIs('qma.support_timesheet.*'))
Timesheet Unit Support
@elseif(request()->routeIs('qma.p2h.summary')) @elseif(request()->routeIs('qma.p2h.summary'))
Summary P2H Unit Support Summary P2H Unit Support
@elseif(request()->routeIs('qma.p2h.templates*')) @elseif(request()->routeIs('qma.p2h.templates*'))
File diff suppressed because it is too large Load Diff
+9
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\SupportTimesheetController;
use App\Http\Controllers\Qma\UnitManagementController; 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;
@@ -92,6 +93,14 @@ 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');
// Timesheet Unit Support (Pencatatan Jam Operasi Alat Berat / Support oleh QMA)
Route::get('/support-timesheet', [SupportTimesheetController::class, 'index'])->name('support_timesheet.index')->middleware('permission:qma.logs.view');
Route::post('/support-timesheet', [SupportTimesheetController::class, 'store'])->name('support_timesheet.store')->middleware('permission:qma.logs.edit_odometer|qma.vehicles.create');
Route::put('/support-timesheet/{id}', [SupportTimesheetController::class, 'update'])->name('support_timesheet.update')->middleware('permission:qma.logs.edit_odometer|qma.vehicles.edit');
Route::delete('/support-timesheet/{id}', [SupportTimesheetController::class, 'destroy'])->name('support_timesheet.destroy')->middleware('permission:qma.logs.edit_odometer|qma.vehicles.delete');
Route::get('/support-timesheet/export-excel', [SupportTimesheetController::class, 'exportExcel'])->name('support_timesheet.export_excel')->middleware('permission:qma.logs.view');
Route::get('/support-timesheet/export-pdf', [SupportTimesheetController::class, 'exportPdf'])->name('support_timesheet.export_pdf')->middleware('permission:qma.logs.view');
// Manajemen Unit (Tracking & Monitoring Posisi LV & Unit Support) // 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::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::post('/unit-management/{id}/location', [UnitManagementController::class, 'updateLocation'])->name('unit_management.update_location')->middleware('permission:qma.vehicles.edit');
+357
View File
@@ -0,0 +1,357 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\UnitSupportTimesheet;
use App\Models\User;
use App\Models\Vehicle;
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 QmaSupportTimesheetTest extends TestCase
{
use RefreshDatabase;
protected User $qmaAdmin;
protected Vehicle $supportUnit;
protected Employee $operator;
protected function setUp(): void
{
parent::setUp();
Permission::firstOrCreate(['name' => 'qma.logs.view', 'guard_name' => 'web']);
Permission::firstOrCreate(['name' => 'qma.logs.edit_odometer', 'guard_name' => 'web']);
Permission::firstOrCreate(['name' => 'qma.vehicles.view', 'guard_name' => 'web']);
Permission::firstOrCreate(['name' => 'qma.vehicles.edit', 'guard_name' => 'web']);
$role = Role::firstOrCreate(['name' => 'qma_admin', 'guard_name' => 'web']);
$role->givePermissionTo(['qma.logs.view', 'qma.logs.edit_odometer', 'qma.vehicles.view', 'qma.vehicles.edit']);
$this->qmaAdmin = User::firstOrCreate(
['username' => 'qma_admin_tester'],
[
'name' => 'Admin QMA Tester',
'email' => '[email protected]',
'role' => 'qma_admin',
'password' => bcrypt('password'),
]
);
$this->qmaAdmin->assignRole('qma_admin');
$this->supportUnit = Vehicle::create([
'code' => 'EX01',
'category' => 'unit_support',
'brand_type' => 'Komatsu PC200-8 Excavator',
'status' => 'Operation',
'site_status' => 'inside_site',
'location' => 'Adit 1',
'current_km' => 1250.00,
]);
$this->operator = Employee::create([
'nik' => 'KMH-OPR-001',
'name' => 'Joko Operator',
'position' => 'Operator Excavator',
'department' => 'Civil Construction',
'is_operator' => true,
'is_driver' => true,
'is_active' => true,
]);
}
/**
* Tamu / user tanpa autentikasi diarahkan ke halaman login.
*/
public function test_unauthenticated_user_redirected_to_login(): void
{
$response = $this->get(route('qma.support_timesheet.index'));
$response->assertRedirect(route('login'));
}
/**
* Admin QMA dapat mengakses halaman Timesheet Unit Support.
*/
public function test_qma_admin_can_view_support_timesheet_page(): void
{
UnitSupportTimesheet::create([
'timesheet_no' => 'TS-US-20261020-0001',
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1258.50,
'operating_hours' => 8.50,
'location' => 'Main Dam',
'activity_type' => 'Galian Material',
'status' => 'Operation',
'created_by_user_id' => $this->qmaAdmin->id,
]);
$response = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.index'));
$response->assertStatus(200);
$response->assertSee('Timesheet Unit Support');
$response->assertSee('TS-US-20261020-0001');
$response->assertSee('EX01');
$response->assertSee('Joko Operator');
$response->assertSee('8,5 HM');
$response->assertSee('Main Dam');
}
/**
* Admin QMA dapat menyimpan timesheet baru, yang mengupdate meter unit dan posisi di Manajemen Unit.
*/
public function test_qma_admin_can_store_support_timesheet_and_syncs_vehicle_and_location(): void
{
$data = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today()->toDateString(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1258.00,
'standby_hours' => 1.0,
'breakdown_hours' => 0,
'location' => 'Powerhouse Area',
'activity_type' => 'Loading Material',
'task_description' => 'Loading batuan hasil peledakan ke dump truck',
'fuel_liters' => 120.50,
'status' => 'Operation',
'notes' => 'Operasi lancar, cuaca cerah',
];
$response = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $data);
$response->assertRedirect();
$response->assertSessionHas('success');
// Verifikasi timesheet tersimpan
$this->assertDatabaseHas('unit_support_timesheets', [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1258.00,
'operating_hours' => 8.00,
'location' => 'Powerhouse Area',
'activity_type' => 'Loading Material',
'fuel_liters' => 120.50,
'status' => 'Operation',
]);
// Verifikasi update master kendaraan
$this->supportUnit->refresh();
$this->assertEquals(1258.00, (float) $this->supportUnit->current_km);
$this->assertEquals('Powerhouse Area', $this->supportUnit->location);
$this->assertEquals('inside_site', $this->supportUnit->site_status);
$this->assertEquals('Admin QMA Tester', $this->supportUnit->location_updated_by);
// Verifikasi pembuatan riwayat audit posisi di Manajemen Unit
$this->assertDatabaseHas('vehicle_location_histories', [
'vehicle_id' => $this->supportUnit->id,
'site_status' => 'inside_site',
'location' => 'Powerhouse Area',
'source' => 'manual',
'user_name' => 'Admin QMA Tester',
]);
}
/**
* Validasi gagal jika end_meter lebih kecil dari start_meter.
*/
public function test_store_validates_end_meter_gte_start_meter(): void
{
$data = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today()->toDateString(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1240.00, // Invalid: lebih kecil dari start
'location' => 'Main Dam',
'activity_type' => 'Galian Material',
'status' => 'Operation',
];
$response = $this->actingAs($this->qmaAdmin)
->post(route('qma.support_timesheet.store'), $data);
$response->assertSessionHasErrors('end_meter');
}
/**
* Admin QMA dapat memperbarui entri timesheet.
*/
public function test_qma_admin_can_update_support_timesheet(): void
{
$timesheet = UnitSupportTimesheet::create([
'timesheet_no' => 'TS-US-20261020-0002',
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1256.00,
'operating_hours' => 6.00,
'location' => 'Adit 2',
'activity_type' => 'Galian Material',
'status' => 'Operation',
'created_by_user_id' => $this->qmaAdmin->id,
]);
$updateData = [
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today()->toDateString(),
'shift' => 'Shift 2 (Malam)',
'meter_type' => 'HM',
'start_meter' => 1250.00,
'end_meter' => 1259.50, // diupdate
'location' => 'Vertical Shaft',
'activity_type' => 'Lifting / Erection',
'status' => 'Standby',
];
$response = $this->actingAs($this->qmaAdmin)
->put(route('qma.support_timesheet.update', $timesheet->id), $updateData);
$response->assertRedirect();
$response->assertSessionHas('success');
$timesheet->refresh();
$this->assertEquals(9.50, (float) $timesheet->operating_hours);
$this->assertEquals('Shift 2 (Malam)', $timesheet->shift);
$this->assertEquals('Vertical Shaft', $timesheet->location);
$this->assertEquals('Standby', $timesheet->status);
}
/**
* Admin QMA dapat menghapus data timesheet.
*/
public function test_qma_admin_can_delete_support_timesheet(): void
{
$timesheet = UnitSupportTimesheet::create([
'timesheet_no' => 'TS-US-20261020-0003',
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 100.00,
'end_meter' => 105.00,
'operating_hours' => 5.00,
'location' => 'Main Dam',
'activity_type' => 'Galian',
'status' => 'Operation',
'created_by_user_id' => $this->qmaAdmin->id,
]);
$response = $this->actingAs($this->qmaAdmin)
->delete(route('qma.support_timesheet.destroy', $timesheet->id));
$response->assertRedirect();
$this->assertDatabaseMissing('unit_support_timesheets', ['id' => $timesheet->id]);
}
/**
* Filter berdasarkan tanggal dan unit berfungsi dengan tepat.
*/
public function test_support_timesheet_filtering_by_date_and_vehicle(): void
{
$unit2 = Vehicle::create([
'code' => 'CR01',
'category' => 'unit_support',
'brand_type' => 'Kato Crane 25 Ton',
'status' => 'Operation',
]);
UnitSupportTimesheet::create([
'timesheet_no' => 'TS-FILTER-01',
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 10,
'end_meter' => 15,
'operating_hours' => 5,
'location' => 'Main Dam',
'activity_type' => 'Galian',
'status' => 'Operation',
]);
UnitSupportTimesheet::create([
'timesheet_no' => 'TS-FILTER-02',
'vehicle_id' => $unit2->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 50,
'end_meter' => 58,
'operating_hours' => 8,
'location' => 'Powerhouse',
'activity_type' => 'Lifting',
'status' => 'Operation',
]);
$res = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.index', ['vehicle_id' => $unit2->id]));
$res->assertStatus(200);
$res->assertSee('TS-FILTER-02');
$res->assertDontSee('TS-FILTER-01');
}
/**
* Ekspor Excel dan PDF menghasilkan response file valid.
*/
public function test_export_excel_and_pdf(): void
{
UnitSupportTimesheet::create([
'timesheet_no' => 'TS-EXPORT-01',
'vehicle_id' => $this->supportUnit->id,
'operator_id' => $this->operator->id,
'date' => Carbon::today(),
'shift' => 'Shift 1 (Siang)',
'meter_type' => 'HM',
'start_meter' => 20,
'end_meter' => 28,
'operating_hours' => 8,
'location' => 'Main Dam',
'activity_type' => 'Galian',
'status' => 'Operation',
]);
// Excel
$resExcel = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.export_excel'));
$resExcel->assertStatus(200);
$this->assertTrue(str_contains(
$resExcel->headers->get('content-type') ?? '',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
));
// PDF
$resPdf = $this->actingAs($this->qmaAdmin)
->get(route('qma.support_timesheet.export_pdf'));
$resPdf->assertStatus(200);
$this->assertTrue(str_contains(
$resPdf->headers->get('content-type') ?? '',
'application/pdf'
));
}
}