From 0d78318dfe8cfc99a8608cb63676fd42c0edd19b Mon Sep 17 00:00:00 2001 From: Ray1111-aa Date: Wed, 28 Oct 2026 11:14:47 +0700 Subject: [PATCH] fix(backup): implement drag-and-drop restore, direct auto-download, and backup history log --- .../Controllers/Admin/BackupController.php | 175 +++++- app/Models/BackupLog.php | 40 ++ app/Services/DatabaseBackupService.php | 2 +- ..._10_28_110520_create_backup_logs_table.php | 38 ++ resources/views/admin/backups/index.blade.php | 505 +++++++++++++++--- routes/web.php | 1 + tests/Feature/BackupAndRestoreTest.php | 41 ++ 7 files changed, 699 insertions(+), 103 deletions(-) create mode 100644 app/Models/BackupLog.php create mode 100644 database/migrations/2026_10_28_110520_create_backup_logs_table.php diff --git a/app/Http/Controllers/Admin/BackupController.php b/app/Http/Controllers/Admin/BackupController.php index fc5d86e..e851447 100644 --- a/app/Http/Controllers/Admin/BackupController.php +++ b/app/Http/Controllers/Admin/BackupController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\AdminActivityLog; +use App\Models\BackupLog; use App\Services\DatabaseBackupService; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -29,11 +30,42 @@ class BackupController extends Controller $stats = $this->backupService->getSystemStats(); $tableGroups = $this->backupService->getTableGroups(); - return view('admin.backups.index', compact('backups', 'stats', 'tableGroups')); + // Sinkronisasi file fisik di server ke riwayat BackupLog jika belum tercatat + foreach ($backups as $b) { + BackupLog::firstOrCreate( + ['filename' => $b['filename']], + [ + 'user_id' => auth()->id(), + 'user_name' => auth()->user()?->name ?? auth()->user()?->username ?? 'Super Admin', + 'scope' => $b['type'], + 'scope_label' => $b['type_label'], + 'table_count' => ($b['type'] === 'semua') ? count($this->backupService->getAllTableNames()) : 0, + 'tables_included' => null, + 'include_media' => ($b['type'] === 'semua'), + 'file_size' => $b['size_raw'], + 'file_size_human' => $b['size_human'], + 'status' => 'Tersimpan di Server', + 'created_at' => $b['created_at'], + ] + ); + } + + // Ambil seluruh riwayat backup terurut dari yang terbaru + $backupLogs = BackupLog::latest()->get(); + $backupDir = $this->backupService->getBackupDirectory(); + + // Tandai apakah file fisik masih ada di disk VPS server + $backupLogs->each(function ($log) use ($backupDir) { + $fullPath = $backupDir . DIRECTORY_SEPARATOR . $log->filename; + $log->file_exists = File::exists($fullPath); + }); + + return view('admin.backups.index', compact('backupLogs', 'backups', 'stats', 'tableGroups')); } /** * Buat file backup baru berekstensi khusus .kmh (Pilih Backup atau Backup Semua). + * Otomatis memicu unduhan langsung ke komputer Super Admin demi menghemat disk VPS kecil. */ public function store(Request $request): RedirectResponse { @@ -67,11 +99,30 @@ class BackupController extends Controller try { $filename = $this->backupService->createKmhBackup($selectedTables, $includeMedia); + $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; + $sizeBytes = File::exists($fullPath) ? File::size($fullPath) : 0; + $sizeHuman = $this->backupService->formatBytes($sizeBytes); + + // Rekam ke Riwayat Aktivitas Backup + BackupLog::create([ + 'user_id' => $request->user()?->id, + 'user_name' => $request->user()?->name ?? $request->user()?->username ?? 'Super Admin', + 'filename' => $filename, + 'scope' => $scope, + 'scope_label' => $scopeLabel, + 'table_count' => is_array($selectedTables) ? count($selectedTables) : count($this->backupService->getAllTableNames()), + 'tables_included' => $selectedTables, + 'include_media' => $includeMedia, + 'file_size' => $sizeBytes, + 'file_size_human' => $sizeHuman, + 'status' => 'Berhasil Diunduh', + ]); + // Rekam ke Log Aktivitas Super Admin AdminActivityLog::record( actionType: 'create', module: 'Backup & Restore', - description: "Membuat file backup terenkripsi .kmh: {$filename} [Cakupan: {$scopeLabel}].", + description: "Membuat file backup terenkripsi .kmh: {$filename} [Cakupan: {$scopeLabel}]. File siap diunduh ke komputer lokal.", targetType: 'BackupFile', targetName: $filename, newValues: [ @@ -79,10 +130,13 @@ class BackupController extends Controller 'scope' => $scope, 'table_count' => is_array($selectedTables) ? count($selectedTables) : 'all', 'include_media' => $includeMedia, + 'size' => $sizeHuman, ] ); - return back()->with('success', "Arsip terenkripsi .kmh ({$filename}) berhasil dibuat dan diamankan di server."); + return back() + ->with('success', "Arsip backup terenkripsi .kmh ({$filename}) berhasil dibuat dan langsung diunduh ke komputer Anda.") + ->with('auto_download', route('admin.backups.download', $filename)); } catch (\Throwable $e) { return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage()); } @@ -97,7 +151,7 @@ class BackupController extends Controller $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; if (!File::exists($fullPath)) { - return back()->with('error', "File backup '{$filename}' tidak ditemukan di server."); + return back()->with('error', "File backup '{$filename}' tidak ditemukan di server (kemungkinan telah dihapus untuk menghemat kapasitas disk VPS)."); } AdminActivityLog::record( @@ -120,6 +174,18 @@ class BackupController extends Controller */ public function upload(Request $request): RedirectResponse { + // Validasi ketersediaan file dan deteksi error PHP upload limit + if (!$request->hasFile('backup_file')) { + $iniMax = ini_get('upload_max_filesize') ?: '2M'; + $postMax = ini_get('post_max_size') ?: '8M'; + return back()->with('error', "Gagal mengunggah file. Server tidak menerima berkas file (kemungkinan ukuran file melebihi batas konfigurasi PHP server: upload_max_filesize={$iniMax}, post_max_size={$postMax})."); + } + + $file = $request->file('backup_file'); + if (!$file->isValid()) { + return back()->with('error', 'File yang diunggah tidak valid atau gagal terkirim: ' . $file->getErrorMessage()); + } + $request->validate([ 'backup_file' => ['required', 'file', 'max:204800'], // Maks. 200 MB ], [ @@ -128,7 +194,6 @@ class BackupController extends Controller 'backup_file.max' => 'Ukuran file backup maksimal 200 MB.', ]); - $file = $request->file('backup_file'); $originalName = basename($file->getClientOriginalName()); $ext = strtolower($file->getClientOriginalExtension()); @@ -146,23 +211,43 @@ class BackupController extends Controller try { $file->move($targetDir, $targetFilename); + $storedPath = $targetDir . DIRECTORY_SEPARATOR . $targetFilename; + $fileSize = File::exists($storedPath) ? File::size($storedPath) : 0; + $fileSizeHuman = $this->backupService->formatBytes($fileSize); + + // Rekam ke Riwayat Aktivitas Backup + BackupLog::firstOrCreate( + ['filename' => $targetFilename], + [ + 'user_id' => $request->user()?->id, + 'user_name' => $request->user()?->name ?? $request->user()?->username ?? 'Super Admin', + 'scope' => str_contains($targetFilename, 'semua') ? 'semua' : 'pilihan', + 'scope_label' => 'Unggahan Eksternal (' . strtoupper($ext) . ')', + 'table_count' => 0, + 'tables_included' => null, + 'include_media' => false, + 'file_size' => $fileSize, + 'file_size_human' => $fileSizeHuman, + 'status' => 'Tersimpan di Server', + ] + ); AdminActivityLog::record( actionType: 'create', module: 'Backup & Restore', - description: "Mengunggah file backup eksternal: {$targetFilename}.", + description: "Mengunggah file backup eksternal: {$targetFilename} ({$fileSizeHuman}).", targetType: 'BackupFile', targetName: $targetFilename ); - return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah ke server."); + return back()->with('success', "File backup '{$targetFilename}' ({$fileSizeHuman}) berhasil diunggah ke server."); } catch (\Throwable $e) { return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage()); } } /** - * Pulihkan (Restore) database & aset sistem dari file backup (.kmh). + * Pulihkan (Restore) database & aset sistem dari file backup (.kmh) yang sudah ada di server. */ public function restore(Request $request, string $filename): RedirectResponse { @@ -195,7 +280,7 @@ class BackupController extends Controller AdminActivityLog::record( actionType: 'update', module: 'Backup & Restore', - description: "Melakukan pemulihan (restore) database dan aset sistem dari file backup: {$filename}.", + description: "Melakukan pemulihan (restore) database dan aset sistem dari file backup server: {$filename}.", targetType: 'BackupFile', targetName: $filename ); @@ -207,24 +292,88 @@ class BackupController extends Controller } /** - * Hapus file backup dari penyimpanan server. + * Pulihkan (Restore) database & aset sistem secara langsung dari file (.kmh) yang diunggah/didrag & drop. + * Tidak meninggalkan file sampah di server sehingga sangat hemat disk VPS. + */ + public function restoreFromFile(Request $request): RedirectResponse + { + if (!$request->hasFile('backup_file')) { + $iniMax = ini_get('upload_max_filesize') ?: '2M'; + $postMax = ini_get('post_max_size') ?: '8M'; + return back()->with('error', "File backup .kmh belum dipilih atau file melebihi batas upload PHP server (upload_max_filesize: {$iniMax}, post_max_size: {$postMax})."); + } + + $file = $request->file('backup_file'); + if (!$file->isValid()) { + return back()->with('error', 'File yang diunggah tidak valid atau gagal dibaca: ' . $file->getErrorMessage()); + } + + $ext = strtolower($file->getClientOriginalExtension()); + if (!in_array($ext, ['kmh', 'sql', 'zip'])) { + return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .kmh, .sql, atau .zip.'); + } + + // Verifikasi Keamanan: Ketik "PULIHKAN" atau masukkan password Super Admin + $confirmed = false; + if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'PULIHKAN') { + $confirmed = true; + } elseif ($request->filled('password') && Hash::check($request->input('password'), $request->user()->password)) { + $confirmed = true; + } + + if (!$confirmed) { + return back()->with('error', 'Konfirmasi keamanan tidak sesuai. Silakan ketik kata "PULIHKAN" atau masukkan password akun Super Admin Anda untuk melanjutkan pemulihan.'); + } + + $tempPath = $file->getRealPath(); + $originalName = $file->getClientOriginalName(); + + try { + $this->backupService->restore($tempPath); + + // Bersihkan cache aplikasi & permission registrar Spatie + Artisan::call('cache:clear'); + app()[PermissionRegistrar::class]->forgetCachedPermissions(); + + AdminActivityLog::record( + actionType: 'update', + module: 'Backup & Restore', + description: "Melakukan pemulihan (restore) langsung dari file lokal: {$originalName}.", + targetType: 'BackupFile', + targetName: $originalName + ); + + return back()->with('success', "Sistem berhasil dipulihkan secara langsung dari file '{$originalName}'. Seluruh data tabel dan media telah disinkronkan kembali."); + } catch (\Throwable $e) { + return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage()); + } + } + + /** + * Hapus file backup dari penyimpanan server untuk menghemat kapasitas disk VPS. + * Riwayat log backup tetap tersimpan di sistem. */ public function destroy(string $filename): RedirectResponse { $filename = basename($filename); if ($this->backupService->deleteBackup($filename)) { + // Update status log jika ada + BackupLog::where('filename', $filename)->update([ + 'status' => 'Tersimpan di Komputer Lokal (Dihapus dari Server)', + ]); + AdminActivityLog::record( actionType: 'delete', module: 'Backup & Restore', - description: "Menghapus file backup: {$filename}.", + description: "Menghapus file fisik backup dari disk server: {$filename}.", targetType: 'BackupFile', targetName: $filename ); - return back()->with('success', "File backup '{$filename}' berhasil dihapus dari server."); + return back()->with('success', "File fisik '{$filename}' berhasil dihapus dari penyimpanan server untuk menghemat kapasitas disk VPS. Riwayat pencadangan tetap tersimpan."); } - return back()->with('error', "File backup '{$filename}' tidak ditemukan atau gagal dihapus."); + return back()->with('error', "File backup '{$filename}' tidak ditemukan di server atau sudah pernah dihapus."); } } diff --git a/app/Models/BackupLog.php b/app/Models/BackupLog.php new file mode 100644 index 0000000..71ac187 --- /dev/null +++ b/app/Models/BackupLog.php @@ -0,0 +1,40 @@ + 'array', + 'include_media' => 'boolean', + 'file_size' => 'integer', + 'table_count' => 'integer', + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + ]; + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Services/DatabaseBackupService.php b/app/Services/DatabaseBackupService.php index 7422f17..b8302f8 100644 --- a/app/Services/DatabaseBackupService.php +++ b/app/Services/DatabaseBackupService.php @@ -728,7 +728,7 @@ class DatabaseBackupService /** * Format byte ke satuan yang mudah dibaca (KB, MB, GB). */ - protected function formatBytes(int $bytes, int $precision = 2): string + public function formatBytes(int $bytes, int $precision = 2): string { if ($bytes <= 0) return '0 B'; diff --git a/database/migrations/2026_10_28_110520_create_backup_logs_table.php b/database/migrations/2026_10_28_110520_create_backup_logs_table.php new file mode 100644 index 0000000..df1479b --- /dev/null +++ b/database/migrations/2026_10_28_110520_create_backup_logs_table.php @@ -0,0 +1,38 @@ +id(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('user_name')->nullable(); + $table->string('filename'); + $table->string('scope')->default('semua'); // 'semua' atau 'pilihan' + $table->string('scope_label'); + $table->integer('table_count')->default(0); + $table->json('tables_included')->nullable(); + $table->boolean('include_media')->default(false); + $table->unsignedBigInteger('file_size')->default(0); + $table->string('file_size_human')->nullable(); + $table->string('status')->default('Berhasil Diunduh'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('backup_logs'); + } +}; diff --git a/resources/views/admin/backups/index.blade.php b/resources/views/admin/backups/index.blade.php index e0c0477..cac7c46 100644 --- a/resources/views/admin/backups/index.blade.php +++ b/resources/views/admin/backups/index.blade.php @@ -11,14 +11,19 @@ Backup & Restore Sistem

- Pencadangan terenkripsi berformat .kmh khusus untuk sistem RKM-KMH. File tidak dapat dibaca oleh sistem luar. + Pencadangan terenkripsi berformat .kmh khusus untuk sistem RKM-KMH. Langsung unduh ke komputer lokal dan hemat kapasitas disk VPS server.

-
+
+
- + @if(session('success')) -
- {{ session('success') }} +
+
+ + {{ session('success') }} +
@endif @if(session('error')) -
- {{ session('error') }} +
+
+ + {{ session('error') }} +
@endif - -
-
- Total File Backup -
- {{ number_format($stats['total_backups']) }} - file (.kmh) + @if($errors->any()) +
+
+ Terdapat kesalahan validasi: +
- Total kapasitas: {{ $stats['total_size_human'] }} +
    + @foreach($errors->all() as $err) +
  • {{ $err }}
  • + @endforeach +
+
+ @endif + + +
+
+ Total Aktivitas Backup +
+ {{ number_format($backupLogs->count()) }} + kali dicadangkan +
+ + Tersedia di server: {{ $backups ? count($backups) : 0 }} file ({{ $stats['total_size_human'] ?? '0 B' }}) + +
+ +
+ Kapasitas Disk Server VPS +
+ {{ $stats['total_size_human'] ?? '0 B' }} + Hemat Ruang +
+ Unduhan langsung ke PC membebaskan storage VPS
Backup Terakhir
- - {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }} + + @if($backupLogs->isNotEmpty()) + {{ $backupLogs->first()->created_at?->translatedFormat('d M Y, H:i') }} WIB + @else + {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }} + @endif - {{ $stats['last_backup']['filename'] ?? '-' }} + {{ $backupLogs->first()->filename ?? ($stats['last_backup']['filename'] ?? '-') }}
@@ -76,97 +116,151 @@
- +
-
-

- Daftar Arsip Backup -

- - storage/app/backups/ - +
+
+

+ Riwayat Aktivitas Backup & Arsip +

+

+ Mencatat tanggal, jenis data yang dicadangkan, dan riwayat arsip terenkripsi .kmh. +

+
+
+ + + Tersedia di Server + + • + + + Tersimpan di PC Lokal + +
- - + + + - + - @forelse($backups as $b) + @forelse($backupLogs as $log) @php - $isFull = ($b['type'] === 'semua'); + $isFull = ($log->scope === 'semua'); + $hasServerFile = (bool) $log->file_exists; @endphp - - - - + + + - - @empty -
Nama FileTipe BackupTanggal & WaktuNama File ArsipJenis / Cakupan Backup UkuranTanggal DibuatStatus & Lokasi Aksi
-
- - {{ $b['filename'] }} - - @if($b['is_kmh']) - - .kmh - - @endif -
+ +
+ + {{ $log->created_at?->translatedFormat('d M Y, H:i') }} WIB + + + {{ $log->created_at?->diffForHumans() }} + + + +
+ + {{ $log->filename }} + + + .kmh + +
+ + Oleh: {{ $log->user_name ?? 'Super Admin' }} + +
@if($isFull) Backup Semua + + 29 Tabel + Media Upload + @else - + Pilih Backup + + {{ $log->table_count > 0 ? $log->table_count . ' Tabel Terpilih' : ($log->scope_label ?? 'Tabel Terpilih') }} + @if($log->include_media) + + Media + @endif + @endif - {{ $b['size_human'] }} + {{ $log->file_size_human ?: '-' }} - {{ $b['created_at_human'] }} + + + @if($hasServerFile) + + + Tersedia di Server + + @else + + + Tersimpan di PC Lokal + + @endif
- - Unduh - + @if($hasServerFile) + + Unduh + - + - + + @else + + @endif
-

Belum ada file backup yang tersimpan di server.

+
+

Belum ada riwayat pencadangan data sistem.

@@ -199,6 +293,11 @@ @csrf
+ +
+ Pemberitahuan Penyimpanan VPS: Setelah pencadangan selesai, file .kmh akan langsung otomatis diunduh ke komputer Anda. Anda tidak perlu khawatir server VPS penuh karena file fisik di server dapat dihapus sewaktu-waktu. +
+
@@ -232,7 +331,7 @@
Backup Semua - Cadangkan seluruh tabel database (29 tabel) + seluruh file media upload. + Cadangkan seluruh tabel database ({{ $stats['table_count'] ?? 29 }} tabel) + seluruh file media upload.
@@ -307,7 +406,7 @@ Batal
@@ -315,24 +414,135 @@ - + + + + + +