From 721abb56c25cd3587cf64d907566b3d0d2d77e03 Mon Sep 17 00:00:00 2001 From: Ray1111-aa Date: Fri, 30 Oct 2026 10:01:54 +0700 Subject: [PATCH] refactor(backup): remove internal reader to keep main application completely clean and decoupled --- .../Commands/InspectKmhBackupCommand.php | 112 ----- .../Controllers/Admin/BackupController.php | 70 --- app/Services/DatabaseBackupService.php | 240 ---------- resources/views/admin/backups/index.blade.php | 414 ------------------ routes/web.php | 2 - tests/Feature/BackupAndRestoreTest.php | 56 --- 6 files changed, 894 deletions(-) delete mode 100644 app/Console/Commands/InspectKmhBackupCommand.php diff --git a/app/Console/Commands/InspectKmhBackupCommand.php b/app/Console/Commands/InspectKmhBackupCommand.php deleted file mode 100644 index d8aa8b3..0000000 --- a/app/Console/Commands/InspectKmhBackupCommand.php +++ /dev/null @@ -1,112 +0,0 @@ -argument('file'); - $backupDir = $service->getBackupDirectory(); - - if (!$input) { - $files = collect(File::glob($backupDir . '/*.kmh')) - ->map(fn($f) => basename($f)) - ->values() - ->all(); - - if (empty($files)) { - $this->warn("Tidak ada file .kmh di direktori backup ({$backupDir})."); - $this->line("Gunakan: php artisan kmh:inspect /path/ke/file.kmh"); - return Command::FAILURE; - } - - $input = $this->choice('Pilih file .kmh yang ingin diinspeksi:', $files); - } - - // Tentukan path lengkap - $targetPath = File::exists($input) - ? $input - : $backupDir . DIRECTORY_SEPARATOR . basename($input); - - if (!File::exists($targetPath)) { - $this->error("Berkas .kmh tidak ditemukan pada: {$targetPath}"); - return Command::FAILURE; - } - - $this->info("Sedang memeriksa & membaca arsip: " . basename($targetPath) . " ..."); - - try { - $data = $service->inspectKmhFile($targetPath); - - $this->newLine(); - $this->line("====================================================================="); - $this->info(" HASIL INSPEKSI ARSIP KMH (RKM BACKUP READER)"); - $this->line("====================================================================="); - - $this->table( - ['Parameter', 'Keterangan'], - [ - ['Nama File', $data['filename']], - ['Ukuran Berkas', $data['file_size_human'] . " ({$data['file_size']} bytes)"], - ['Format Arsip', $data['format']], - ['Sistem Asal', $data['system']], - ['Waktu Pembuatan', $data['created_at_human'] . " ({$data['created_at_diff']})"], - ['Tipe Backup', $data['type_label']], - ['Database Asal', $data['database']], - ['Enkripsi & Keamanan', $data['encryption_cipher'] . ' (' . $data['hmac_verification'] . ')'], - ['Ukuran SQL Database', $data['sql_size_human']], - ['File Media (storage/)', $data['has_media'] ? "{$data['media_file_count']} berkas media" : 'Tidak disertakan'], - ['Versi Environment', "Laravel {$data['laravel_version']} / PHP {$data['php_version']}"], - ] - ); - - if (!empty($data['tables'])) { - $this->newLine(); - $this->comment(" Daftar Tabel & Jumlah Baris Data (" . count($data['tables']) . " tabel):"); - $formattedTables = array_map(function ($t) use ($data) { - $rows = $data['table_details'][$t]['rows_count'] ?? 0; - return "{$t} ({$rows} baris)"; - }, $data['tables']); - - $chunks = array_chunk($formattedTables, 3); - $rows = array_map(function ($chunk) { - return array_pad($chunk, 3, ''); - }, $chunks); - $this->table(['Tabel & Baris', 'Tabel & Baris', 'Tabel & Baris'], $rows); - } - - if (!empty($data['media_samples'])) { - $this->newLine(); - $this->comment(" Sampel Berkas Media:"); - foreach ($data['media_samples'] as $sample) { - $this->line(" - {$sample}"); - } - } - - $this->newLine(); - $this->info("✓ Berkas sah, terenkripsi valid, dan siap dipulihkan jika diperlukan."); - $this->line("====================================================================="); - - return Command::SUCCESS; - } catch (\Throwable $e) { - $this->error("Gagal membaca arsip .kmh: " . $e->getMessage()); - return Command::FAILURE; - } - } -} diff --git a/app/Http/Controllers/Admin/BackupController.php b/app/Http/Controllers/Admin/BackupController.php index 0d95870..465500d 100644 --- a/app/Http/Controllers/Admin/BackupController.php +++ b/app/Http/Controllers/Admin/BackupController.php @@ -6,7 +6,6 @@ use App\Http\Controllers\Controller; use App\Models\AdminActivityLog; use App\Models\BackupLog; use App\Services\DatabaseBackupService; -use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Artisan; @@ -383,75 +382,6 @@ class BackupController extends Controller } } - /** - * Inspeksi dan baca metadata isi file .kmh yang sudah ada di penyimpanan server. - */ - public function inspect(string $filename): JsonResponse - { - $filename = basename($filename); - $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; - - if (!File::exists($fullPath)) { - return response()->json([ - 'success' => false, - 'message' => "Berkas backup '{$filename}' tidak ditemukan di penyimpanan server VPS.", - ], 404); - } - - try { - $data = $this->backupService->inspectKmhFile($fullPath); - return response()->json([ - 'success' => true, - 'data' => $data, - ]); - } catch (\Throwable $e) { - return response()->json([ - 'success' => false, - 'message' => $e->getMessage(), - ], 422); - } - } - - /** - * Inspeksi dan baca metadata isi file .kmh yang diunggah dari komputer lokal. - * File sementara langsung dihapus otomatis setelah dibaca (Zero Storage Retention). - */ - public function inspectUpload(Request $request): JsonResponse - { - $request->validate([ - 'backup_file' => ['required', 'file', 'max:512000'], - ], [ - 'backup_file.required' => 'Pilih atau letakkan berkas file .kmh yang ingin dibaca.', - 'backup_file.file' => 'Berkas yang diunggah tidak valid.', - 'backup_file.max' => 'Ukuran file melebihi batas maksimal upload 500 MB.', - ]); - - $uploaded = $request->file('backup_file'); - $tempPath = tempnam(sys_get_temp_dir(), 'kmh_upload_inspect_'); - - try { - $uploaded->move(dirname($tempPath), basename($tempPath)); - - $data = $this->backupService->inspectKmhFile($tempPath); - // Ganti nama file dengan nama asli dari komputer pengguna - $data['filename'] = $uploaded->getClientOriginalName(); - - return response()->json([ - 'success' => true, - 'data' => $data, - ]); - } catch (\Throwable $e) { - return response()->json([ - 'success' => false, - 'message' => $e->getMessage(), - ], 422); - } finally { - if (is_file($tempPath)) { - @unlink($tempPath); - } - } - } - /** * Hapus file backup dari penyimpanan server untuk menghemat kapasitas disk VPS. * Riwayat log backup tetap tersimpan di sistem. diff --git a/app/Services/DatabaseBackupService.php b/app/Services/DatabaseBackupService.php index 6802bd4..b8302f8 100644 --- a/app/Services/DatabaseBackupService.php +++ b/app/Services/DatabaseBackupService.php @@ -203,43 +203,6 @@ class DatabaseBackupService } } - // Kumpulkan statistik tabel dan sampel data untuk pratinjau instan di manifest - $tableDetails = []; - foreach ($targetTables as $tableName) { - try { - $q = DB::table($tableName); - if (Schema::hasColumn($tableName, 'deleted_at')) { - $q->whereNull('deleted_at'); - } - $totalRows = $q->count(); - $samples = $q->limit(5)->get()->map(function ($row) { - $arr = (array) $row; - foreach (['password', 'remember_token', 'two_factor_secret'] as $secret) { - if (isset($arr[$secret])) { - $arr[$secret] = '••••••••'; - } - } - return $arr; - })->all(); - - $cols = !empty($samples) ? array_keys($samples[0]) : (Schema::hasTable($tableName) ? Schema::getColumnListing($tableName) : []); - - $tableDetails[$tableName] = [ - 'name' => $tableName, - 'rows_count' => $totalRows, - 'columns' => $cols, - 'samples' => $samples, - ]; - } catch (\Throwable $e) { - $tableDetails[$tableName] = [ - 'name' => $tableName, - 'rows_count' => 0, - 'columns' => [], - 'samples' => [], - ]; - } - } - // Manifest informasi arsip .kmh $manifest = [ 'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)', @@ -249,7 +212,6 @@ class DatabaseBackupService 'database' => $database, 'table_count' => count($targetTables), 'tables' => $targetTables, - 'table_details' => $tableDetails, 'has_media' => $includeMedia, 'laravel_version' => app()->version(), 'php_version' => PHP_VERSION, @@ -275,208 +237,6 @@ class DatabaseBackupService } } - /** - * Inspeksi dan baca metadata isi file arsip .kmh tanpa melakukan restore atau manipulasi database. - * Mengembalikan manifest, daftar tabel terarsip, metrik data, dan status integritas enkripsi. - * - * @return array - */ - public function inspectKmhFile(string $filePath): array - { - @set_time_limit(180); - @ini_set('memory_limit', '512M'); - - if (!File::exists($filePath)) { - throw new RuntimeException("Berkas file backup tidak ditemukan: {$filePath}"); - } - - $content = file_get_contents($filePath); - $headerLen = strlen(self::KMH_MAGIC_HEADER); - - if (substr($content, 0, $headerLen) !== self::KMH_MAGIC_HEADER) { - throw new RuntimeException("Berkas bukan format arsip .kmh yang sah atau file rusak (Magic Header tidak cocok)."); - } - - // Dekripsi payload (verifikasi HMAC & kunci enkripsi) - $decryptedZip = $this->decryptFromKmh($content); - - // Buka zip sementara untuk membaca manifest dan statistik file - $tempZip = tempnam(sys_get_temp_dir(), 'kmh_inspect_'); - file_put_contents($tempZip, $decryptedZip); - - try { - $zip = new ZipArchive(); - if ($zip->open($tempZip) !== true) { - throw new RuntimeException("Gagal membuka struktur arsip ZIP internal di dalam berkas .kmh."); - } - - $manifestJson = $zip->getFromName('manifest.json'); - $manifest = $manifestJson ? json_decode($manifestJson, true) : []; - - $filesCount = $zip->numFiles; - $mediaCount = 0; - $sqlSize = 0; - $mediaSamples = []; - - for ($i = 0; $i < $filesCount; $i++) { - $stat = $zip->statIndex($i); - $name = $stat['name'] ?? ''; - $size = $stat['size'] ?? 0; - - if (str_starts_with($name, 'storage/')) { - $mediaCount++; - if (count($mediaSamples) < 5) { - $mediaSamples[] = basename($name); - } - } elseif (str_ends_with($name, '.sql') || $name === 'database.sql') { - $sqlSize = $size; - } - } - - $tables = $manifest['tables'] ?? []; - $tableCount = count($tables); - - // Ambil rincian tabel & sampel data (dari manifest langsung atau fallback parse dari database.sql) - $tableDetails = $manifest['table_details'] ?? null; - if (empty($tableDetails)) { - $tableDetails = $this->parseTableDetailsFromSqlStream($zip, $tables); - } - - $zip->close(); - - $hasMedia = (bool) ($manifest['has_media'] ?? ($mediaCount > 0)); - $createdAt = isset($manifest['created_at']) ? Carbon::parse($manifest['created_at']) : Carbon::createFromTimestamp(filemtime($filePath)); - - return [ - 'is_valid' => true, - 'filename' => basename($filePath), - 'file_size' => filesize($filePath), - 'file_size_human' => $this->formatBytes(filesize($filePath)), - 'format' => $manifest['format'] ?? 'KMH_ENCRYPTED_V1', - 'system' => $manifest['system'] ?? 'PT Kerinci Merangin Hidro (RKM)', - 'created_at' => $createdAt->toIso8601String(), - 'created_at_human' => $createdAt->translatedFormat('d F Y, H:i:s') . ' WIB', - 'created_at_diff' => $createdAt->diffForHumans(), - 'type' => $manifest['type'] ?? ($hasMedia ? 'semua' : 'pilihan'), - 'type_label' => ($manifest['type'] ?? '') === 'semua' || $hasMedia - ? 'Backup Semua (Database + Media Foto)' - : 'Pilih Backup (Tabel Tertentu)', - 'database' => $manifest['database'] ?? config('database.connections.mysql.database', 'rkm_kmh'), - 'table_count' => $tableCount, - 'tables' => $tables, - 'table_details' => $tableDetails, - 'has_media' => $hasMedia, - 'media_file_count' => $mediaCount, - 'media_samples' => $mediaSamples, - 'sql_size' => $sqlSize, - 'sql_size_human' => $this->formatBytes($sqlSize), - 'laravel_version' => $manifest['laravel_version'] ?? app()->version(), - 'php_version' => $manifest['php_version'] ?? PHP_VERSION, - 'encryption_cipher' => 'AES-256-CBC', - 'hmac_verification' => 'SHA-256 Terverifikasi Sah', - ]; - } finally { - if (is_file($tempZip)) { - @unlink($tempZip); - } - } - } - - /** - * Parse rincian nama kolom, total baris data, dan sampel 5 baris pertama - * langsung dari stream database.sql untuk file arsip yang belum memiliki table_details di manifest. - * - * @param ZipArchive $zip - * @param array $tables - * @return array> - */ - protected function parseTableDetailsFromSqlStream(ZipArchive $zip, array $tables): array - { - $details = []; - foreach ($tables as $t) { - $details[$t] = [ - 'name' => $t, - 'rows_count' => 0, - 'columns' => [], - 'samples' => [], - ]; - } - - $fp = $zip->getStream('database.sql'); - if (!$fp) { - return $details; - } - - $currentTable = null; - $currentColumns = []; - $collectingSamples = false; - - while (($line = fgets($fp, 65536)) !== false) { - $trimmed = trim($line); - if (empty($trimmed)) continue; - - if (preg_match('/^--\s*Struktur Tabel untuk\s*`([^`]+)`/i', $trimmed, $m)) { - $currentTable = $m[1]; - if (!isset($details[$currentTable])) { - $details[$currentTable] = [ - 'name' => $currentTable, - 'rows_count' => 0, - 'columns' => [], - 'samples' => [], - ]; - } - $currentColumns = []; - $collectingSamples = false; - continue; - } - - if (preg_match('/^INSERT INTO\s*`([^`]+)`\s*\(([^)]+)\)\s*VALUES/i', $trimmed, $m)) { - $currentTable = $m[1]; - if (!isset($details[$currentTable])) { - $details[$currentTable] = [ - 'name' => $currentTable, - 'rows_count' => 0, - 'columns' => [], - 'samples' => [], - ]; - } - $rawCols = explode(',', $m[2]); - $currentColumns = array_map(fn($c) => trim($c, " \t\n\r\0\x0B`'\""), $rawCols); - $details[$currentTable]['columns'] = $currentColumns; - $collectingSamples = true; - continue; - } - - if ($currentTable && $collectingSamples) { - if (str_starts_with($trimmed, '(')) { - $details[$currentTable]['rows_count']++; - if (count($details[$currentTable]['samples']) < 5) { - $endPos = strrpos($trimmed, ')'); - if ($endPos !== false) { - $valuesStr = substr($trimmed, 1, $endPos - 1); - $parsedValues = str_getcsv($valuesStr, ',', "'", "\\"); - $rowAssoc = []; - foreach ($currentColumns as $idx => $colName) { - $val = $parsedValues[$idx] ?? null; - if ($val === 'NULL') $val = null; - if (in_array($colName, ['password', 'remember_token', 'two_factor_secret'])) { - $val = '••••••••'; - } - $rowAssoc[$colName] = $val; - } - $details[$currentTable]['samples'][] = $rowAssoc; - } - } - } elseif (str_starts_with($trimmed, '--') || str_starts_with($trimmed, 'DROP TABLE')) { - $collectingSamples = false; - } - } - } - - fclose($fp); - return $details; - } - /** * Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback). */ diff --git a/resources/views/admin/backups/index.blade.php b/resources/views/admin/backups/index.blade.php index 851d3a8..5719bdd 100644 --- a/resources/views/admin/backups/index.blade.php +++ b/resources/views/admin/backups/index.blade.php @@ -15,11 +15,6 @@

-
- - - - - @@ -1028,254 +863,5 @@ document.getElementById('deleteBackupModal').classList.add('hidden'); document.documentElement.classList.remove('modal-open'); } - - /* ========================================================================= */ - /* PEMBACA & INSPEKSI ARSIP .KMH (KMH READER JAVASCRIPT - MODEL UPLOAD) */ - /* ========================================================================= */ - let currentInspectedFile = null; - - function openInspectModal() { - document.getElementById('inspectBackupModal').classList.remove('hidden'); - document.documentElement.classList.add('modal-open'); - resetInspectToUpload(); - } - - function closeInspectModal() { - document.getElementById('inspectBackupModal').classList.add('hidden'); - document.documentElement.classList.remove('modal-open'); - } - - function resetInspectToUpload() { - document.getElementById('inspectLoading').classList.add('hidden'); - document.getElementById('inspectError').classList.add('hidden'); - document.getElementById('inspectResult').classList.add('hidden'); - document.getElementById('panelInspectUpload').classList.remove('hidden'); - const fileInput = document.getElementById('inspectFileInput'); - if (fileInput) fileInput.value = ''; - } - - function resetInspectResult() { - document.getElementById('inspectLoading').classList.add('hidden'); - document.getElementById('inspectError').classList.add('hidden'); - document.getElementById('inspectResult').classList.add('hidden'); - } - - function handleInspectFileInput(input) { - if (input.files && input.files[0]) { - inspectUploadedFile(input.files[0]); - } - } - - function handleInspectFileDrop(e, dropzone) { - e.preventDefault(); - e.stopPropagation(); - dropzone.classList.remove('border-sky-500', 'bg-sky-50/20'); - if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) { - inspectUploadedFile(e.dataTransfer.files[0]); - } - } - - function inspectUploadedFile(file) { - if (!file.name.toLowerCase().endsWith('.kmh')) { - alert('File yang dipilih harus berekstensi .kmh!'); - return; - } - - resetInspectResult(); - document.getElementById('panelInspectUpload').classList.add('hidden'); - const loading = document.getElementById('inspectLoading'); - document.getElementById('inspectLoadingText').textContent = `Mengunggah & memeriksa "${file.name}" (${(file.size / (1024 * 1024)).toFixed(1)} MB)...`; - loading.classList.remove('hidden'); - - const formData = new FormData(); - formData.append('backup_file', file); - formData.append('_token', '{{ csrf_token() }}'); - - fetch(`{{ route('admin.backups.inspect_upload') }}`, { - method: 'POST', - body: formData, - headers: { - 'Accept': 'application/json', - 'X-Requested-With': 'XMLHttpRequest' - } - }) - .then(res => res.json()) - .then(res => { - loading.classList.add('hidden'); - if (res.success && res.data) { - currentInspectedFile = file; - renderInspectionResult(res.data, 'upload'); - } else { - document.getElementById('panelInspectUpload').classList.remove('hidden'); - showInspectError(res.message || 'Gagal membaca arsip.'); - } - }) - .catch(err => { - loading.classList.add('hidden'); - document.getElementById('panelInspectUpload').classList.remove('hidden'); - showInspectError('Gagal membaca berkas: ' + err.message); - }); - } - - function showInspectError(msg) { - const errorDiv = document.getElementById('inspectError'); - document.getElementById('inspectErrorMessage').textContent = msg; - errorDiv.classList.remove('hidden'); - } - - let currentTableDetails = {}; - let activePreviewTable = null; - - function renderTableButtons(filter = '') { - const tableListDiv = document.getElementById('resTableList'); - tableListDiv.innerHTML = ''; - - const tableNames = Object.keys(currentTableDetails); - const filtered = filter ? tableNames.filter(t => t.toLowerCase().includes(filter.toLowerCase())) : tableNames; - - if (filtered.length === 0) { - tableListDiv.innerHTML = 'Tidak ada tabel yang cocok dengan pencarian.'; - return; - } - - filtered.forEach(tbl => { - const detail = currentTableDetails[tbl] || { rows_count: 0, columns: [], samples: [] }; - const count = detail.rows_count ?? 0; - const btn = document.createElement('button'); - btn.type = 'button'; - const isActive = (tbl === activePreviewTable); - - btn.className = isActive - ? 'px-2.5 py-1 rounded-lg text-[11px] font-mono font-semibold bg-sky-600 text-white shadow-2xs transition shrink-0' - : 'px-2.5 py-1 rounded-lg text-[11px] font-mono bg-white hover:bg-slate-100 border border-slate-200 text-slate-700 shadow-2xs transition shrink-0'; - - btn.textContent = `${tbl} (${count} baris)`; - btn.onclick = function() { - selectPreviewTable(tbl); - }; - - tableListDiv.appendChild(btn); - }); - } - - function selectPreviewTable(tbl) { - activePreviewTable = tbl; - const filterInput = document.getElementById('inspectTableFilterInput'); - renderTableButtons(filterInput ? filterInput.value : ''); - - const card = document.getElementById('resTablePreviewCard'); - const detail = currentTableDetails[tbl]; - - if (!detail) { - card.classList.add('hidden'); - return; - } - - card.classList.remove('hidden'); - document.getElementById('previewTableName').textContent = tbl; - document.getElementById('previewTableRowCount').textContent = `${detail.rows_count ?? 0} baris data`; - - const thead = document.getElementById('previewTableHead'); - const tbody = document.getElementById('previewTableBody'); - thead.innerHTML = ''; - tbody.innerHTML = ''; - - const columns = detail.columns || []; - const samples = detail.samples || []; - - if (columns.length === 0) { - thead.innerHTML = 'Kolom'; - tbody.innerHTML = 'Tabel kosong atau struktur kolom tidak terdefinisi.'; - return; - } - - // Header kolom - const trHead = document.createElement('tr'); - columns.forEach(col => { - const th = document.createElement('th'); - th.className = 'py-2 px-3 whitespace-nowrap text-slate-700 font-semibold'; - th.textContent = col; - trHead.appendChild(th); - }); - thead.appendChild(trHead); - - // Baris data sampel - if (samples.length === 0) { - const trEmpty = document.createElement('tr'); - const tdEmpty = document.createElement('td'); - tdEmpty.colSpan = columns.length; - tdEmpty.className = 'py-4 px-3 text-center text-slate-400 italic'; - tdEmpty.textContent = '(Tabel kosong / 0 baris data)'; - trEmpty.appendChild(tdEmpty); - tbody.appendChild(trEmpty); - } else { - samples.forEach(row => { - const tr = document.createElement('tr'); - tr.className = 'hover:bg-slate-50 transition'; - columns.forEach(col => { - const td = document.createElement('td'); - td.className = 'py-1.5 px-3 whitespace-nowrap text-slate-800'; - const val = row[col]; - if (val === null || val === undefined) { - td.innerHTML = 'null'; - } else if (typeof val === 'string' && val.length > 50) { - td.textContent = val.substring(0, 50) + '...'; - td.title = val; - } else { - td.textContent = val; - } - tr.appendChild(td); - }); - tbody.appendChild(tr); - }); - } - } - - function filterInspectTables(query) { - renderTableButtons(query); - } - - function renderInspectionResult(data, source) { - document.getElementById('resFilename').textContent = data.filename; - document.getElementById('resFileSize').textContent = data.file_size_human; - document.getElementById('resCreatedAt').textContent = data.created_at_human; - document.getElementById('resCreatedDiff').textContent = data.created_at_diff; - document.getElementById('resSecurity').textContent = `${data.encryption_cipher} (${data.hmac_verification})`; - document.getElementById('resType').textContent = data.type_label; - document.getElementById('resDatabase').textContent = data.database; - document.getElementById('resSql').textContent = data.sql_size_human; - document.getElementById('resMedia').textContent = data.has_media ? `${data.media_file_count} Berkas Media` : 'Tidak Ada Media'; - document.getElementById('resTableCount').textContent = data.table_count; - - // Siapkan struktur detail tabel & baris data - currentTableDetails = data.table_details || {}; - const tableKeys = Object.keys(currentTableDetails); - const filterInput = document.getElementById('inspectTableFilterInput'); - if (filterInput) filterInput.value = ''; - - if (tableKeys.length > 0) { - activePreviewTable = tableKeys[0]; - renderTableButtons(''); - selectPreviewTable(tableKeys[0]); - } else { - document.getElementById('resTableList').innerHTML = 'Daftar tabel tidak terdefinisi di manifest.'; - document.getElementById('resTablePreviewCard').classList.add('hidden'); - } - - const btnProceed = document.getElementById('btnProceedRestore'); - btnProceed.onclick = function() { - closeInspectModal(); - openDirectRestoreModal(); - if (currentInspectedFile) { - const input = document.getElementById('directRestoreFileInput'); - const dataTransfer = new DataTransfer(); - dataTransfer.items.add(currentInspectedFile); - input.files = dataTransfer.files; - handleDirectRestoreFileChange(input); - } - }; - - document.getElementById('inspectResult').classList.remove('hidden'); - } @endsection diff --git a/routes/web.php b/routes/web.php index efa1fc4..3d5648b 100644 --- a/routes/web.php +++ b/routes/web.php @@ -218,9 +218,7 @@ Route::middleware('auth')->group(function () { // Backup & Restore Sistem (Database & Media) Route::get('/backups', [BackupController::class, 'index'])->name('backups.index'); Route::post('/backups', [BackupController::class, 'store'])->name('backups.store'); - Route::post('/backups/inspect-file', [BackupController::class, 'inspectUpload'])->name('backups.inspect_upload'); Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1'); - Route::get('/backups/{filename}/inspect', [BackupController::class, 'inspect'])->name('backups.inspect'); Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download'); Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload'); Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1'); diff --git a/tests/Feature/BackupAndRestoreTest.php b/tests/Feature/BackupAndRestoreTest.php index 21d196a..406426f 100644 --- a/tests/Feature/BackupAndRestoreTest.php +++ b/tests/Feature/BackupAndRestoreTest.php @@ -310,60 +310,4 @@ class BackupAndRestoreTest extends TestCase 'target_name' => 'backup_dari_pc.kmh', ]); } - - public function test_super_admin_can_inspect_server_kmh_backup(): void - { - $filename = $this->backupService->createKmhBackup(['users'], false, 'test_inspect_server.kmh'); - - $response = $this->actingAs($this->superAdmin) - ->getJson(route('admin.backups.inspect', $filename)); - - $response->assertStatus(200); - $response->assertJson([ - 'success' => true, - 'data' => [ - 'filename' => $filename, - 'is_valid' => true, - 'encryption_cipher' => 'AES-256-CBC', - ], - ]); - - $this->assertContains('users', $response->json('data.tables')); - } - - public function test_super_admin_can_inspect_uploaded_kmh_backup_with_zero_disk_retention(): void - { - $filename = $this->backupService->createKmhBackup(['users'], false, 'test_inspect_upload.kmh'); - $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; - $kmhContent = file_get_contents($fullPath); - - $uploadedFile = UploadedFile::fake()->createWithContent('arsip_lama_2bulan_lalu.kmh', $kmhContent); - - $response = $this->actingAs($this->superAdmin) - ->postJson(route('admin.backups.inspect_upload'), [ - 'backup_file' => $uploadedFile, - ]); - - $response->assertStatus(200); - $response->assertJson([ - 'success' => true, - 'data' => [ - 'filename' => 'arsip_lama_2bulan_lalu.kmh', - 'is_valid' => true, - 'encryption_cipher' => 'AES-256-CBC', - ], - ]); - - $this->assertContains('users', $response->json('data.tables')); - } - - public function test_inspect_kmh_command_outputs_metadata(): void - { - $filename = $this->backupService->createKmhBackup(['users'], false, 'test_cli_inspect.kmh'); - - $this->artisan('kmh:inspect', ['file' => $filename]) - ->expectsOutputToContain('HASIL INSPEKSI ARSIP KMH') - ->expectsOutputToContain('AES-256-CBC') - ->assertExitCode(0); - } }