feat: timesheet auto hm, sync excel vehicle locations, heavy equipment grouped by type, 2-party bast signature, and compact role permission ui

This commit is contained in:
Ray1111-aa
2026-11-01 22:28:12 +07:00
parent b83a8fa843
commit 96178971fd
11 changed files with 1509 additions and 478 deletions
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Models\UnitSupportTimesheet;
use App\Models\Vehicle;
use Illuminate\Console\Command;
class RecalculateTimesheetHoursCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'qma:recalculate-timesheet-hours';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Hitung otomatis dan perbarui finish HM serta durasi jam operasional (1 HM = 1 Jam) dari entri kronologis berikutnya';
/**
* Execute the console command.
*/
public function handle(): int
{
$this->info('Memulai rekalkulasi finish HM & jam operasi timesheet unit support...');
$vehicles = Vehicle::whereHas('supportTimesheets')->get();
$totalUpdated = 0;
foreach ($vehicles as $veh) {
$timesheets = UnitSupportTimesheet::where('vehicle_id', $veh->id)
->orderBy('date', 'asc')
->orderBy('start_time', 'asc')
->orderBy('id', 'asc')
->get();
$count = $timesheets->count();
for ($i = 0; $i < $count - 1; $i++) {
$current = $timesheets[$i];
$next = $timesheets[$i + 1];
// Jika current belum memiliki end_meter atau bernilai 0
if ($current->end_meter === null || (float) $current->end_meter == 0) {
if ($next->start_meter !== null && (float) $next->start_meter >= (float) $current->start_meter) {
$diff = (float) $next->start_meter - (float) $current->start_meter;
$current->update([
'end_meter' => $next->start_meter,
'operating_hours' => $diff,
]);
$totalUpdated++;
}
}
}
}
$this->info("Rekalkulasi selesai. Sebanyak {$totalUpdated} entri timesheet berhasil diperbarui.");
return self::SUCCESS;
}
}
@@ -0,0 +1,204 @@
<?php
namespace App\Console\Commands;
use App\Models\Vehicle;
use App\Models\VehicleLocationHistory;
use App\Services\SimpleXlsxImporter;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class SyncExcelVehicleDataCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'qma:sync-excel-locations {--file=Berkas/DATA LOKASI TERBARU RKM KMH.xlsx}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Perbarui lokasi, status site, tipe, dan spesifikasi unit alat berat (Heavy Equipment) dari berkas Excel DATA LOKASI TERBARU RKM KMH';
/**
* Execute the console command.
*/
public function handle(): int
{
$filePath = base_path($this->option('file'));
if (!file_exists($filePath)) {
$this->error("Berkas Excel tidak ditemukan di: {$filePath}");
return self::FAILURE;
}
$this->info("Membaca berkas: {$filePath} ...");
$rows = SimpleXlsxImporter::parse($filePath);
$totalRows = count($rows);
$this->info("Total baris terbaca: {$totalRows}");
if ($totalRows < 2) {
$this->warn('Berkas Excel kosong atau tidak memiliki baris data.');
return self::SUCCESS;
}
$updatedCount = 0;
$createdCount = 0;
DB::beginTransaction();
try {
for ($i = 1; $i < $totalRows; $i++) {
$r = $rows[$i];
$code1 = trim($r[4] ?? '');
if (!$code1) {
continue;
}
$cat = trim($r[2] ?? '') ?: 'SUPPORT';
$type = trim($r[3] ?? '') ?: 'HEAVY EQUIPMENT';
$statusRaw = strtoupper(trim($r[6] ?? ''));
$jenis = strtoupper(trim($r[7] ?? ''));
$lokasiSite = trim($r[8] ?? '');
$plate = trim($r[9] ?? '');
$assetNo = trim($r[10] ?? '');
$brand = trim($r[11] ?? '');
$model = trim($r[12] ?? '');
$serial = trim($r[13] ?? '');
$prodYear = trim($r[16] ?? '');
$lokasiCurrent = trim($r[18] ?? '');
$owner = trim($r[20] ?? '');
// 1. Status Operasional
$status = match ($statusRaw) {
'OPERASI', 'OPERATION' => 'Operation',
'BREAKDOWN' => 'Breakdown',
'STANDBY' => 'Standby',
'MAINTENANCE' => 'Maintenance',
default => 'Standby',
};
// 2. Lokasi & Status Area (Inside / Outside Site)
if (strtoupper($lokasiCurrent) === 'SITE' || empty($lokasiCurrent)) {
$finalLocation = $lokasiSite ?: 'Site Kerinci';
$siteStatus = 'inside_site';
} else {
$finalLocation = $lokasiCurrent;
$siteStatus = 'outside_site';
}
// 3. Timesheet Mobile Flag
$isMobile = (str_contains($jenis, 'MOBILE') || $type === 'DUMP TRUCK' || $type === 'LIGHT TRUCK');
// 4. Cari unit di database (cocokkan kode asli, kode tanpa spasi, atau nomor seri)
$cleanCode = preg_replace('/[^a-zA-Z0-9]/', '', $code1);
$vehicle = Vehicle::where('code', $code1)
->orWhereRaw("REPLACE(REPLACE(code, ' ', ''), '-', '') = ?", [$cleanCode])
->first();
if (!$vehicle && !empty($serial) && $serial !== '?') {
$vehicle = Vehicle::where('serial_number', $serial)->first();
}
$cleanBrand = ($brand !== '?' && !empty($brand)) ? $brand : null;
$cleanModel = ($model !== '?' && !empty($model)) ? $model : null;
$cleanSerial = ($serial !== '?' && !empty($serial)) ? $serial : null;
$yearInt = (is_numeric($prodYear) && (int) $prodYear > 1950 && (int) $prodYear < 2100) ? (int) $prodYear : null;
$brandTypeCombined = trim(($cleanBrand ?? '') . ' ' . ($cleanModel ?? ''));
if ($vehicle) {
// Update data unit yang sudah ada
$updatePayload = [
'category' => 'unit_support',
'unit_category' => $cat,
'unit_type' => $type,
'location' => $finalLocation,
'site_status' => $siteStatus,
'status' => $status,
'location_updated_at' => Carbon::now(),
'location_updated_by' => 'Import Berkas Excel Lokasi',
'location_note' => "Pembaruan dari berkas DATA LOKASI TERBARU RKM KMH ({$finalLocation})",
];
if ($cleanBrand) {
$updatePayload['brand'] = $cleanBrand;
}
if ($cleanModel) {
$updatePayload['model_number'] = $cleanModel;
}
if (empty($vehicle->brand_type) && !empty($brandTypeCombined)) {
$updatePayload['brand_type'] = $brandTypeCombined;
}
if ($cleanSerial && empty($vehicle->serial_number)) {
$updatePayload['serial_number'] = $cleanSerial;
}
if ($yearInt && empty($vehicle->production_year)) {
$updatePayload['production_year'] = $yearInt;
}
if (!empty($plate) && empty($vehicle->license_plate)) {
$updatePayload['license_plate'] = $plate;
}
if (!empty($owner)) {
$updatePayload['ownership'] = $owner;
}
if ($isMobile) {
$updatePayload['is_timesheet_mobile'] = true;
}
$vehicle->update($updatePayload);
$updatedCount++;
} else {
// Buat unit baru jika belum terdaftar
$vehicle = Vehicle::create([
'code' => $code1,
'category' => 'unit_support',
'unit_category' => $cat,
'unit_type' => $type,
'brand' => $cleanBrand,
'model_number' => $cleanModel,
'brand_type' => !empty($brandTypeCombined) ? $brandTypeCombined : $type,
'serial_number' => $cleanSerial,
'license_plate' => $plate ?: null,
'production_year' => $yearInt,
'location' => $finalLocation,
'site_status' => $siteStatus,
'status' => $status,
'ownership' => $owner ?: 'PT Kerinci Merangin Hidro',
'is_timesheet_mobile' => $isMobile,
'location_updated_at' => Carbon::now(),
'location_updated_by' => 'Import Berkas Excel Lokasi',
'location_note' => "Pendaftaran baru dari berkas DATA LOKASI TERBARU RKM KMH",
]);
$createdCount++;
}
// Catat riwayat lokasi unit
VehicleLocationHistory::create([
'vehicle_id' => $vehicle->id,
'site_status' => $siteStatus,
'location' => $finalLocation,
'note' => "Sinkronisasi Berkas Excel: Status {$status} di {$finalLocation}",
'source' => 'import',
'user_id' => null,
'user_name' => 'Import Berkas Excel Lokasi',
'recorded_at' => Carbon::now(),
]);
}
DB::commit();
} catch (\Throwable $e) {
DB::rollBack();
$this->error("Gagal melakukan sinkronisasi: " . $e->getMessage());
return self::FAILURE;
}
$this->info("Sinkronisasi Selesai!");
$this->info("- Unit diperbarui: {$updatedCount}");
$this->info("- Unit baru dibuat: {$createdCount}");
return self::SUCCESS;
}
}
@@ -134,12 +134,15 @@ class SupportTimesheetController extends Controller
$timesheets = $query->paginate($perPage)->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();
$statsItems = (clone $this->getFilteredQuery($request))->get();
$totalEntries = $statsItems->count();
$totalOperatingHours = 0.0;
foreach ($statsItems as $item) {
$totalOperatingHours += (float) ($item->effective_operating_hours ?? 0);
}
$totalFuelLiters = $statsItems->sum('fuel_liters');
$activeUnitsCount = $statsItems->pluck('vehicle_id')->unique()->count();
$breakdownCount = $statsItems->where('status', 'Breakdown')->count();
// Data Master untuk Form & Filter
$unitSupports = Vehicle::unitSupports()
@@ -168,8 +171,37 @@ class SupportTimesheetController extends Controller
}
$shifts = self::SHIFTS;
$activityTypes = self::PRESET_ACTIVITIES;
$locationSuggestions = UnitManagementController::getAllLocationSuggestions();
// Ambil preset + aktivitas yang pernah diisi secara dinamis di database
$dbActivities = UnitSupportTimesheet::whereNotNull('activity_type')
->where('activity_type', '!=', '')
->distinct()
->pluck('activity_type')
->all();
$activityTypes = collect(self::PRESET_ACTIVITIES)
->merge($dbActivities)
->map(fn($a) => trim($a))
->filter()
->unique()
->values()
->all();
// Ambil seluruh saran lokasi dari gerbang, kendaraan, riwayat, dan timesheet
$dbTimesheetLocs = UnitSupportTimesheet::whereNotNull('location')
->where('location', '!=', '')
->distinct()
->pluck('location')
->all();
$locationSuggestions = collect(UnitManagementController::getAllLocationSuggestions())
->merge($dbTimesheetLocs)
->map(fn($l) => trim($l))
->filter()
->unique()
->sort()
->values()
->all();
$unitLocations = $unitSupports->groupBy(function ($u) {
return trim($u->location) ?: 'Site Kerinci';
@@ -282,7 +314,26 @@ class SupportTimesheetController extends Controller
$endMeter = isset($validated['end_meter']) && $validated['end_meter'] !== '' && $validated['end_meter'] !== null
? (float) $validated['end_meter']
: null;
$operatingHours = $endMeter !== null ? max(0, $endMeter - $startMeter) : null;
if ($endMeter === null) {
$nextEntry = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where(function ($q) use ($validated, $startMeter) {
$q->where('date', '>', $validated['date'])
->orWhere(function ($sq) use ($validated, $startMeter) {
$sq->where('date', $validated['date'])
->where('start_meter', '>=', $startMeter);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($nextEntry && (float) $nextEntry->start_meter >= $startMeter) {
$endMeter = (float) $nextEntry->start_meter;
}
}
$operatingHours = $endMeter !== null ? max(0.0, $endMeter - $startMeter) : null;
$shift = $validated['shift'] ?: 'Shift Siang';
$updaterName = auth()->user()?->name ?? 'Admin QMA';
$timesheetNo = null;
@@ -325,6 +376,25 @@ class SupportTimesheetController extends Controller
'created_by_user_id' => auth()->id(),
]);
// 1b. Perbarui entri sebelumnya yang belum memiliki end_meter untuk unit yang sama (1 HM = 1 Jam)
$prevTimesheet = UnitSupportTimesheet::where('vehicle_id', $vehicle->id)
->where('id', '<', $timesheet->id)
->whereDate('date', '<=', $validated['date'])
->where(function ($q) {
$q->whereNull('end_meter')
->orWhere('end_meter', '<=', 0);
})
->orderByDesc('id')
->first();
if ($prevTimesheet && (float) $startMeter >= (float) $prevTimesheet->start_meter) {
$prevDiff = (float) $startMeter - (float) $prevTimesheet->start_meter;
$prevTimesheet->update([
'end_meter' => $startMeter,
'operating_hours' => $prevDiff,
]);
}
// 2. Sinkronisasi Master Kendaraan (Odometer & Posisi di Manajemen Unit)
$updateData = [
'status' => $validated['status'],
@@ -511,6 +581,9 @@ class SupportTimesheetController extends Controller
$rows = [];
foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [
$idx + 1,
$ts->timesheet_no,
@@ -523,8 +596,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->nik ?: '-',
$ts->meter_type,
number_format($ts->start_meter, 2, ',', '.'),
number_format($ts->end_meter, 2, ',', '.'),
number_format($ts->operating_hours, 2, ',', '.'),
$endMeter !== null ? number_format($endMeter, 2, ',', '.') : '-',
$opHours !== null ? number_format($opHours, 2, ',', '.') : '-',
number_format($ts->standby_hours, 2, ',', '.'),
number_format($ts->breakdown_hours, 2, ',', '.'),
$ts->location,
@@ -606,6 +679,9 @@ class SupportTimesheetController extends Controller
$rows = [];
foreach ($timesheets as $idx => $ts) {
$endMeter = $ts->effective_end_meter;
$opHours = $ts->effective_operating_hours;
$rows[] = [
$idx + 1,
$ts->date ? $ts->date->format('d/m/Y') : '-',
@@ -614,8 +690,8 @@ class SupportTimesheetController extends Controller
$ts->operator?->name ? ($ts->operator->name . ' (' . ($ts->operator->employee_type ?: 'Karyawan') . ')') : '-',
$ts->shift,
number_format($ts->start_meter, 1, ',', '.'),
number_format($ts->end_meter, 1, ',', '.'),
number_format($ts->operating_hours, 1, ',', '.') . ' ' . $ts->meter_type,
$endMeter !== null ? number_format($endMeter, 1, ',', '.') : '-',
($opHours !== null ? number_format($opHours, 1, ',', '.') : '-') . ' ' . $ts->meter_type,
$ts->location,
$ts->status,
];
+166 -49
View File
@@ -280,53 +280,7 @@ class VehicleController extends Controller
*/
public function indexSupport(Request $request): View
{
$query = Vehicle::unitSupportCategories()->withCount('units');
// Filter Status Operasional
if ($request->filled('status')) {
$query->where('status', $request->input('status'));
}
// Filter Kategori Heavy Equipment (Excavator, Crane, Bulldozer, dll)
if ($request->filled('unit_category')) {
$query->where('unit_category', $request->input('unit_category'));
}
// Filter Pencarian Keyword Heavy Equipment
if ($request->filled('search')) {
$search = trim($request->input('search'));
$query->where(function ($q) use ($search) {
$q->where('code', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('unit_category', 'like', "%{$search}%")
->orWhere('unit_type', 'like', "%{$search}%")
->orWhere('brand', 'like', "%{$search}%")
->orWhere('model_number', 'like', "%{$search}%")
->orWhere('location', 'like', "%{$search}%")
->orWhere('ownership', 'like', "%{$search}%")
->orWhere('division', 'like', "%{$search}%");
});
}
$perPage = (int) $request->input('per_page', 15);
if (!in_array($perPage, [15, 50, 100])) {
$perPage = 15;
}
$vehicles = $query->orderBy('code')->paginate($perPage)->withQueryString();
// Statistik Ringkasan Khusus Heavy Equipment
$totalSupport = Vehicle::unitSupportCategories()->count();
$totalUnits = Vehicle::unitSupportPhysical()->count();
$totalOperation = Vehicle::unitSupportCategories()->where('status', 'Operation')->count();
$totalStandby = Vehicle::unitSupportCategories()->where('status', 'Standby')->count();
$totalBreakdown = Vehicle::unitSupportCategories()->where('status', 'Breakdown')->count();
// Daftar kategori alat berat yang terdaftar untuk opsi filter
$availableCategories = Vehicle::unitSupportCategories()
->whereNotNull('unit_category')
->distinct()
->pluck('unit_category');
$selectedType = $request->input('type');
// Master data daftar divisi perusahaan (gabungan standar + data existing di Employee & Vehicle)
$standardDivisions = collect([
@@ -353,8 +307,170 @@ class VehicleController extends Controller
->values()
->all();
// Daftar semua kode Heavy Equipment untuk validasi unik langsung di form
$existingCodes = Vehicle::unitSupports()->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
// Master data daftar kategori & tipe alat berat
$availableCategories = Vehicle::where('category', 'unit_support')
->whereNotNull('unit_category')
->where('unit_category', '!=', '')
->distinct()
->pluck('unit_category');
$availableTypes = Vehicle::where('category', 'unit_support')
->whereNotNull('unit_type')
->where('unit_type', '!=', '')
->distinct()
->orderBy('unit_type')
->pluck('unit_type');
$existingCodes = Vehicle::where('category', 'unit_support')->pluck('code')->map(fn($c) => strtoupper(trim($c)))->values()->all();
// 1. JIKA USER MEMILIH / MASUK KE TIPE TERTENTU (Tampilkan unit-unit fisik tipe tersebut)
if ($selectedType) {
$unitsQuery = Vehicle::where('category', 'unit_support')
->where(function ($q) use ($selectedType) {
$q->where('unit_type', $selectedType)
->orWhere('unit_category', $selectedType);
});
if ($request->filled('status')) {
$unitsQuery->where('status', $request->input('status'));
}
if ($request->filled('site_status')) {
$unitsQuery->where('site_status', $request->input('site_status'));
}
if ($request->filled('location')) {
$unitsQuery->where('location', $request->input('location'));
}
if ($request->filled('search')) {
$search = trim($request->input('search'));
$unitsQuery->where(function ($q) use ($search) {
$q->where('code', 'like', "%{$search}%")
->orWhere('brand', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('model_number', 'like', "%{$search}%")
->orWhere('serial_number', 'like', "%{$search}%")
->orWhere('license_plate', 'like', "%{$search}%")
->orWhere('location', 'like', "%{$search}%");
});
}
$perPage = (int) $request->input('per_page', 15);
if (!in_array($perPage, [15, 50, 100])) {
$perPage = 15;
}
$typeUnits = $unitsQuery->orderBy('code')->paginate($perPage)->withQueryString();
// Statistik Khusus Tipe Terpilih
$allOfType = Vehicle::where('category', 'unit_support')
->where(function ($q) use ($selectedType) {
$q->where('unit_type', $selectedType)
->orWhere('unit_category', $selectedType);
})
->get();
$totalUnitsOfType = $allOfType->count();
$opCount = $allOfType->where('status', 'Operation')->count();
$stCount = $allOfType->where('status', 'Standby')->count();
$bdCount = $allOfType->where('status', 'Breakdown')->count();
$insideCount = $allOfType->where('site_status', 'inside_site')->count();
$outsideCount = $allOfType->where('site_status', 'outside_site')->count();
// Total global statistik untuk header
$totalUnits = Vehicle::where('category', 'unit_support')->count();
$totalOperation = Vehicle::where('category', 'unit_support')->where('status', 'Operation')->count();
$totalStandby = Vehicle::where('category', 'unit_support')->where('status', 'Standby')->count();
$totalBreakdown = Vehicle::where('category', 'unit_support')->where('status', 'Breakdown')->count();
$totalSupport = $availableTypes->count();
return view('qma.vehicles_support', compact(
'selectedType',
'typeUnits',
'totalUnitsOfType',
'opCount',
'stCount',
'bdCount',
'insideCount',
'outsideCount',
'totalSupport',
'totalUnits',
'totalOperation',
'totalStandby',
'totalBreakdown',
'availableCategories',
'availableTypes',
'availableDivisions',
'existingCodes'
));
}
// 2. TAMPILAN UTAMA: PENGELOMPOKAN BERDASARKAN TYPE DULU
$allSupportQuery = Vehicle::where('category', 'unit_support');
$totalUnits = (clone $allSupportQuery)->count();
$totalOperation = (clone $allSupportQuery)->where('status', 'Operation')->count();
$totalStandby = (clone $allSupportQuery)->where('status', 'Standby')->count();
$totalBreakdown = (clone $allSupportQuery)->where('status', 'Breakdown')->count();
$totalSupport = (clone $allSupportQuery)->whereNotNull('unit_type')->where('unit_type', '!=', '')->distinct('unit_type')->count('unit_type');
// Query pengelompokan berdasarkan tipe
$hasTypes = Vehicle::where('category', 'unit_support')->whereNotNull('unit_type')->where('unit_type', '!=', '')->exists();
if ($hasTypes) {
$typeGroupsQuery = Vehicle::where('category', 'unit_support')
->select(
DB::raw("COALESCE(NULLIF(unit_type, ''), 'LAINNYA') as unit_type"),
DB::raw('MAX(unit_category) as unit_category'),
DB::raw('COUNT(*) as units_count'),
DB::raw("SUM(CASE WHEN status = 'Operation' THEN 1 ELSE 0 END) as total_operation"),
DB::raw("SUM(CASE WHEN status = 'Standby' THEN 1 ELSE 0 END) as total_standby"),
DB::raw("SUM(CASE WHEN status = 'Breakdown' THEN 1 ELSE 0 END) as total_breakdown"),
DB::raw("SUM(CASE WHEN site_status = 'inside_site' THEN 1 ELSE 0 END) as inside_site_count"),
DB::raw("SUM(CASE WHEN site_status = 'outside_site' THEN 1 ELSE 0 END) as outside_site_count"),
DB::raw('MAX(brand_type) as sample_brand_type'),
DB::raw('MAX(photo_path) as sample_photo'),
DB::raw('MIN(id) as sample_id'),
DB::raw('MIN(code) as code')
)
->groupBy(DB::raw("COALESCE(NULLIF(unit_type, ''), 'LAINNYA')"));
if ($request->filled('unit_category')) {
$typeGroupsQuery->where('unit_category', $request->input('unit_category'));
}
if ($request->filled('search')) {
$search = trim($request->input('search'));
$typeGroupsQuery->where(function ($q) use ($search) {
$q->where('unit_type', 'like', "%{$search}%")
->orWhere('unit_category', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('code', 'like', "%{$search}%");
});
}
$perPage = (int) $request->input('per_page', 15);
if (!in_array($perPage, [15, 50, 100])) {
$perPage = 15;
}
$vehicles = $typeGroupsQuery->orderByDesc(DB::raw('COUNT(*)'))->paginate($perPage)->withQueryString();
} else {
// Fallback untuk DB sebelum sync excel atau legacy category format
$query = Vehicle::unitSupportCategories()->withCount('units');
if ($request->filled('status')) {
$query->where('status', $request->input('status'));
}
if ($request->filled('unit_category')) {
$query->where('unit_category', $request->input('unit_category'));
}
if ($request->filled('search')) {
$search = trim($request->input('search'));
$query->where(function ($q) use ($search) {
$q->where('code', 'like', "%{$search}%")
->orWhere('brand_type', 'like', "%{$search}%")
->orWhere('unit_category', 'like', "%{$search}%");
});
}
$perPage = (int) $request->input('per_page', 15);
$vehicles = $query->orderBy('code')->paginate($perPage)->withQueryString();
}
return view('qma.vehicles_support', compact(
'vehicles',
@@ -364,6 +480,7 @@ class VehicleController extends Controller
'totalStandby',
'totalBreakdown',
'availableCategories',
'availableTypes',
'availableDivisions',
'existingCodes'
));
+52
View File
@@ -45,6 +45,11 @@ class UnitSupportTimesheet extends Model
'fuel_liters' => 'decimal:2',
];
protected $appends = [
'effective_end_meter',
'effective_operating_hours',
];
public function vehicle(): BelongsTo
{
return $this->belongsTo(Vehicle::class);
@@ -60,6 +65,53 @@ class UnitSupportTimesheet extends Model
return $this->belongsTo(User::class, 'created_by_user_id');
}
/**
* Dapatkan meter akhir efektif.
* Jika end_meter sudah diisi, gunakan nilainya.
* Jika belum, cari dari start_meter entri berikutnya untuk unit yang sama.
*/
public function getEffectiveEndMeterAttribute(): ?float
{
if ($this->end_meter !== null && (float) $this->end_meter > 0) {
return (float) $this->end_meter;
}
$next = static::where('vehicle_id', $this->vehicle_id)
->where(function ($q) {
$q->where('date', '>', $this->date)
->orWhere(function ($sq) {
$sq->where('date', $this->date)
->where('id', '>', $this->id);
});
})
->orderBy('date', 'asc')
->orderBy('id', 'asc')
->first();
if ($next && $next->start_meter !== null && (float) $next->start_meter >= (float) $this->start_meter) {
return (float) $next->start_meter;
}
return null;
}
/**
* Dapatkan jam kerja operasional efektif (1 HM = 1 Jam).
*/
public function getEffectiveOperatingHoursAttribute(): ?float
{
if ($this->operating_hours !== null && (float) $this->operating_hours > 0) {
return (float) $this->operating_hours;
}
$end = $this->effective_end_meter;
if ($end !== null && $this->start_meter !== null) {
return max(0.0, (float) $end - (float) $this->start_meter);
}
return null;
}
/**
* Generate nomor timesheet unik harian (Format: TS-US-YYYYMMDD-0001).
* Dilengkapi mitigasi tabrakan concurrency dan pengecekan soft deleted records.