feat: add compressed photo upload for LV, unit support, and employees

This commit is contained in:
Ray1111-aa
2026-10-20 16:00:29 +07:00
parent cb284a7432
commit 7126648c1c
10 changed files with 929 additions and 15 deletions
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Hse;
use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\User;
use App\Services\ImageCompressionService;
use App\Services\SimperPdfExporter;
use App\Services\SimpleXlsxExporter;
use App\Services\SimpleXlsxImporter;
@@ -536,6 +537,7 @@ class EmployeeController extends Controller
'position' => ['required', 'string'],
'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
], [
'nik.required' => 'NIK wajib diisi.',
'nik.unique' => 'NIK sudah terdaftar dalam sistem.',
@@ -563,6 +565,11 @@ class EmployeeController extends Controller
$user->assignRole('employee');
}
$photoPath = null;
if ($request->hasFile('photo')) {
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
}
Employee::create([
'nik' => $validated['nik'],
'name' => $validated['name'],
@@ -571,6 +578,7 @@ class EmployeeController extends Controller
'position' => $validated['position'],
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath,
'user_id' => $user->id,
]);
@@ -592,6 +600,7 @@ class EmployeeController extends Controller
'position' => ['sometimes', 'required', 'string'],
'is_operator' => ['required', 'in:1,0'],
'simper_expired_at' => ['nullable', 'date'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
], [
'nik.unique' => 'NIK sudah digunakan oleh karyawan lain.',
'name.required' => 'Nama lengkap wajib diisi.',
@@ -601,6 +610,12 @@ class EmployeeController extends Controller
$isOperator = (bool) $validated['is_operator'];
$simperExpiredAt = $isOperator ? ($validated['simper_expired_at'] ?? $employee->simper_expired_at) : null;
$photoPath = $employee->photo_path;
if ($request->hasFile('photo')) {
ImageCompressionService::deleteIfExists($employee->photo_path);
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'employees', 500, 500, 80);
}
$employee->update([
'nik' => $validated['nik'] ?? $employee->nik,
'name' => $validated['name'] ?? $employee->name,
@@ -609,6 +624,7 @@ class EmployeeController extends Controller
'position' => $validated['position'] ?? $employee->position,
'is_operator' => $isOperator,
'simper_expired_at' => $simperExpiredAt,
'photo_path' => $photoPath,
]);
return back()->with('success', "Data SIMPER untuk {$employee->name} berhasil diperbarui.");
@@ -9,6 +9,7 @@ use App\Models\P2hRecord;
use App\Models\P2hTemplate;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use App\Services\ImageCompressionService;
use App\Services\SimpleXlsxExporter;
use App\Services\VehiclePdfExporter;
use Carbon\Carbon;
@@ -895,6 +896,7 @@ class VehicleController extends Controller
'kir_document' => ['nullable', 'string', 'max:150'],
'ownership' => ['nullable', 'string', 'max:150'],
'division' => ['nullable', 'string', 'max:100'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
]);
return DB::transaction(function () use ($request, $category) {
@@ -918,6 +920,11 @@ class VehicleController extends Controller
return back()->withInput()->with('error', "Kode unit [{$code}] sudah terdaftar di sistem. Silakan gunakan nomor urut lain.");
}
$photoPath = null;
if ($request->hasFile('photo')) {
$photoPath = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75);
}
$unit = Vehicle::create([
'code' => $code,
'category' => 'unit_support',
@@ -939,6 +946,7 @@ class VehicleController extends Controller
'fuel_consumption' => $category->fuel_consumption,
'silo_document' => $request->input('silo_document'),
'kir_document' => $request->input('kir_document'),
'photo_path' => $photoPath,
]);
return back()->with('success', "Unit fisik [{$unit->code}] berhasil ditambahkan ke kategori {$category->unit_category}.");
@@ -962,6 +970,7 @@ class VehicleController extends Controller
'division' => ['nullable', 'string', 'max:100'],
'status' => [$category === 'unit_support' ? 'nullable' : 'required', 'string', 'in:Operation,Standby,Breakdown,Maintenance'],
'current_km' => [$category === 'unit_support' ? 'nullable' : 'required', 'numeric', 'min:0'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
];
// Atribut opsional spesifik Unit Support (Kendaraan Berat)
@@ -994,6 +1003,11 @@ class VehicleController extends Controller
$validated['current_km'] = $validated['current_km'] ?? 0;
}
if ($request->hasFile('photo')) {
$validated['photo_path'] = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75);
}
unset($validated['photo']);
$vehicle = Vehicle::create($validated);
if ($vehicle->isSupportCategory()) {
@@ -1045,6 +1059,7 @@ class VehicleController extends Controller
'stnk_document' => ['nullable', 'string', 'max:150'],
'pajak_document' => ['nullable', 'string', 'max:150'],
'kir_document' => ['nullable', 'string', 'max:150'],
'photo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp', 'max:10240'],
];
$validated = $request->validate($rules, [
@@ -1054,6 +1069,12 @@ class VehicleController extends Controller
'current_km.required' => 'Nilai KM / HM wajib diisi.',
]);
if ($request->hasFile('photo')) {
ImageCompressionService::deleteIfExists($vehicle->photo_path);
$validated['photo_path'] = ImageCompressionService::uploadAndCompress($request->file('photo'), 'vehicles', 800, 800, 75);
}
unset($validated['photo']);
DB::transaction(function () use ($vehicle, $validated, $oldCode, $newCode) {
$vehicle->update($validated);
@@ -1133,6 +1154,13 @@ class VehicleController extends Controller
}
}
if ($vehicle->isSupportCategory()) {
foreach ($vehicle->units as $u) {
ImageCompressionService::deleteIfExists($u->photo_path);
}
}
ImageCompressionService::deleteIfExists($vehicle->photo_path);
$code = $vehicle->code;
$vehicle->delete();
+17
View File
@@ -30,6 +30,10 @@ class Employee extends Model
'simper_expired_at' => 'date',
];
protected $appends = [
'photo_url',
];
/**
* Cek apakah SIMPER masih aktif hari ini.
*/
@@ -42,6 +46,19 @@ class Employee extends Model
return $this->simper_expired_at->isFuture() || $this->simper_expired_at->isToday();
}
public function getPhotoUrlAttribute(): ?string
{
if (!$this->photo_path) {
return null;
}
if (str_starts_with($this->photo_path, 'http://') || str_starts_with($this->photo_path, 'https://')) {
return $this->photo_path;
}
return asset('storage/' . ltrim($this->photo_path, '/'));
}
/**
* Scope untuk mengambil hanya karyawan yang berstatus operator/driver.
*/
+17
View File
@@ -46,11 +46,28 @@ class Vehicle extends Model
'parent_id' => 'integer',
];
protected $appends = [
'photo_url',
];
public function isLightVehicle(): bool
{
return $this->category === 'light_vehicle';
}
public function getPhotoUrlAttribute(): ?string
{
if (!$this->photo_path) {
return null;
}
if (str_starts_with($this->photo_path, 'http://') || str_starts_with($this->photo_path, 'https://')) {
return $this->photo_path;
}
return asset('storage/' . ltrim($this->photo_path, '/'));
}
public function isUnitSupport(): bool
{
return $this->category === 'unit_support';
+150
View File
@@ -0,0 +1,150 @@
<?php
namespace App\Services;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ImageCompressionService
{
/**
* Kompresi dan simpan foto ke disk publik dengan optimasi resolusi & ukuran file.
*
* @param UploadedFile $file File yang diunggah dari form request
* @param string $directory Direktori penyimpanan (misal: 'vehicles', 'employees')
* @param int $maxWidth Lebar maksimal gambar dalam pixel (default: 800)
* @param int $maxHeight Tinggi maksimal gambar dalam pixel (default: 800)
* @param int $quality Kualitas kompresi JPEG 1-100 (default: 75)
* @return string Path relatif file yang tersimpan di disk public
*/
public static function uploadAndCompress(
UploadedFile $file,
string $directory,
int $maxWidth = 800,
int $maxHeight = 800,
int $quality = 75
): string {
$cleanDir = trim($directory, '/');
// Jika ekstensi GD tidak aktif, fallback simpan langsung
if (!extension_loaded('gd')) {
$fallbackName = Str::random(40) . '.' . ($file->guessExtension() ?: 'jpg');
return $file->storeAs($cleanDir, $fallbackName, 'public');
}
try {
$realPath = $file->getRealPath();
$imageContent = file_get_contents($realPath);
if ($imageContent === false) {
$fallbackName = Str::random(40) . '.' . ($file->guessExtension() ?: 'jpg');
return $file->storeAs($cleanDir, $fallbackName, 'public');
}
// Buat resource gambar dari data string
$srcImage = @imagecreatefromstring($imageContent);
if (!$srcImage) {
$fallbackName = Str::random(40) . '.' . ($file->guessExtension() ?: 'jpg');
return $file->storeAs($cleanDir, $fallbackName, 'public');
}
// 1. Tangani Auto-Orientation berdasarkan EXIF (kamera smartphone)
if (function_exists('exif_read_data')) {
$exif = @exif_read_data($realPath);
if (!empty($exif['Orientation'])) {
$srcImage = match ($exif['Orientation']) {
3 => imagerotate($srcImage, 180, 0),
6 => imagerotate($srcImage, -90, 0),
8 => imagerotate($srcImage, 90, 0),
default => $srcImage,
};
}
}
// 2. Hitung Dimensi Proporsional
$origWidth = imagesx($srcImage);
$origHeight = imagesy($srcImage);
if ($origWidth > $maxWidth || $origHeight > $maxHeight) {
$ratio = min($maxWidth / $origWidth, $maxHeight / $origHeight);
$targetWidth = max(1, (int) round($origWidth * $ratio));
$targetHeight = max(1, (int) round($origHeight * $ratio));
} else {
$targetWidth = $origWidth;
$targetHeight = $origHeight;
}
// 3. Buat Canvas Truecolor Baru
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
// Beri latar belakang putih solid jika ada area transparan (PNG/WebP)
$white = imagecolorallocate($canvas, 255, 255, 255);
imagefilledrectangle($canvas, 0, 0, $targetWidth, $targetHeight, $white);
// 4. Salin & Resample Gambar dengan Kualitas Tinggi
imagecopyresampled(
$canvas,
$srcImage,
0,
0,
0,
0,
$targetWidth,
$targetHeight,
$origWidth,
$origHeight
);
// 5. Simpan Hasil Kompresi Gambar ke Buffer Memori sesuai format yang didukung
$compressedStream = null;
$extension = 'jpg';
if (function_exists('imagejpeg')) {
$extension = 'jpg';
ob_start();
imagejpeg($canvas, null, $quality);
$compressedStream = ob_get_clean();
} elseif (function_exists('imagewebp')) {
$extension = 'webp';
ob_start();
imagewebp($canvas, null, $quality);
$compressedStream = ob_get_clean();
} elseif (function_exists('imagepng')) {
$extension = 'png';
$pngLevel = max(0, min(9, (int) round((100 - $quality) / 10)));
ob_start();
imagepng($canvas, null, $pngLevel);
$compressedStream = ob_get_clean();
}
// Bersihkan resource GD dari memori
imagedestroy($canvas);
imagedestroy($srcImage);
if (!empty($compressedStream)) {
$fileName = Str::random(40) . '.' . $extension;
$targetPath = $cleanDir . '/' . $fileName;
Storage::disk('public')->put($targetPath, $compressedStream);
return $targetPath;
}
} catch (\Throwable $e) {
// Jika terjadi kesalahan proses GD, fallback aman simpan file asli
}
$fallbackName = Str::random(40) . '.' . ($file->guessExtension() ?: 'jpg');
return $file->storeAs($cleanDir, $fallbackName, 'public');
}
/**
* Hapus file foto lama dari disk publik jika ada.
*
* @param string|null $path
* @return void
*/
public static function deleteIfExists(?string $path): void
{
if (!empty($path) && Storage::disk('public')->exists($path)) {
Storage::disk('public')->delete($path);
}
}
}
+100 -4
View File
@@ -151,8 +151,19 @@
<!-- NIK (Font Bold Hitam Tegas) -->
<td class="py-3.5 px-4 font-bold text-slate-900 font-mono text-xs">{{ $emp->nik }}</td>
<!-- Nama Lengkap (Font Bold Hitam) -->
<td class="py-3.5 px-4 font-bold text-slate-900">{{ $emp->name }}</td>
<!-- Nama Lengkap (Avatar + Font Bold Hitam) -->
<td class="py-3.5 px-4 font-bold text-slate-900">
<div class="flex items-center space-x-2.5">
@if($emp->photo_path)
<img src="{{ $emp->photo_url }}" alt="{{ $emp->name }}" class="w-8 h-8 rounded-full object-cover border border-slate-200 shadow-2xs flex-shrink-0 cursor-pointer" onclick='openEditModal(@json($emp))'>
@else
<div class="w-8 h-8 rounded-full bg-emerald-50 border border-emerald-200 text-[#1b5e20] flex items-center justify-center text-xs font-bold uppercase flex-shrink-0">
{{ substr($emp->name, 0, 1) }}
</div>
@endif
<span class="truncate">{{ $emp->name }}</span>
</div>
</td>
<!-- Jabatan -->
<td class="py-3.5 px-4 text-slate-600">{{ $emp->position ?? '-' }}</td>
@@ -273,8 +284,27 @@
</button>
</div>
<form action="{{ route('hse.employees.store') }}" method="POST" class="mt-5 space-y-4">
<form action="{{ route('hse.employees.store') }}" method="POST" enctype="multipart/form-data" class="mt-5 space-y-4">
@csrf
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Foto Profil Karyawan (Opsional)</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="addEmpPhotoPreviewContainer" class="w-14 h-14 rounded-full border-2 border-dashed border-slate-300 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="addEmpPhotoPreview" src="" alt="Pratinjau" class="w-full h-full object-cover hidden">
<i id="addEmpPhotoPlaceholder" class="fa-solid fa-camera text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="addEmpPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewEmployeeImage(this, 'addEmpPhotoPreview', 'addEmpPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Format: JPG, PNG, WebP (Maks. 10MB). Resolusi & file dikompresi otomatis.</p>
</div>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">NIK (Nomor Induk Karyawan) <span class="text-rose-500">*</span></label>
@@ -485,9 +515,28 @@
</button>
</div>
<form id="editForm" method="POST" action="" class="mt-5 space-y-4">
<form id="editForm" method="POST" action="" enctype="multipart/form-data" class="mt-5 space-y-4">
@csrf
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Foto Profil Karyawan</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="editEmpPhotoPreviewContainer" class="w-14 h-14 rounded-full border border-slate-200 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="editEmpPhotoPreview" src="" alt="Foto Karyawan" class="w-full h-full object-cover hidden">
<i id="editEmpPhotoPlaceholder" class="fa-solid fa-user text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="editEmpPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewEmployeeImage(this, 'editEmpPhotoPreview', 'editEmpPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Pilih foto baru jika ingin mengganti. Otomatis dikompresi hemat storage.</p>
</div>
</div>
</div>
<!-- Profil Master Data Karyawan (Read-Only Info Card) -->
<div class="bg-slate-50 border border-slate-200/80 rounded-2xl p-4">
<div class="flex items-center justify-between mb-2 pb-2 border-b border-slate-200/60">
@@ -680,6 +729,24 @@
}
}
function previewEmployeeImage(input, imgId, placeholderId) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById(imgId);
const placeholder = document.getElementById(placeholderId);
if (img) {
img.src = e.target.result;
img.classList.remove('hidden');
}
if (placeholder) {
placeholder.classList.add('hidden');
}
};
reader.readAsDataURL(input.files[0]);
}
}
function openEditModal(emp) {
document.getElementById('editNikDisplay').textContent = emp.nik || '-';
document.getElementById('editNameDisplay').textContent = emp.name || '-';
@@ -687,6 +754,24 @@
document.getElementById('editDivisionPositionDisplay').textContent = (emp.division || '-') + ' / ' + (emp.position || '-');
document.getElementById('editOperator').value = emp.is_operator ? '1' : '0';
const editPhotoPreview = document.getElementById('editEmpPhotoPreview');
const editPhotoPlaceholder = document.getElementById('editEmpPhotoPlaceholder');
const editPhotoInput = document.getElementById('editEmpPhotoInput');
if (editPhotoInput) editPhotoInput.value = '';
if (emp.photo_url) {
if (editPhotoPreview) {
editPhotoPreview.src = emp.photo_url;
editPhotoPreview.classList.remove('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.add('hidden');
} else {
if (editPhotoPreview) {
editPhotoPreview.src = '';
editPhotoPreview.classList.add('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.remove('hidden');
}
let expDate = '';
if (emp.simper_expired_at) {
expDate = emp.simper_expired_at.substring(0, 10);
@@ -829,6 +914,17 @@
// Modal Tambah Karyawan Manual
function openAddKaryawanModal() {
const modal = document.getElementById('addKaryawanModal');
const addPhotoPreview = document.getElementById('addEmpPhotoPreview');
const addPhotoPlaceholder = document.getElementById('addEmpPhotoPlaceholder');
const addPhotoInput = document.getElementById('addEmpPhotoInput');
if (addPhotoInput) addPhotoInput.value = '';
if (addPhotoPreview) {
addPhotoPreview.src = '';
addPhotoPreview.classList.add('hidden');
}
if (addPhotoPlaceholder) {
addPhotoPlaceholder.classList.remove('hidden');
}
if (modal) modal.classList.remove('hidden');
}
function closeAddKaryawanModal() {
+117 -3
View File
@@ -145,7 +145,21 @@
</td>
<td class="py-3.5 px-4 font-bold text-slate-900">
{{ $v->brand_type }}
<div class="flex items-center space-x-3">
@if($v->photo_path)
<img src="{{ $v->photo_url }}" alt="{{ $v->code }}" class="w-9 h-9 rounded-lg object-cover border border-slate-200 shadow-2xs flex-shrink-0 cursor-pointer" onclick='openDetailModal(@json($v))'>
@else
<div class="w-9 h-9 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-400 flex-shrink-0">
<i class="fa-solid fa-car text-xs"></i>
</div>
@endif
<div class="min-w-0">
<div class="truncate">{{ $v->brand_type }}</div>
@if($v->serial_number)
<div class="text-[10px] text-slate-400 font-mono font-normal truncate">SN: {{ $v->serial_number }}</div>
@endif
</div>
</div>
</td>
<td class="py-3.5 px-4 text-center whitespace-nowrap">
@@ -267,10 +281,29 @@
</button>
</div>
<form id="addVehicleForm" action="{{ route('qma.vehicles.store') }}" method="POST" class="space-y-4">
<form id="addVehicleForm" action="{{ route('qma.vehicles.store') }}" method="POST" enctype="multipart/form-data" class="space-y-4">
@csrf
<input type="hidden" name="category" value="light_vehicle">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Foto Unit Kendaraan (Opsional)</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="addPhotoPreviewContainer" class="w-14 h-14 rounded-xl border-2 border-dashed border-slate-300 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="addPhotoPreview" src="" alt="Pratinjau" class="w-full h-full object-cover hidden">
<i id="addPhotoPlaceholder" class="fa-solid fa-camera text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="addPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewVehicleImage(this, 'addPhotoPreview', 'addPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Format: JPG, PNG, WebP (Maks. 10MB). Otomatis dikompresi agar hemat storage.</p>
</div>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Kode LV <span class="text-rose-500">*</span></label>
@@ -364,10 +397,29 @@
</button>
</div>
<form id="editVehicleForm" action="" method="POST" class="space-y-4">
<form id="editVehicleForm" action="" method="POST" enctype="multipart/form-data" class="space-y-4">
@csrf
<input type="hidden" name="category" value="light_vehicle">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Foto Unit Kendaraan</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="editPhotoPreviewContainer" class="w-14 h-14 rounded-xl border border-slate-200 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="editPhotoPreview" src="" alt="Foto Unit" class="w-full h-full object-cover hidden">
<i id="editPhotoPlaceholder" class="fa-solid fa-car text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="editPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewVehicleImage(this, 'editPhotoPreview', 'editPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Pilih foto baru jika ingin mengganti. Otomatis dikompresi hemat storage server.</p>
</div>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Kode LV <span class="text-rose-500">*</span></label>
@@ -456,6 +508,11 @@
</div>
<div class="space-y-4">
<!-- Foto Kendaraan di Detail Modal -->
<div id="detailPhotoContainer" class="w-full h-48 rounded-2xl bg-slate-100 border border-slate-200 flex items-center justify-center overflow-hidden relative hidden">
<img id="detailPhoto" src="" alt="Foto Unit LV" class="w-full h-full object-cover">
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Kode LV</label>
@@ -828,8 +885,37 @@
});
}
function previewVehicleImage(input, imgId, placeholderId) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById(imgId);
const placeholder = document.getElementById(placeholderId);
if (img) {
img.src = e.target.result;
img.classList.remove('hidden');
}
if (placeholder) {
placeholder.classList.add('hidden');
}
};
reader.readAsDataURL(input.files[0]);
}
}
function openAddModal() {
document.getElementById('addVehicleModal').classList.remove('hidden');
const addPhotoPreview = document.getElementById('addPhotoPreview');
const addPhotoPlaceholder = document.getElementById('addPhotoPlaceholder');
const addPhotoInput = document.getElementById('addPhotoInput');
if (addPhotoInput) addPhotoInput.value = '';
if (addPhotoPreview) {
addPhotoPreview.src = '';
addPhotoPreview.classList.add('hidden');
}
if (addPhotoPlaceholder) {
addPhotoPlaceholder.classList.remove('hidden');
}
if (addCodeInput) addCodeInput.focus();
}
function closeAddModal() {
@@ -849,6 +935,24 @@
document.getElementById('editOwnership').value = v.ownership || '';
document.getElementById('editStatus').value = v.status || 'Operation';
document.getElementById('editCurrentKm').value = v.current_km || 0;
const editPhotoPreview = document.getElementById('editPhotoPreview');
const editPhotoPlaceholder = document.getElementById('editPhotoPlaceholder');
const editPhotoInput = document.getElementById('editPhotoInput');
if (editPhotoInput) editPhotoInput.value = '';
if (v.photo_url) {
if (editPhotoPreview) {
editPhotoPreview.src = v.photo_url;
editPhotoPreview.classList.remove('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.add('hidden');
} else {
if (editPhotoPreview) {
editPhotoPreview.src = '';
editPhotoPreview.classList.add('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.remove('hidden');
}
}
function closeEditModal() {
document.getElementById('editVehicleModal').classList.add('hidden');
@@ -865,6 +969,16 @@
document.getElementById('detailDivision').innerText = v.division || '-';
document.getElementById('detailOwnership').innerText = v.ownership || '-';
const detailPhotoContainer = document.getElementById('detailPhotoContainer');
const detailPhoto = document.getElementById('detailPhoto');
if (v.photo_url) {
if (detailPhoto) detailPhoto.src = v.photo_url;
if (detailPhotoContainer) detailPhotoContainer.classList.remove('hidden');
} else {
if (detailPhoto) detailPhoto.src = '';
if (detailPhotoContainer) detailPhotoContainer.classList.add('hidden');
}
const badge = document.getElementById('detailStatusBadge');
if (badge) {
badge.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold border ';
+113 -2
View File
@@ -130,7 +130,18 @@
</td>
<td class="py-3.5 px-4 whitespace-nowrap">
<div class="flex items-center space-x-3">
@if($v->photo_path)
<img src="{{ $v->photo_url }}" alt="{{ $v->code }}" class="w-9 h-9 rounded-lg object-cover border border-slate-200 shadow-2xs flex-shrink-0 cursor-pointer" onclick='openDetailModal(@json($v))'>
@else
<div class="w-9 h-9 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-400 flex-shrink-0">
<i class="fa-solid fa-truck-monster text-xs"></i>
</div>
@endif
<div>
<span class="font-bold text-slate-900 block text-xs">{{ $v->unit_category ?? 'Alat Berat' }}</span>
</div>
</div>
</td>
<td class="py-3.5 px-4 text-center whitespace-nowrap">
@@ -240,10 +251,29 @@
</button>
</div>
<form id="addVehicleForm" action="{{ route('qma.vehicles.store') }}" method="POST" class="space-y-3.5">
<form id="addVehicleForm" action="{{ route('qma.vehicles.store') }}" method="POST" enctype="multipart/form-data" class="space-y-3.5">
@csrf
<input type="hidden" name="category" value="unit_support">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1">Foto Kategori Unit Support (Opsional)</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="addPhotoPreviewContainer" class="w-14 h-14 rounded-xl border-2 border-dashed border-slate-300 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="addPhotoPreview" src="" alt="Pratinjau" class="w-full h-full object-cover hidden">
<i id="addPhotoPlaceholder" class="fa-solid fa-camera text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="addPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewVehicleImage(this, 'addPhotoPreview', 'addPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Format: JPG, PNG, WebP (Maks. 10MB). Resolusi & file dikompresi otomatis.</p>
</div>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1">Kode Kategori <span class="text-rose-500">*</span></label>
@@ -343,10 +373,29 @@
</button>
</div>
<form id="editVehicleForm" action="" method="POST" class="space-y-3.5">
<form id="editVehicleForm" action="" method="POST" enctype="multipart/form-data" class="space-y-3.5">
@csrf
<input type="hidden" name="category" value="unit_support">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Foto Kategori Unit Support</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="editPhotoPreviewContainer" class="w-14 h-14 rounded-xl border border-slate-200 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="editPhotoPreview" src="" alt="Foto Kategori" class="w-full h-full object-cover hidden">
<i id="editPhotoPlaceholder" class="fa-solid fa-truck-monster text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="editPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewVehicleImage(this, 'editPhotoPreview', 'editPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Pilih foto baru jika ingin mengganti. Otomatis dikompresi hemat storage.</p>
</div>
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Kode Kategori <span class="text-rose-500">*</span></label>
@@ -443,6 +492,11 @@
</div>
<div class="space-y-4">
<!-- Foto Kategori di Detail Modal -->
<div id="detailPhotoContainer" class="w-full h-48 rounded-2xl bg-slate-100 border border-slate-200 flex items-center justify-center overflow-hidden relative hidden">
<img id="detailPhoto" src="" alt="Foto Kategori Unit Support" class="w-full h-full object-cover">
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
<div>
<label class="block text-xs font-bold text-slate-800 mb-1.5">Kode Kategori</label>
@@ -794,8 +848,37 @@
});
}
function previewVehicleImage(input, imgId, placeholderId) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById(imgId);
const placeholder = document.getElementById(placeholderId);
if (img) {
img.src = e.target.result;
img.classList.remove('hidden');
}
if (placeholder) {
placeholder.classList.add('hidden');
}
};
reader.readAsDataURL(input.files[0]);
}
}
function openAddModal() {
document.getElementById('addVehicleModal').classList.remove('hidden');
const addPhotoPreview = document.getElementById('addPhotoPreview');
const addPhotoPlaceholder = document.getElementById('addPhotoPlaceholder');
const addPhotoInput = document.getElementById('addPhotoInput');
if (addPhotoInput) addPhotoInput.value = '';
if (addPhotoPreview) {
addPhotoPreview.src = '';
addPhotoPreview.classList.add('hidden');
}
if (addPhotoPlaceholder) {
addPhotoPlaceholder.classList.remove('hidden');
}
if (addCodeInput) addCodeInput.focus();
}
function closeAddModal() {
@@ -836,6 +919,24 @@
}
document.getElementById('editOwnership').value = v.ownership || '';
document.getElementById('editFuelConsumption').value = v.fuel_consumption || '';
const editPhotoPreview = document.getElementById('editPhotoPreview');
const editPhotoPlaceholder = document.getElementById('editPhotoPlaceholder');
const editPhotoInput = document.getElementById('editPhotoInput');
if (editPhotoInput) editPhotoInput.value = '';
if (v.photo_url) {
if (editPhotoPreview) {
editPhotoPreview.src = v.photo_url;
editPhotoPreview.classList.remove('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.add('hidden');
} else {
if (editPhotoPreview) {
editPhotoPreview.src = '';
editPhotoPreview.classList.add('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.remove('hidden');
}
}
function closeEditModal() {
document.getElementById('editVehicleModal').classList.add('hidden');
@@ -853,6 +954,16 @@
document.getElementById('detailDivision').innerText = v.division || '-';
document.getElementById('detailOwnership').innerText = v.ownership || 'PT Kerinci Merangin Hidro';
const detailPhotoContainer = document.getElementById('detailPhotoContainer');
const detailPhoto = document.getElementById('detailPhoto');
if (v.photo_url) {
if (detailPhoto) detailPhoto.src = v.photo_url;
if (detailPhotoContainer) detailPhotoContainer.classList.remove('hidden');
} else {
if (detailPhoto) detailPhoto.src = '';
if (detailPhotoContainer) detailPhotoContainer.classList.add('hidden');
}
const count = v.units_count !== undefined ? v.units_count : 0;
document.getElementById('detailUnitCountText').innerText = count + ' Unit Fisik';
const manageBtn = document.getElementById('detailManageUnitsBtn');
@@ -154,9 +154,18 @@
</td>
<td class="py-3.5 px-4 font-bold text-slate-900 font-mono text-xs whitespace-nowrap">
<div class="flex items-center space-x-2.5">
@if($u->photo_path)
<img src="{{ $u->photo_url }}" alt="{{ $u->code }}" class="w-8 h-8 rounded-lg object-cover border border-slate-200 shadow-2xs flex-shrink-0 cursor-pointer" onclick='openDetailModal(@json($u))'>
@else
<div class="w-8 h-8 rounded-lg bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-400 flex-shrink-0">
<i class="fa-solid fa-truck-pickup text-[10px]"></i>
</div>
@endif
<span class="bg-blue-50 text-blue-800 px-2.5 py-1 rounded-lg border border-blue-200 font-bold">
{{ $u->code }}
</span>
</div>
</td>
<td class="py-3.5 px-4 font-mono text-xs text-slate-700 whitespace-nowrap">
@@ -331,9 +340,28 @@
Tambah Unit Baru
</h3>
<form method="POST" action="{{ route('qma.vehicles.support.units.store', $category->id) }}" id="addUnitForm" class="space-y-4">
<form method="POST" action="{{ route('qma.vehicles.support.units.store', $category->id) }}" id="addUnitForm" enctype="multipart/form-data" class="space-y-4">
@csrf
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">Foto Unit Fisik (Opsional)</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="addPhotoPreviewContainer" class="w-14 h-14 rounded-xl border-2 border-dashed border-slate-300 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="addPhotoPreview" src="" alt="Pratinjau" class="w-full h-full object-cover hidden">
<i id="addPhotoPlaceholder" class="fa-solid fa-camera text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="addPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewUnitImage(this, 'addPhotoPreview', 'addPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Format: JPG, PNG, WebP (Maks. 10MB). Resolusi otomatis dikompresi hemat storage.</p>
</div>
</div>
</div>
<!-- Aset Induk (Readonly) Sesuai Mockup -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">
@@ -495,11 +523,30 @@
<h3 class="text-xl font-extrabold text-slate-900 tracking-tight mb-5">
Edit Data Unit Fisik
</h3>
<form id="editUnitForm" method="POST" action="" class="space-y-4">
<form id="editUnitForm" method="POST" action="" enctype="multipart/form-data" class="space-y-4">
@csrf
<input type="hidden" name="category" value="unit_support">
<input type="hidden" name="brand_type" id="edit_brand_type">
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">Foto Unit Fisik</label>
<div class="flex items-center space-x-3.5 p-3 rounded-2xl border border-slate-200 bg-slate-50/50">
<div id="editPhotoPreviewContainer" class="w-14 h-14 rounded-xl border border-slate-200 bg-white flex items-center justify-center overflow-hidden flex-shrink-0 shadow-2xs">
<img id="editPhotoPreview" src="" alt="Foto Unit" class="w-full h-full object-cover hidden">
<i id="editPhotoPlaceholder" class="fa-solid fa-truck-pickup text-slate-400 text-base"></i>
</div>
<div class="flex-1 min-w-0">
<input type="file"
name="photo"
id="editPhotoInput"
accept="image/jpeg,image/png,image/jpg,image/webp"
onchange="previewUnitImage(this, 'editPhotoPreview', 'editPhotoPlaceholder')"
class="block w-full text-xs text-slate-500 file:mr-3 file:py-1.5 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-bold file:bg-emerald-50 file:text-[#1b5e20] hover:file:bg-emerald-100 cursor-pointer">
<p class="text-[10px] text-slate-400 mt-1">Pilih foto baru jika ingin mengganti. Otomatis dikompresi hemat storage.</p>
</div>
</div>
</div>
<div>
<label class="block text-xs font-bold text-slate-700 mb-1.5">Kode Unit <span class="text-rose-500">*</span></label>
<input type="text" name="code" id="edit_code" required class="w-full text-xs px-3.5 py-2 rounded-xl border border-slate-200 bg-slate-100 text-slate-700 font-mono font-bold focus:outline-none" readonly>
@@ -589,6 +636,11 @@
</div>
<div class="py-4 space-y-3 text-xs">
<!-- Foto Unit Fisik di Detail Modal -->
<div id="detail_photo_container" class="w-full h-44 rounded-2xl bg-slate-100 border border-slate-200 flex items-center justify-center overflow-hidden relative hidden mb-3">
<img id="detail_photo" src="" alt="Foto Unit Fisik" class="w-full h-full object-cover">
</div>
<div class="flex justify-between py-1.5 border-b border-slate-50">
<span class="text-slate-400">Kategori Induk:</span>
<span class="font-bold text-slate-800">{{ $category->code }} - {{ $category->unit_category }}</span>
@@ -675,8 +727,37 @@
<script>
const categoryCode = "{{ $category->code }}";
function previewUnitImage(input, imgId, placeholderId) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById(imgId);
const placeholder = document.getElementById(placeholderId);
if (img) {
img.src = e.target.result;
img.classList.remove('hidden');
}
if (placeholder) {
placeholder.classList.add('hidden');
}
};
reader.readAsDataURL(input.files[0]);
}
}
function openAddUnitModal() {
document.getElementById('addUnitModal').classList.remove('hidden');
const addPhotoPreview = document.getElementById('addPhotoPreview');
const addPhotoPlaceholder = document.getElementById('addPhotoPlaceholder');
const addPhotoInput = document.getElementById('addPhotoInput');
if (addPhotoInput) addPhotoInput.value = '';
if (addPhotoPreview) {
addPhotoPreview.src = '';
addPhotoPreview.classList.add('hidden');
}
if (addPhotoPlaceholder) {
addPhotoPlaceholder.classList.remove('hidden');
}
document.getElementById('unitNumberInput').focus();
}
@@ -722,6 +803,24 @@
document.getElementById('edit_silo').value = unit.silo_document || '';
document.getElementById('edit_kir').value = unit.kir_document || '';
const editPhotoPreview = document.getElementById('editPhotoPreview');
const editPhotoPlaceholder = document.getElementById('editPhotoPlaceholder');
const editPhotoInput = document.getElementById('editPhotoInput');
if (editPhotoInput) editPhotoInput.value = '';
if (unit.photo_url) {
if (editPhotoPreview) {
editPhotoPreview.src = unit.photo_url;
editPhotoPreview.classList.remove('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.add('hidden');
} else {
if (editPhotoPreview) {
editPhotoPreview.src = '';
editPhotoPreview.classList.add('hidden');
}
if (editPhotoPlaceholder) editPhotoPlaceholder.classList.remove('hidden');
}
document.getElementById('editModal').classList.remove('hidden');
}
@@ -740,6 +839,16 @@
document.getElementById('detail_silo').textContent = unit.silo_document || 'Tidak ada';
document.getElementById('detail_kir').textContent = unit.kir_document || 'Tidak ada';
const detailPhotoContainer = document.getElementById('detail_photo_container');
const detailPhoto = document.getElementById('detail_photo');
if (unit.photo_url) {
if (detailPhoto) detailPhoto.src = unit.photo_url;
if (detailPhotoContainer) detailPhotoContainer.classList.remove('hidden');
} else {
if (detailPhoto) detailPhoto.src = '';
if (detailPhotoContainer) detailPhotoContainer.classList.add('hidden');
}
document.getElementById('detailModal').classList.remove('hidden');
}
@@ -0,0 +1,256 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\User;
use App\Models\Vehicle;
use Database\Seeders\RolePermissionSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PhotoUploadAndCompressionTest extends TestCase
{
use RefreshDatabase;
protected User $adminQma;
protected User $adminHse;
protected function setUp(): void
{
parent::setUp();
$this->seed(RolePermissionSeeder::class);
$this->adminQma = User::factory()->create([
'username' => 'admin_qma',
'role' => 'qma_admin',
]);
$this->adminQma->assignRole('qma_admin');
$this->adminHse = User::factory()->create([
'username' => 'admin_hse',
'role' => 'hse_admin',
]);
$this->adminHse->assignRole('hse_admin');
}
public function test_admin_qma_can_upload_and_compress_lv_photo(): void
{
Storage::fake('public');
// Simulasi foto mentah resolusi tinggi dari kamera (1600x1200)
$file = UploadedFile::fake()->image('hilux.png', 1600, 1200);
$response = $this->actingAs($this->adminQma)->post(route('qma.vehicles.store'), [
'code' => 'LV-99',
'category' => 'light_vehicle',
'brand_type' => 'Toyota Hilux 4x4 Double Cabin',
'license_plate' => 'BH 9999 XX',
'division' => 'HSE',
'ownership' => 'PT Kerinci Merangin Hidro',
'status' => 'Operation',
'current_km' => 1500,
'photo' => $file,
]);
$response->assertRedirect();
$this->assertDatabaseHas('vehicles', [
'code' => 'LV-99',
'category' => 'light_vehicle',
]);
$vehicle = Vehicle::where('code', 'LV-99')->firstOrFail();
$this->assertNotNull($vehicle->photo_path);
Storage::disk('public')->assertExists($vehicle->photo_path);
// Verifikasi resolusi gambar telah dikompresi proporsional (max 800x800)
$savedContent = Storage::disk('public')->get($vehicle->photo_path);
$imageResource = @imagecreatefromstring($savedContent);
$this->assertNotFalse($imageResource);
$this->assertLessThanOrEqual(800, imagesx($imageResource));
$this->assertLessThanOrEqual(800, imagesy($imageResource));
imagedestroy($imageResource);
}
public function test_updating_lv_photo_replaces_and_deletes_old_photo(): void
{
Storage::fake('public');
$oldFile = UploadedFile::fake()->image('old_car.png', 1000, 1000);
$this->actingAs($this->adminQma)->post(route('qma.vehicles.store'), [
'code' => 'LV-88',
'category' => 'light_vehicle',
'brand_type' => 'Mitsubishi Triton',
'license_plate' => 'BH 8888 XX',
'status' => 'Operation',
'current_km' => 2000,
'photo' => $oldFile,
]);
$vehicle = Vehicle::where('code', 'LV-88')->firstOrFail();
$oldPath = $vehicle->photo_path;
Storage::disk('public')->assertExists($oldPath);
// Update dengan foto baru
$newFile = UploadedFile::fake()->image('new_car.png', 1200, 800);
$updateResponse = $this->actingAs($this->adminQma)->post(route('qma.vehicles.update', $vehicle->id), [
'code' => 'LV-88',
'category' => 'light_vehicle',
'brand_type' => 'Mitsubishi Triton Ultimate',
'license_plate' => 'BH 8888 XX',
'status' => 'Standby',
'current_km' => 2500,
'photo' => $newFile,
]);
$updateResponse->assertRedirect();
$vehicle->refresh();
$newPath = $vehicle->photo_path;
$this->assertNotEquals($oldPath, $newPath);
Storage::disk('public')->assertMissing($oldPath);
Storage::disk('public')->assertExists($newPath);
}
public function test_deleting_vehicle_deletes_its_photo_from_storage(): void
{
Storage::fake('public');
$file = UploadedFile::fake()->image('car_to_delete.png', 800, 600);
$this->actingAs($this->adminQma)->post(route('qma.vehicles.store'), [
'code' => 'LV-DEL',
'category' => 'light_vehicle',
'brand_type' => 'Isuzu D-Max',
'status' => 'Standby',
'current_km' => 500,
'photo' => $file,
]);
$vehicle = Vehicle::where('code', 'LV-DEL')->firstOrFail();
$photoPath = $vehicle->photo_path;
Storage::disk('public')->assertExists($photoPath);
$deleteResponse = $this->actingAs($this->adminQma)->delete(route('qma.vehicles.destroy', $vehicle->id));
$deleteResponse->assertRedirect();
$this->assertDatabaseMissing('vehicles', ['id' => $vehicle->id]);
Storage::disk('public')->assertMissing($photoPath);
}
public function test_admin_qma_can_upload_photo_for_support_unit(): void
{
Storage::fake('public');
// Buat kategori Unit Support terlebih dahulu
$category = Vehicle::create([
'code' => 'EX01',
'category' => 'unit_support',
'brand_type' => 'Komatsu PC200-8',
'unit_category' => 'Excavator',
'status' => 'Operation',
'current_km' => 0,
]);
$file = UploadedFile::fake()->image('excavator.png', 1500, 1000);
$response = $this->actingAs($this->adminQma)->post(route('qma.vehicles.support.units.store', $category->id), [
'unit_number' => '001',
'serial_number' => 'SN-EXC-999',
'status' => 'Operation',
'current_km' => 120,
'location' => 'Main Dam',
'photo' => $file,
]);
$response->assertRedirect();
$unit = Vehicle::where('code', 'EX01-001')->firstOrFail();
$this->assertNotNull($unit->photo_path);
Storage::disk('public')->assertExists($unit->photo_path);
$savedContent = Storage::disk('public')->get($unit->photo_path);
$imageResource = @imagecreatefromstring($savedContent);
$this->assertNotFalse($imageResource);
$this->assertLessThanOrEqual(800, imagesx($imageResource));
$this->assertLessThanOrEqual(800, imagesy($imageResource));
imagedestroy($imageResource);
}
public function test_admin_hse_can_upload_and_compress_employee_photo(): void
{
Storage::fake('public');
// Simulasi foto avatar mentah ukuran 1200x1200
$file = UploadedFile::fake()->image('profile.png', 1200, 1200);
$response = $this->actingAs($this->adminHse)->post(route('hse.employees.store'), [
'nik' => 'KMH-PHOTO-01',
'name' => 'Budi Santoso',
'unit_kerja' => 'Pembangkit',
'division' => 'Operasi',
'position' => 'Driver Operasional',
'is_operator' => '1',
'simper_expired_at' => now()->addYear()->toDateString(),
'photo' => $file,
]);
$response->assertRedirect();
$this->assertDatabaseHas('employees', [
'nik' => 'KMH-PHOTO-01',
'name' => 'Budi Santoso',
]);
$employee = Employee::where('nik', 'KMH-PHOTO-01')->firstOrFail();
$this->assertNotNull($employee->photo_path);
Storage::disk('public')->assertExists($employee->photo_path);
// Verifikasi resolusi avatar dikompresi proporsional (max 500x500 untuk avatar)
$savedContent = Storage::disk('public')->get($employee->photo_path);
$imageResource = @imagecreatefromstring($savedContent);
$this->assertNotFalse($imageResource);
$this->assertLessThanOrEqual(500, imagesx($imageResource));
$this->assertLessThanOrEqual(500, imagesy($imageResource));
imagedestroy($imageResource);
}
public function test_updating_employee_photo_replaces_and_deletes_old_photo(): void
{
Storage::fake('public');
$oldFile = UploadedFile::fake()->image('old_avatar.png', 600, 600);
$this->actingAs($this->adminHse)->post(route('hse.employees.store'), [
'nik' => 'KMH-PHOTO-02',
'name' => 'Dewi Lestari',
'unit_kerja' => 'Umum',
'division' => 'Keuangan',
'position' => 'Staff Finance',
'is_operator' => '0',
'photo' => $oldFile,
]);
$employee = Employee::where('nik', 'KMH-PHOTO-02')->firstOrFail();
$oldPath = $employee->photo_path;
Storage::disk('public')->assertExists($oldPath);
// Update dengan avatar baru
$newFile = UploadedFile::fake()->image('new_avatar.png', 800, 800);
$updateResponse = $this->actingAs($this->adminHse)->post(route('hse.employees.update', $employee->id), [
'nik' => 'KMH-PHOTO-02',
'name' => 'Dewi Lestari, S.E.',
'unit_kerja' => 'Umum',
'division' => 'Keuangan',
'position' => 'Senior Staff Finance',
'is_operator' => '0',
'photo' => $newFile,
]);
$updateResponse->assertRedirect();
$employee->refresh();
$newPath = $employee->photo_path;
$this->assertNotEquals($oldPath, $newPath);
Storage::disk('public')->assertMissing($oldPath);
Storage::disk('public')->assertExists($newPath);
}
}