perbaikan upload foto

This commit is contained in:
majid
2025-02-05 13:27:21 +07:00
parent edb5a65fbf
commit 97ad08bc56
6 changed files with 459 additions and 958 deletions

View File

@@ -339,18 +339,6 @@ class SurveyorController extends Controller
{
$validatedData = $this->validateFotoRequest($request);
try {
$log = [];
$photoCategories = [
'rute_menuju_lokasi',
'foto_lingkungan',
];
$lainnya = [
'foto_rute_lainnya' => ['foto_rute_lainnya', 'name_rute_lainnya'],
'foto_lantai_lainnya' => ['foto_lantai_lainnya', 'name_lantai_lainnya']
];
$inspeksi = Inspeksi::firstOrNew([
'permohonan_id' => $request->input('permohonan_id'),
'dokument_id' => $request->input('dokument_id')
@@ -363,48 +351,7 @@ class SurveyorController extends Controller
$formatFotojson = $existingData;
// Upload berbagai jenis foto
$this->handleFileUpload($request, 'rute_menuju_lokasi', $formatFotojson);
$this->handleFileUpload($request, 'foto_lingkungan', $formatFotojson);
$this->processFotoLantaiUnit($request, $formatFotojson);
if ($request->hasFile('foto_objek')) {
$existingObjekJaminan = $formatFotojson['object_jaminan'] ?? [];
$formatFotojson['object_jaminan'] = $this->processObjekJaminanPhotos(
$request,
$existingObjekJaminan
);
}
foreach ($lainnya as $category => $fields) {
$photoField = $fields[0];
$nameField = $fields[1];
$descriptionField = $fields[2] ?? null;
if ($request->hasFile($photoField)) {
$newPhotos = $this->processPhotoLainnya(
$request,
$fields,
$existingData[$category] ?? []
);
$formatFotojson[$category] = $newPhotos;
}
}
// // Process single files
$singleFiles = ['foto_basement', 'foto_gerbang', 'pendamping'];
foreach ($singleFiles as $file) {
if ($request->hasFile($file)) {
// Hapus file lama jika ada
if (isset($formatFotojson[$file])) {
$this->deleteOfFile($formatFotojson[$file]);
}
// Upload dan simpan file baru
$formatFotojson[$file] = $this->uploadFile($request->file($file), $file);
}
}
$this->handleFileUploadBaru($request, 'rute_menuju_lokasi', $formatFotojson);
// Update record
if (!empty($formatFotojson)) {
@@ -414,8 +361,7 @@ class SurveyorController extends Controller
return response()->json([
'success' => true,
'message' => 'Data berhasil disimpan',
'data' => $formatFotojson,
'log' => $log
'data' => $formatFotojson
], 200);
}
@@ -428,77 +374,95 @@ class SurveyorController extends Controller
}
}
/**
* Process a photo
*/
protected function processFotoLantaiUnit(Request $request, &$formatFotojson)
public function updateFoto(Request $request)
{
// Pastikan foto_lantai_unit sudah ada di formatFotojson
if (!isset($formatFotojson['foto_lantai_unit'])) {
$formatFotojson['foto_lantai_unit'] = [];
}
try {
// Validasi input
$validated = $request->validate([
'permohonan_id' => 'required',
'dokument_id' => 'required|string',
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'category' => 'required|string|max:255',
'sub' => 'nullable|string|max:255',
'path' => 'nullable|string',
]);
// Ambil nama-nama lantai dari request
$lantaiNama = $request->input('lantai_nama', []);
$inspeksi = Inspeksi::firstOrNew([
'permohonan_id' => $validated['permohonan_id'],
'dokument_id' => $validated['dokument_id'],
]);
// Tambahan: gunakan lantai_index jika tersedia
$lantaiIndex = $request->input('lantai_index', null);
$cleanRequestPath = str_replace('/storage/', '', $validated['path']);
// Cek apakah ada file foto lantai yang diunggah
$lantaiFiles = $request->file('foto_lantai_unit', []);
$fotoForm = json_decode($inspeksi->foto_form, true) ?? [];
// Proses setiap file foto lantai
foreach ($lantaiFiles as $index => $files) {
// Pastikan $files adalah array
if (!is_array($files)) {
$files = [$files];
if (!isset($fotoForm['rute_menuju_lokasi'])) {
$fotoForm['rute_menuju_lokasi'] = [];
}
// Gunakan lantai_index jika tersedia, jika tidak gunakan cara sebelumnya
$lantaiNomor = $lantaiIndex ?? ($index + 1);
// Inisialisasi array untuk lantai ini jika belum ada
if (!isset($formatFotojson['foto_lantai_unit'][$lantaiNomor])) {
$formatFotojson['foto_lantai_unit'][$lantaiNomor] = [];
}
foreach ($files as $fileIndex => $file) {
// Validasi file
if (!$file->isValid()) {
continue; // Lewati file yang tidak valid
$existingIndex = null;
if (!empty($validated['path'])) {
foreach ($fotoForm['rute_menuju_lokasi'] as $index => $foto) {
if ($foto['path'] === $cleanRequestPath) {
$existingIndex = $index;
break;
}
}
// Generate nama file unik
$uniqueFileName = 'lantai_unit_' . $lantaiNomor . '_' . $fileIndex . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
// Simpan file dengan nama asli
$path = $file->storeAs(
'surveyor/lantai_unit',
$uniqueFileName . '/' . time() . '_' . $file->getClientOriginalName(),
'public'
);
// Buat nama foto
$fotoName = "Foto Lantai {$lantaiNomor} - " . ($fileIndex + 1);
// Tambahkan detail foto ke array
$fotoDetail = [
'path' => $path,
'name' => $fotoName
];
// Tambahkan ke array foto lantai unit sesuai struktur
$formatFotojson['foto_lantai_unit'][$lantaiNomor][] = $fotoDetail;
}
}
return $formatFotojson;
// Siapkan data baru
$newFotoData = [
'name' => $validated['name'],
'description' => $validated['description'],
'category' => $validated['category'],
'sub' => $validated['sub'],
'path' => $cleanRequestPath,
'created_by' => Auth::user()->name,
'created_at' => now()->toDateTimeString(),
'updated_by' => Auth::user()->name,
'updated_at' => now()->toDateTimeString(),
];
if ($existingIndex !== null) {
$existingFoto = $fotoForm['rute_menuju_lokasi'][$existingIndex];
$fotoForm['rute_menuju_lokasi'][$existingIndex] = [
'name' => $validated['name'],
'description' => $validated['description'],
'category' => $validated['category'],
'sub' => $validated['sub'],
'path' => $cleanRequestPath,
'created_by' => $existingFoto['created_by'] ?? Auth::user()->name,
'created_at' => $existingFoto['created_at'] ?? now()->toDateTimeString(),
'updated_by' => Auth::user()->name,
'updated_at' => now()->toDateTimeString(),
];
} else {
$fotoForm['rute_menuju_lokasi'][] = $newFotoData;
}
// Simpan kembali data ke database
$inspeksi->foto_form = json_encode($fotoForm);
$inspeksi->save();
return response()->json([
'success' => true,
'message' => 'Data berhasil diperbarui.',
], 200);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal memperbarui data: ' . $e->getMessage(),
], 500);
}
}
private function handleFileUpload(Request $request, $paramName, &$formatFotojson)
private function handleFileUploadBaru(Request $request, $paramName, &$formatFotojson)
{
if ($request->hasFile($paramName)) {
$files = $request->file($paramName);
@@ -509,45 +473,54 @@ class SurveyorController extends Controller
}
$formatFotoData = [];
$nomor_registrasi = $request->nomor_registrasi;
foreach ($files as $index => $file) {
$timestamp = time();
$originalName = $file->getClientOriginalName();
$uniqueFileName = "{$timestamp}_{$originalName}";
$extension = $file->getClientOriginalExtension();
// Validasi nama file
if (empty($originalName)) {
$originalName = "file_{$timestamp}";
}
$uniqueFileName = "{$timestamp}.{$extension}";
// Simpan file
$path = $file->storeAs("surveyor/{$paramName}", $uniqueFileName, 'public');
$nomor_registrasi = $request->nomor_registrasi;
$path = $file->storeAs("surveyor/{$paramName}/{$nomor_registrasi}", $uniqueFileName, 'public');
$fotoData = [
'name' => pathinfo($originalName, PATHINFO_FILENAME),
'path' => $path,
'name' => ucwords(str_replace('_', ' ', $paramName)) . ' - ' . ($index + 1)
'category' => 'lainnya',
'sub' => null,
'description' => null,
'created_by' => Auth::user()->name,
'created_at' => now()->toDateTimeString(),
];
$formatFotoData[] = $fotoData;
}
// Struktur JSON yang konsisten
if (!isset($formatFotojson[$paramName][$paramName][0])) {
$formatFotojson[$paramName] = [
$paramName => [
$formatFotoData
]
];
if (!isset($formatFotojson[$paramName])) {
$formatFotojson[$paramName] = $formatFotoData;
} else {
$formatFotojson[$paramName][$paramName][0] = array_merge(
$formatFotojson[$paramName][$paramName][0] ?? [],
$formatFotojson[$paramName] = array_merge(
$formatFotojson[$paramName] ?? [],
$formatFotoData
);
}
return $formatFotoData;
}
return [];
}
public function hapusFoto(Request $request)
{
try {
@@ -562,39 +535,35 @@ class SurveyorController extends Controller
);
$fotoForm = json_decode($inspeksi->foto_form, true);
if (isset($fotoForm[$paramName][$paramName][0])) {
// Filter foto yang akan dihapus
$tes = null;
$fotoForm[$paramName][$paramName][0] = array_values(
array_filter(
$fotoForm[$paramName][$paramName][0],
function ($foto) use ($cleanRequestPath) {
if ($foto['path'] === $cleanRequestPath) {
// Hapus file dari storage
\Storage::disk('public')->delete($cleanRequestPath);
return false; // Hapus elemen ini dari array
}
$tes = $foto['path'];
return true;
if (isset($fotoForm[$paramName]) && is_array($fotoForm[$paramName])) {
// Filter foto yang tidak sesuai dengan path yang akan dihapus
$fotoForm[$paramName] = array_values(array_filter(
$fotoForm[$paramName],
function ($foto) use ($cleanRequestPath) {
if ($foto['path'] === $cleanRequestPath) {
// Hapus file dari storage
\Storage::disk('public')->delete($cleanRequestPath);
return false;
}
)
);
return true;
}
));
// Reset array index
$fotoForm[$paramName][$paramName][0] = array_values($fotoForm[$paramName][$paramName][0]);
$inspeksi->foto_form = $fotoForm;
// Simpan kembali data ke database
$inspeksi->foto_form = json_encode($fotoForm);
$inspeksi->save();
return response()->json([
'success' => true,
'message' => 'Foto berhasil dihapus',
'message' => 'Foto berhasil dihapus',
], 200);
}
return response()->json(['success' => false], 400);
// Jika parameter tidak ditemukan
return response()->json([
'success' => false,
'message' => 'Foto atau parameter tidak ditemukan',
], 400);
} catch (\Exception $e) {
return response()->json([
'success' => false,
@@ -621,37 +590,32 @@ class SurveyorController extends Controller
$fotos = $this->findFotoByParamName($fotoForm, $paramName);
$param = $paramName == 'rute_menuju_lokasi' ? $fotos['rute_menuju_lokasi'][0] : $fotos['foto_lingkungan'][0];
$data = array_map(function ($foto) {
return [
'name' => $foto['name'] ?? 'Foto',
'path' => \Storage::url($foto['path']),
'path' => \Storage::url($foto['path'] ?? ''),
'category' => $foto['category'] ?? 'lainnya',
'sub' => $foto['sub'] ?? null,
'description' => $foto['description'] ?? null,
'upload_by' => $foto['upload_by'] ?? null,
];
}, $param);
}, $fotos);
return response()->json([
'fotos' => $data,
'success' => !empty($data)
'success' => !empty($data),
]);
}
private function findFotoByParamName($fotoForm, $paramName)
{
// Mapping parameter name ke struktur JSON
$paramMapping = [
'rute_menuju_lokasi' => ['rute_menuju_lokasi'],
'foto_lingkungan' => ['foto_lingkungan'],
];
// // Traverse array menggunakan mapping
$fotos = $fotoForm;
if (isset($paramMapping[$paramName])) {
foreach ($paramMapping[$paramName] as $key) {
$fotos = $fotos[$key] ?? [];
}
if (isset($fotoForm[$paramName]) && is_array($fotoForm[$paramName])) {
return $fotoForm[$paramName]; // Kembalikan array foto jika ditemukan
}
return is_array($fotos) ? $fotos : [];
// Jika parameter tidak ditemukan atau bukan array, kembalikan array kosong
return [];
}
@@ -783,38 +747,7 @@ class SurveyorController extends Controller
], 404);
}
private function processPhotoLainnya(Request $request, array $fields, array $existingPhotos = [])
{
$result = $existingPhotos; // Start with existing photos
$photoField = $fields[0];
$nameField = $fields[1];
$descriptionField = $fields[2] ?? null;
if ($request->hasFile($photoField)) {
$newFiles = $request->file($photoField, []);
$newNames = $request->input($nameField, []);
$newDescriptions = $descriptionField ? $request->input($descriptionField, []) : [];
// Process each new file
foreach ($newFiles as $key => $file) {
// Create new photo entry
$newPhotoEntry = [
$nameField => $newNames[$key] ?? '', // Use new name if provided
$photoField => $this->uploadFile($file, $photoField . '.' . $key)
];
// Add description if field exists
if ($descriptionField) {
$newPhotoEntry[$descriptionField] = $newDescriptions[$key] ?? '';
}
// Add to result
$result[] = $newPhotoEntry;
}
}
return $result;
}
private function generateUniqueFileName($file, $prefix = '')
{
@@ -838,27 +771,8 @@ class SurveyorController extends Controller
return $request->validate([
'permohonan_id' => 'required',
'dokument_id' => 'required',
'pendamping' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'foto_objek.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_objek.*' => 'required|string|max:255',
'name_lingkungan.*' => 'required|string|max:255',
'nomor_registrasi' => 'required',
'foto_rute.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_rute.*' => 'required|string|max:255',
'lantai.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_rute_lainnya.*' => 'nullable|string',
'foto_rute_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'foto_lantai_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_lantai_lainnya.*' => 'nullable|string|max:255',
'foto_basement.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_basement.*' => 'nullable|string|max:255',
'foto_gerbang' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize,
'name_gerbang' => 'nullable|string|max:255',
'name_lantai_unit' => 'array',
]);
}
@@ -1708,6 +1622,7 @@ class SurveyorController extends Controller
$permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId);
$surveyor = $id;
$branches = Branch::all();
$provinces = Province::all();
@@ -2343,7 +2258,8 @@ class SurveyorController extends Controller
'perkerasanJalan' => PerkerasanJalan::all(),
'terletakDiArea' => TerletakArea::all(),
'tujuanPenilaian' => TujuanPenilaian::all(),
'perizinan' => Perizinan::all()
'perizinan' => Perizinan::all(),
'foto' => FotoObjekJaminan::all()
];
}