feat(backup): implement proprietary encrypted .kmh format, dual backup selection (pilih vs semua), and clean minimalist UI

This commit is contained in:
Ray1111-aa
2026-10-28 09:20:18 +07:00
parent 238ec128d2
commit cb9891b1e3
5 changed files with 742 additions and 670 deletions
+26 -20
View File
@@ -11,45 +11,51 @@ class CreateBackupCommand extends Command
* Nama dan signature perintah CLI. * Nama dan signature perintah CLI.
*/ */
protected $signature = 'backup:create protected $signature = 'backup:create
{--type=database : Jenis backup: database atau full} {--scope=semua : Cakupan backup: semua atau pilihan}
{--filename= : Nama kustom untuk file backup}'; {--tables= : Daftar nama tabel dipisah koma (jika scope=pilihan)}
{--filename= : Nama kustom untuk file .kmh}';
/** /**
* Deskripsi perintah. * Deskripsi perintah.
*/ */
protected $description = 'Buat backup database MySQL atau Full Backup (+ media upload) sistem RKM-KMH'; protected $description = 'Buat backup terenkripsi (.kmh) untuk sistem RKM-KMH';
public function handle(DatabaseBackupService $service): int public function handle(DatabaseBackupService $service): int
{ {
$type = strtolower($this->option('type') ?: 'database'); $scope = strtolower($this->option('scope') ?: 'semua');
$customName = $this->option('filename'); $customName = $this->option('filename');
$tablesOption = $this->option('tables');
if (!in_array($type, ['database', 'full'])) { $selectedTables = null;
$this->error("Pilihan --type tidak valid. Gunakan 'database' atau 'full'."); $includeMedia = false;
return Command::FAILURE;
if ($scope === 'semua') {
$includeMedia = true;
$this->info("Memulai pembuatan [Backup Semua] sistem RKM-KMH (.kmh)...");
} else {
if ($tablesOption) {
$selectedTables = array_map('trim', explode(',', $tablesOption));
} else {
$selectedTables = $service->getAllTableNames();
}
$this->info("Memulai pembuatan [Pilih Backup] (" . count($selectedTables) . " tabel) (.kmh)...");
} }
$this->info("Memulai pembuatan backup sistem RKM-KMH [Tipe: " . strtoupper($type) . "]...");
try { try {
$startTime = microtime(true); $startTime = microtime(true);
$filename = $service->createKmhBackup($selectedTables, $includeMedia, $customName);
if ($type === 'full') {
$filename = $service->createFullBackup($customName);
} else {
$filename = $service->createDatabaseBackup($customName);
}
$duration = round(microtime(true) - $startTime, 2); $duration = round(microtime(true) - $startTime, 2);
$fullPath = $service->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; $fullPath = $service->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$sizeHuman = FileSizeHelper::format(file_exists($fullPath) ? filesize($fullPath) : 0); $size = file_exists($fullPath) ? filesize($fullPath) : 0;
$sizeHuman = FileSizeHelper::format($size);
$this->newLine(); $this->newLine();
$this->info("✓ Backup berhasil dibuat!"); $this->info("✓ File backup .kmh berhasil dibuat dan terenkripsi!");
$this->line(" File : <comment>{$filename}</comment>"); $this->line(" File : <comment>{$filename}</comment>");
$this->line(" Lokasi : {$fullPath}"); $this->line(" Lokasi : {$fullPath}");
$this->line(" Ukuran : {$sizeHuman}"); $this->line(" Ukuran : {$sizeHuman}");
$this->line(" Waktu : {$duration} detik"); $this->line(" Waktu : {$duration} detik");
return Command::SUCCESS; return Command::SUCCESS;
} catch (\Throwable $e) { } catch (\Throwable $e) {
+41 -29
View File
@@ -27,55 +27,69 @@ class BackupController extends Controller
{ {
$backups = $this->backupService->listBackups(); $backups = $this->backupService->listBackups();
$stats = $this->backupService->getSystemStats(); $stats = $this->backupService->getSystemStats();
$tableGroups = $this->backupService->getTableGroups();
return view('admin.backups.index', compact('backups', 'stats')); return view('admin.backups.index', compact('backups', 'stats', 'tableGroups'));
} }
/** /**
* Buat file backup baru (Database Saja atau Full Backup + Media). * Buat file backup baru berekstensi khusus .kmh (Pilih Backup atau Backup Semua).
*/ */
public function store(Request $request): RedirectResponse public function store(Request $request): RedirectResponse
{ {
$validated = $request->validate([ $validated = $request->validate([
'type' => ['required', 'in:database,full'], 'backup_scope' => ['required', 'in:pilihan,semua'],
'selected_tables' => ['nullable', 'array'],
'selected_tables.*' => ['string'],
'include_media' => ['nullable', 'in:1,0'],
], [ ], [
'type.required' => 'Pilih jenis backup yang ingin dibuat.', 'backup_scope.required' => 'Pilih cakupan pencadangan: Pilih Backup atau Backup Semua.',
'type.in' => 'Jenis backup harus bernilai database atau full.', 'backup_scope.in' => 'Cakupan backup tidak valid.',
]); ]);
$type = $validated['type']; $scope = $validated['backup_scope'];
$includeMedia = false;
$selectedTables = null;
if ($scope === 'semua') {
$includeMedia = true;
$selectedTables = null; // Semua tabel
$scopeLabel = 'Backup Semua (Database + Media Upload)';
} else {
$selectedTables = $request->input('selected_tables', []);
if (empty($selectedTables)) {
return back()->with('error', 'Silakan centang minimal satu tabel yang ingin Anda cadangkan.');
}
$includeMedia = (bool) $request->input('include_media', false);
$scopeLabel = 'Pilih Backup (' . count($selectedTables) . ' Tabel Terpilih)';
}
try { try {
if ($type === 'full') { $filename = $this->backupService->createKmhBackup($selectedTables, $includeMedia);
$filename = $this->backupService->createFullBackup();
$typeLabel = 'Full Backup (+ Media)';
} else {
$filename = $this->backupService->createDatabaseBackup();
$typeLabel = 'Database SQL';
}
// Catat ke Log Aktivitas Super Admin // Rekam ke Log Aktivitas Super Admin
AdminActivityLog::record( AdminActivityLog::record(
actionType: 'create', actionType: 'create',
module: 'Backup & Restore', module: 'Backup & Restore',
description: "Membuat {$typeLabel} baru dengan nama file: {$filename}.", description: "Membuat file backup terenkripsi .kmh: {$filename} [Cakupan: {$scopeLabel}].",
targetType: 'BackupFile', targetType: 'BackupFile',
targetName: $filename, targetName: $filename,
newValues: [ newValues: [
'filename' => $filename, 'filename' => $filename,
'type' => $type, 'scope' => $scope,
'created_at' => now()->toIso8601String(), 'table_count' => is_array($selectedTables) ? count($selectedTables) : 'all',
'include_media' => $includeMedia,
] ]
); );
return back()->with('success', "{$typeLabel} ({$filename}) berhasil dibuat dan disimpan di server."); return back()->with('success', "Arsip terenkripsi .kmh ({$filename}) berhasil dibuat dan diamankan di server.");
} catch (\Throwable $e) { } catch (\Throwable $e) {
return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage()); return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage());
} }
} }
/** /**
* Unduh file backup ke penyimpanan lokal administrator. * Unduh file backup .kmh ke penyimpanan komputer lokal.
*/ */
public function download(string $filename): BinaryFileResponse|RedirectResponse public function download(string $filename): BinaryFileResponse|RedirectResponse
{ {
@@ -89,7 +103,7 @@ class BackupController extends Controller
AdminActivityLog::record( AdminActivityLog::record(
actionType: 'export', actionType: 'export',
module: 'Backup & Restore', module: 'Backup & Restore',
description: "Mengunduh file backup: {$filename}.", description: "Mengunduh file arsip backup: {$filename}.",
targetType: 'BackupFile', targetType: 'BackupFile',
targetName: $filename targetName: $filename
); );
@@ -102,7 +116,7 @@ class BackupController extends Controller
} }
/** /**
* Unggah file backup (.sql, .zip, .gz) dari komputer lokal ke server. * Unggah file backup (.kmh, .sql, atau .zip) dari komputer lokal ke server.
*/ */
public function upload(Request $request): RedirectResponse public function upload(Request $request): RedirectResponse
{ {
@@ -118,11 +132,10 @@ class BackupController extends Controller
$originalName = basename($file->getClientOriginalName()); $originalName = basename($file->getClientOriginalName());
$ext = strtolower($file->getClientOriginalExtension()); $ext = strtolower($file->getClientOriginalExtension());
if (!in_array($ext, ['sql', 'zip', 'gz'])) { if (!in_array($ext, ['kmh', 'sql', 'zip', 'gz'])) {
return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .sql, .zip, atau .gz.'); return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .kmh, .sql, atau .zip.');
} }
// Cegah nama ganda dengan menambahkan timestamp jika file sudah ada
$targetDir = $this->backupService->getBackupDirectory(); $targetDir = $this->backupService->getBackupDirectory();
$targetFilename = $originalName; $targetFilename = $originalName;
@@ -142,14 +155,14 @@ class BackupController extends Controller
targetName: $targetFilename targetName: $targetFilename
); );
return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah dan siap dipulihkan jika diperlukan."); return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah ke server.");
} catch (\Throwable $e) { } catch (\Throwable $e) {
return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage()); return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage());
} }
} }
/** /**
* Pulihkan (Restore) database & aset sistem dari file backup. * Pulihkan (Restore) database & aset sistem dari file backup (.kmh).
*/ */
public function restore(Request $request, string $filename): RedirectResponse public function restore(Request $request, string $filename): RedirectResponse
{ {
@@ -160,7 +173,7 @@ class BackupController extends Controller
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server."); return back()->with('error', "File backup '{$filename}' tidak ditemukan di server.");
} }
// Verifikasi Keamanan: Harap ketik "PULIHKAN" atau masukkan password Super Admin // Verifikasi Keamanan: Ketik "PULIHKAN" atau masukkan password Super Admin
$confirmed = false; $confirmed = false;
if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'PULIHKAN') { if ($request->filled('confirmation') && trim($request->input('confirmation')) === 'PULIHKAN') {
$confirmed = true; $confirmed = true;
@@ -173,7 +186,6 @@ class BackupController extends Controller
} }
try { try {
// Jalankan proses restore
$this->backupService->restore($fullPath); $this->backupService->restore($fullPath);
// Bersihkan cache aplikasi & permission registrar Spatie // Bersihkan cache aplikasi & permission registrar Spatie
@@ -188,7 +200,7 @@ class BackupController extends Controller
targetName: $filename targetName: $filename
); );
return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data dan tabel telah disinkronkan kembali."); return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data tabel telah disinkronkan kembali.");
} catch (\Throwable $e) { } catch (\Throwable $e) {
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage()); return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage());
} }
+330 -239
View File
@@ -11,6 +11,8 @@ use ZipArchive;
class DatabaseBackupService class DatabaseBackupService
{ {
public const KMH_MAGIC_HEADER = "KMH_ENCRYPTED_BACKUP_V1\n";
protected string $backupDir; protected string $backupDir;
public function __construct() public function __construct()
@@ -29,6 +31,61 @@ class DatabaseBackupService
return $this->backupDir; return $this->backupDir;
} }
/**
* Dapatkan kunci enkripsi 256-bit berbasis APP_KEY sistem.
* Hanya sistem ini yang bisa mendekripsi dan membaca konten file .kmh.
*/
protected function getEncryptionKey(): string
{
$appKey = config('app.key');
if (str_starts_with((string)$appKey, 'base64:')) {
$appKey = base64_decode(substr((string)$appKey, 7));
}
return hash('sha256', (string)$appKey . '_RKM_KMH_ENCRYPTION_SECRET', true);
}
/**
* Enkripsi payload mentah ke dalam format kontainer aman .kmh dengan header magic bytes & HMAC.
*/
public function encryptToKmh(string $rawContent): string
{
$key = $this->getEncryptionKey();
$iv = random_bytes(16);
$ciphertext = openssl_encrypt($rawContent, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext, $key, true);
return self::KMH_MAGIC_HEADER . $iv . $hmac . $ciphertext;
}
/**
* Dekripsi file .kmh kembali ke konten arsip aslinya setelah verifikasi HMAC.
*/
public function decryptFromKmh(string $kmhContent): string
{
$headerLen = strlen(self::KMH_MAGIC_HEADER);
if (substr($kmhContent, 0, $headerLen) !== self::KMH_MAGIC_HEADER) {
throw new RuntimeException("File ini bukan format arsip .kmh yang sah atau file rusak.");
}
$iv = substr($kmhContent, $headerLen, 16);
$hmac = substr($kmhContent, $headerLen + 16, 32);
$ciphertext = substr($kmhContent, $headerLen + 48);
$key = $this->getEncryptionKey();
$calculatedHmac = hash_hmac('sha256', $ciphertext, $key, true);
if (!hash_equals($hmac, $calculatedHmac)) {
throw new RuntimeException("Gagal membuka file .kmh: Kunci enkripsi tidak cocok atau file telah dimodifikasi oleh sistem luar.");
}
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
throw new RuntimeException("Gagal mendekripsi payload arsip .kmh.");
}
return $decrypted;
}
/** /**
* Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru. * Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru.
* *
@@ -40,7 +97,8 @@ class DatabaseBackupService
* size_raw: int, * size_raw: int,
* size_human: string, * size_human: string,
* created_at: Carbon, * created_at: Carbon,
* created_at_human: string * created_at_human: string,
* is_kmh: bool
* }> * }>
*/ */
public function listBackups(): array public function listBackups(): array
@@ -50,17 +108,18 @@ class DatabaseBackupService
foreach ($files as $file) { foreach ($files as $file) {
$extension = strtolower($file->getExtension()); $extension = strtolower($file->getExtension());
if (!in_array($extension, ['sql', 'zip', 'gz'])) { if (!in_array($extension, ['kmh', 'sql', 'zip', 'gz'])) {
continue; continue;
} }
$filename = $file->getFilename(); $filename = $file->getFilename();
$size = $file->getSize(); $size = $file->getSize();
$createdAt = Carbon::createFromTimestamp($file->getMTime()); $createdAt = Carbon::createFromTimestamp($file->getMTime());
$isKmh = ($extension === 'kmh');
$isFull = str_ends_with($filename, '.zip') || str_contains($filename, '_full_'); $isFull = str_contains($filename, 'semua') || str_contains($filename, '_full_') || $extension === 'zip';
$type = $isFull ? 'full' : 'database'; $type = $isFull ? 'semua' : 'pilihan';
$typeLabel = $isFull ? 'Full Backup (+ File Media)' : 'Database SQL'; $typeLabel = $isFull ? 'Backup Semua' : 'Pilih Backup';
$backups[] = [ $backups[] = [
'filename' => $filename, 'filename' => $filename,
@@ -71,6 +130,7 @@ class DatabaseBackupService
'size_human' => $this->formatBytes($size), 'size_human' => $this->formatBytes($size),
'created_at' => $createdAt, 'created_at' => $createdAt,
'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB', 'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB',
'is_kmh' => $isKmh,
]; ];
} }
@@ -80,167 +140,104 @@ class DatabaseBackupService
} }
/** /**
* Buat backup database (MySQL / SQLite) ke dalam file .sql murni. * Buat backup terenkripsi .kmh (baik "Pilih Backup" tabel tertentu atau "Backup Semua" + media).
* Menggunakan PDO stream generator mandiri tanpa ketergantungan mysqldump eksternal. *
* @param array<int, string>|null $selectedTables Tabel yang dipilih (null = semua tabel)
* @param bool $includeMedia Sertakan file media upload di storage/app/public
* @param string|null $customFilename Nama file kustom opsional
*/ */
public function createDatabaseBackup(?string $customFilename = null): string public function createKmhBackup(?array $selectedTables = null, bool $includeMedia = false, ?string $customFilename = null): string
{
@set_time_limit(300);
@ini_set('memory_limit', '512M');
$driver = DB::connection()->getDriverName();
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database);
$timestamp = now()->format('Ymd_His');
$filename = $customFilename ?: "backup_db_{$cleanDbName}_{$timestamp}.sql";
// Amankan nama file dari traversal
$filename = basename($filename);
if (!str_ends_with($filename, '.sql')) {
$filename .= '.sql';
}
$fullPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename;
$handle = fopen($fullPath, 'w');
if (!$handle) {
throw new RuntimeException("Gagal membuka file backup untuk penulisan: {$fullPath}");
}
try {
$pdo = DB::connection()->getPdo();
$nowString = now()->format('Y-m-d H:i:s');
// Header SQL Standar
fwrite($handle, "-- ==============================================================\n");
fwrite($handle, "-- RKM-KMH DATABASE BACKUP (PT Kerinci Merangin Hidro)\n");
fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n");
fwrite($handle, "-- Driver : {$driver}\n");
fwrite($handle, "-- Database : {$database}\n");
fwrite($handle, "-- ==============================================================\n\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n");
} else {
fwrite($handle, "SET NAMES utf8mb4;\n");
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n");
fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n");
fwrite($handle, "SET time_zone = '+00:00';\n\n");
}
// Ambil daftar seluruh tabel aktif
$tables = $this->getAllTableNames();
foreach ($tables as $tableName) {
$this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver);
}
// Footer SQL
fwrite($handle, "\n-- ==============================================================\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = ON;\n");
} else {
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n");
}
fwrite($handle, "-- END OF RKM-KMH DATABASE BACKUP\n");
fwrite($handle, "-- ==============================================================\n");
fclose($handle);
return $filename;
} catch (\Throwable $e) {
if (is_resource($handle)) {
fclose($handle);
}
if (File::exists($fullPath)) {
File::delete($fullPath);
}
throw new RuntimeException("Gagal membuat backup database: " . $e->getMessage(), 0, $e);
}
}
/**
* Buat full backup (.zip) yang mencakup file database .sql dan seluruh file upload media (storage/app/public).
*/
public function createFullBackup(?string $customFilename = null): string
{ {
@set_time_limit(600); @set_time_limit(600);
@ini_set('memory_limit', '512M'); @ini_set('memory_limit', '512M');
if (!class_exists('ZipArchive')) { if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.'); throw new RuntimeException('Ekstensi PHP ZipArchive diperlukan untuk memaketkan arsip.');
} }
$database = config('database.connections.' . config('database.default') . '.database', 'database'); $allTables = $this->getAllTableNames();
$targetTables = (!empty($selectedTables)) ? array_values(array_intersect($allTables, $selectedTables)) : $allTables;
if (empty($targetTables)) {
throw new RuntimeException('Silakan pilih minimal satu tabel yang ingin dicadangkan.');
}
$database = config('database.connections.' . config('database.default') . '.database', 'rkm_kmh');
$cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database); $cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database);
$timestamp = now()->format('Ymd_His'); $timestamp = now()->format('Ymd_His');
$zipFilename = $customFilename ?: "backup_full_{$cleanDbName}_{$timestamp}.zip";
$zipFilename = basename($zipFilename); $isFull = ($includeMedia || count($targetTables) === count($allTables));
if (!str_ends_with($zipFilename, '.zip')) { $prefix = $includeMedia ? 'backup_semua' : 'backup_pilihan';
$zipFilename .= '.zip';
$filename = $customFilename ?: "{$prefix}_{$cleanDbName}_{$timestamp}.kmh";
$filename = basename($filename);
if (!str_ends_with($filename, '.kmh')) {
$filename .= '.kmh';
} }
$zipFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $zipFilename; // 1. Buat temporary SQL dump untuk tabel-tabel yang dipilih
$tempSqlFile = storage_path('app/temp_dump_' . uniqid() . '.sql');
// 1. Buat temporary SQL dump terlebih dahulu $this->dumpTablesToSqlFile($targetTables, $tempSqlFile);
$tempSqlName = "temp_db_{$timestamp}.sql";
$this->createDatabaseBackup($tempSqlName);
$tempSqlFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $tempSqlName;
// 2. Buat temporary ZIP container
$tempZipFile = storage_path('app/temp_pkg_' . uniqid() . '.zip');
$zip = new ZipArchive(); $zip = new ZipArchive();
if ($zip->open($zipFullPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { if ($zip->open($tempZipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
if (File::exists($tempSqlFullPath)) { @unlink($tempSqlFile);
File::delete($tempSqlFullPath); throw new RuntimeException('Gagal membuat paket arsip sementara.');
}
throw new RuntimeException("Gagal membuat file ZIP di: {$zipFullPath}");
} }
try { try {
// Masukkan database SQL ke dalam root arsip ZIP $zip->addFile($tempSqlFile, 'database.sql');
$zip->addFile($tempSqlFullPath, 'database.sql');
// Masukkan seluruh file media yang ada di storage/app/public (misal foto profil, foto kendaraan, simper) // Tambahkan file media jika diminta (Backup Semua)
$publicStorageDir = storage_path('app/public'); if ($includeMedia) {
if (File::isDirectory($publicStorageDir)) { $publicStorageDir = storage_path('app/public');
$files = File::allFiles($publicStorageDir); if (File::isDirectory($publicStorageDir)) {
foreach ($files as $file) { $files = File::allFiles($publicStorageDir);
$relativePath = 'storage/' . $file->getRelativePathname(); foreach ($files as $file) {
$zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath)); $relativePath = 'storage/' . $file->getRelativePathname();
$zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath));
}
} }
} }
// Tambahkan metadata ringkas manifest.json // Manifest informasi arsip .kmh
$manifest = [ $manifest = [
'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)', 'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)',
'format' => 'KMH_ENCRYPTED_V1',
'created_at' => now()->toIso8601String(), 'created_at' => now()->toIso8601String(),
'type' => 'full', 'type' => $includeMedia ? 'semua' : 'pilihan',
'database' => $database, 'database' => $database,
'table_count' => count($targetTables),
'tables' => $targetTables,
'has_media' => $includeMedia,
'laravel_version' => app()->version(), 'laravel_version' => app()->version(),
'php_version' => PHP_VERSION, 'php_version' => PHP_VERSION,
]; ];
$zip->addFromString('manifest.json', json_encode($manifest, JSON_PRETTY_PRINT)); $zip->addFromString('manifest.json', json_encode($manifest, JSON_PRETTY_PRINT));
$zip->close(); $zip->close();
// Hapus file temporary SQL @unlink($tempSqlFile);
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
return $zipFilename; // 3. Enkripsi seluruh paket ZIP menjadi file .kmh terenkripsi
$rawZipContent = file_get_contents($tempZipFile);
@unlink($tempZipFile);
$encryptedKmh = $this->encryptToKmh($rawZipContent);
$finalPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename;
file_put_contents($finalPath, $encryptedKmh);
return $filename;
} catch (\Throwable $e) { } catch (\Throwable $e) {
$zip->close(); if (is_file($tempSqlFile)) @unlink($tempSqlFile);
if (File::exists($tempSqlFullPath)) { if (is_file($tempZipFile)) @unlink($tempZipFile);
File::delete($tempSqlFullPath); throw new RuntimeException("Gagal membuat arsip terenkripsi .kmh: " . $e->getMessage(), 0, $e);
}
if (File::exists($zipFullPath)) {
File::delete($zipFullPath);
}
throw new RuntimeException("Gagal membuat full backup ZIP: " . $e->getMessage(), 0, $e);
} }
} }
/** /**
* Pulihkan (Restore) database & aset dari file backup (.sql atau .zip). * Pulihkan (Restore) data dari file .kmh (atau .sql / .zip sebagai fallback).
*/ */
public function restore(string $backupFilenameOrPath): void public function restore(string $backupFilenameOrPath): void
{ {
@@ -255,28 +252,107 @@ class DatabaseBackupService
throw new RuntimeException("File backup tidak ditemukan: {$filePath}"); throw new RuntimeException("File backup tidak ditemukan: {$filePath}");
} }
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION)); $content = file_get_contents($filePath);
$headerLen = strlen(self::KMH_MAGIC_HEADER);
// Jika file berformat .kmh terenkripsi
if (substr($content, 0, $headerLen) === self::KMH_MAGIC_HEADER) {
$this->restoreFromKmhContent($content);
return;
}
// Fallback untuk file .sql atau .zip warisan
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if ($extension === 'zip') { if ($extension === 'zip') {
$this->restoreFromZip($filePath); $this->restoreFromZip($filePath);
} elseif ($extension === 'sql') { } elseif ($extension === 'sql') {
$this->restoreFromSql($filePath); $this->restoreFromSql($filePath);
} elseif ($extension === 'gz') {
$this->restoreFromGzip($filePath);
} else { } else {
throw new RuntimeException("Format file tidak didukung untuk pemulihan: .{$extension}"); throw new RuntimeException("Format file tidak didukung untuk pemulihan: .{$extension}");
} }
} }
/** /**
* Pulihkan dari file SQL langsung. * Pulihkan dari konten terenkripsi .kmh.
*/
protected function restoreFromKmhContent(string $kmhContent): void
{
$decryptedZipContent = $this->decryptFromKmh($kmhContent);
$tempZipFile = storage_path('app/temp_restore_' . uniqid() . '.zip');
file_put_contents($tempZipFile, $decryptedZipContent);
try {
$this->restoreFromZip($tempZipFile);
@unlink($tempZipFile);
} catch (\Throwable $e) {
if (is_file($tempZipFile)) @unlink($tempZipFile);
throw $e;
}
}
/**
* Pulihkan dari file arsip ZIP.
*/
public function restoreFromZip(string $zipFilePath): void
{
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
}
$zip = new ZipArchive();
if ($zip->open($zipFilePath) !== true) {
throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}");
}
$tempExtractDir = storage_path('app/temp_extract_' . uniqid());
File::makeDirectory($tempExtractDir, 0755, true);
try {
$zip->extractTo($tempExtractDir);
$zip->close();
// 1. Eksekusi file SQL database
$sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql';
if (!File::exists($sqlFile)) {
$foundSql = File::glob($tempExtractDir . '/*.sql');
if (!empty($foundSql)) {
$sqlFile = $foundSql[0];
} else {
throw new RuntimeException('File database.sql tidak ditemukan di dalam paket arsip.');
}
}
$this->restoreFromSql($sqlFile);
// 2. Pulihkan file aset media ke storage/app/public jika ada
$extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage';
$targetStorageDir = storage_path('app/public');
if (File::isDirectory($extractedStorageDir)) {
if (!File::isDirectory($targetStorageDir)) {
File::makeDirectory($targetStorageDir, 0755, true);
}
File::copyDirectory($extractedStorageDir, $targetStorageDir);
}
File::deleteDirectory($tempExtractDir);
} catch (\Throwable $e) {
if (File::isDirectory($tempExtractDir)) {
File::deleteDirectory($tempExtractDir);
}
throw $e;
}
}
/**
* Eksekusi pemulihan dari file skrip SQL.
*/ */
public function restoreFromSql(string $sqlFilePath): void public function restoreFromSql(string $sqlFilePath): void
{ {
$pdo = DB::connection()->getPdo(); $pdo = DB::connection()->getPdo();
$driver = DB::connection()->getDriverName(); $driver = DB::connection()->getDriverName();
// Nonaktifkan pemeriksaan foreign key untuk mencegah deadlock/relasi urutan
if ($driver === 'sqlite') { if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = OFF;"); $pdo->exec("PRAGMA foreign_keys = OFF;");
} else { } else {
@@ -303,9 +379,7 @@ class DatabaseBackupService
while (($line = fgets($handle)) !== false) { while (($line = fgets($handle)) !== false) {
$trimmed = trim($line); $trimmed = trim($line);
// Lewati komentar baris tunggal jika tidak sedang di dalam quote
if (!$inQuotes && (str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*') || str_starts_with($trimmed, '#'))) { if (!$inQuotes && (str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*') || str_starts_with($trimmed, '#'))) {
// Cek jika komentar multi baris
if (str_starts_with($trimmed, '/*') && !str_ends_with($trimmed, '*/')) { if (str_starts_with($trimmed, '/*') && !str_ends_with($trimmed, '*/')) {
while (($line = fgets($handle)) !== false) { while (($line = fgets($handle)) !== false) {
if (str_contains($line, '*/')) break; if (str_contains($line, '*/')) break;
@@ -341,7 +415,6 @@ class DatabaseBackupService
$quoteChar = $char; $quoteChar = $char;
$currentQuery .= $char; $currentQuery .= $char;
} elseif ($char === ';') { } elseif ($char === ';') {
// Akhir dari sebuah statement SQL
$statement = trim($currentQuery); $statement = trim($currentQuery);
if ($statement !== '') { if ($statement !== '') {
$pdo->exec($statement); $pdo->exec($statement);
@@ -354,7 +427,6 @@ class DatabaseBackupService
} }
} }
// Jalankan statement terakhir jika ada yang tersisa tanpa titik koma
$finalStatement = trim($currentQuery); $finalStatement = trim($currentQuery);
if ($finalStatement !== '') { if ($finalStatement !== '') {
$pdo->exec($finalStatement); $pdo->exec($finalStatement);
@@ -379,96 +451,6 @@ class DatabaseBackupService
} }
} }
/**
* Pulihkan dari file full backup .zip (restore database.sql dan sinkronkan file media).
*/
public function restoreFromZip(string $zipFilePath): void
{
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
}
$zip = new ZipArchive();
if ($zip->open($zipFilePath) !== true) {
throw new RuntimeException("Gagal membuka file arsip ZIP: {$zipFilePath}");
}
$tempExtractDir = storage_path('app/temp_restore_' . uniqid());
File::makeDirectory($tempExtractDir, 0755, true);
try {
$zip->extractTo($tempExtractDir);
$zip->close();
// 1. Eksekusi file SQL database
$sqlFile = $tempExtractDir . DIRECTORY_SEPARATOR . 'database.sql';
if (!File::exists($sqlFile)) {
$foundSql = File::glob($tempExtractDir . '/*.sql');
if (!empty($foundSql)) {
$sqlFile = $foundSql[0];
} else {
throw new RuntimeException('File database.sql tidak ditemukan di dalam paket ZIP.');
}
}
$this->restoreFromSql($sqlFile);
// 2. Pulihkan file aset media ke storage/app/public jika ada
$extractedStorageDir = $tempExtractDir . DIRECTORY_SEPARATOR . 'storage';
$targetStorageDir = storage_path('app/public');
if (File::isDirectory($extractedStorageDir)) {
if (!File::isDirectory($targetStorageDir)) {
File::makeDirectory($targetStorageDir, 0755, true);
}
File::copyDirectory($extractedStorageDir, $targetStorageDir);
}
// Bersihkan temporary folder
File::deleteDirectory($tempExtractDir);
} catch (\Throwable $e) {
if (File::isDirectory($tempExtractDir)) {
File::deleteDirectory($tempExtractDir);
}
throw $e;
}
}
/**
* Pulihkan dari file SQL terkompresi Gzip (.sql.gz).
*/
protected function restoreFromGzip(string $gzFilePath): void
{
if (!function_exists('gzopen')) {
throw new RuntimeException('Ekstensi PHP zlib tidak tersedia untuk dekompresi gzip.');
}
$tempSqlFile = storage_path('app/temp_restore_' . uniqid() . '.sql');
$gz = gzopen($gzFilePath, 'rb');
$out = fopen($tempSqlFile, 'wb');
if (!$gz || !$out) {
throw new RuntimeException("Gagal mengekstrak file gzip: {$gzFilePath}");
}
while (!gzeof($gz)) {
fwrite($out, gzread($gz, 65536));
}
gzclose($gz);
fclose($out);
try {
$this->restoreFromSql($tempSqlFile);
File::delete($tempSqlFile);
} catch (\Throwable $e) {
if (File::exists($tempSqlFile)) {
File::delete($tempSqlFile);
}
throw $e;
}
}
/** /**
* Hapus file backup tertentu dari penyimpanan. * Hapus file backup tertentu dari penyimpanan.
*/ */
@@ -486,16 +468,6 @@ class DatabaseBackupService
/** /**
* Dapatkan informasi statistik penyimpanan backup dan database sistem. * Dapatkan informasi statistik penyimpanan backup dan database sistem.
*
* @return array{
* total_backups: int,
* total_size_raw: int,
* total_size_human: string,
* database_name: string,
* table_count: int,
* estimated_db_size_human: string,
* last_backup: ?array
* }
*/ */
public function getSystemStats(): array public function getSystemStats(): array
{ {
@@ -556,6 +528,126 @@ class DatabaseBackupService
return $names; return $names;
} }
/**
* Kelompokkan tabel database ke dalam modul-modul fungsional untuk memudahkan pilihan backup.
*
* @return array<string, array{name: string, description: string, tables: array<int, string>}>
*/
public function getTableGroups(): array
{
$allTables = $this->getAllTableNames();
$groups = [
'hse' => [
'name' => 'K3 / HSE (Karyawan & SIMPER)',
'description' => 'Data personil karyawan, master jenis SIMPER, dan izin mengemudi.',
'tables' => array_values(array_intersect($allTables, [
'employees', 'simper_types', 'employee_simpers'
])),
],
'qma' => [
'name' => 'QMA (Kendaraan, Alat Berat & P2H)',
'description' => 'Master unit LV/HE, checklist P2H, transfer unit, dan log aktivitas.',
'tables' => array_values(array_intersect($allTables, [
'vehicles', 'vehicle_activities', 'vehicle_location_histories',
'unit_transfers', 'unit_support_timesheets', 'p2h_templates',
'p2h_template_items', 'p2h_records', 'p2h_record_items'
])),
],
'pg' => [
'name' => 'Private Guard (Satpam & Pos Gerbang)',
'description' => 'Data personil satpam lapangan dan pos pemeriksaan gerbang.',
'tables' => array_values(array_intersect($allTables, [
'gates', 'security_guards'
])),
],
'rbac' => [
'name' => 'Pengguna & Hak Akses (RBAC)',
'description' => 'Akun pengguna, jabatan role, direct permissions, dan log aktivitas admin.',
'tables' => array_values(array_intersect($allTables, [
'users', 'roles', 'permissions', 'model_has_roles',
'model_has_permissions', 'role_has_permissions', 'admin_activity_logs'
])),
],
'system' => [
'name' => 'Sistem & Internal Database',
'description' => 'Migrasi, sesi, cache, dan antrean background jobs.',
'tables' => array_values(array_intersect($allTables, [
'migrations', 'sessions', 'cache', 'cache_locks',
'jobs', 'job_batches', 'failed_jobs', 'password_reset_tokens'
])),
],
];
// Kelompokkan tabel lain jika ada tabel kustom tambahan di database
$categorized = [];
foreach ($groups as $g) {
$categorized = array_merge($categorized, $g['tables']);
}
$otherTables = array_values(array_diff($allTables, $categorized));
if (!empty($otherTables)) {
$groups['other'] = [
'name' => 'Tabel Lainnya',
'description' => 'Tabel data tambahan sistem.',
'tables' => $otherTables,
];
}
return $groups;
}
/**
* Dump struktur dan data dari daftar tabel tertentu ke file SQL.
*
* @param array<int, string> $tables
*/
protected function dumpTablesToSqlFile(array $tables, string $targetSqlPath): void
{
$handle = fopen($targetSqlPath, 'w');
if (!$handle) {
throw new RuntimeException("Gagal membuka file SQL sementara untuk penulisan: {$targetSqlPath}");
}
try {
$pdo = DB::connection()->getPdo();
$driver = DB::connection()->getDriverName();
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$nowString = now()->format('Y-m-d H:i:s');
fwrite($handle, "-- ==============================================================\n");
fwrite($handle, "-- RKM-KMH SECURE DATABASE DUMP (PT Kerinci Merangin Hidro)\n");
fwrite($handle, "-- Dibuat pada : {$nowString} WIB\n");
fwrite($handle, "-- Database : {$database}\n");
fwrite($handle, "-- ==============================================================\n\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = OFF;\n\n");
} else {
fwrite($handle, "SET NAMES utf8mb4;\n");
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 0;\n");
fwrite($handle, "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';\n");
fwrite($handle, "SET time_zone = '+00:00';\n\n");
}
foreach ($tables as $tableName) {
$this->dumpTableStructureAndData($handle, $pdo, $tableName, $driver);
}
fwrite($handle, "\n-- ==============================================================\n");
if ($driver === 'sqlite') {
fwrite($handle, "PRAGMA foreign_keys = ON;\n");
} else {
fwrite($handle, "SET FOREIGN_KEY_CHECKS = 1;\n");
}
fwrite($handle, "-- END OF DUMP\n");
fclose($handle);
} catch (\Throwable $e) {
if (is_resource($handle)) fclose($handle);
throw $e;
}
}
/** /**
* Dump struktur dan data satu tabel database. * Dump struktur dan data satu tabel database.
*/ */
@@ -579,7 +671,6 @@ class DatabaseBackupService
fwrite($handle, $createTableSql . ";\n\n"); fwrite($handle, $createTableSql . ";\n\n");
} }
// Dump Data Baris (chunk 200 baris untuk efisiensi RAM)
fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n"); fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n");
$query = DB::table($tableName); $query = DB::table($tableName);
+277 -320
View File
@@ -4,265 +4,173 @@
@section('content') @section('content')
<div class="space-y-6"> <div class="space-y-6">
<!-- Header Halaman --> <!-- Header Halaman (Clean Minimalist) -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-2 border-b border-slate-100">
<div> <div>
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5"> <h1 class="text-xl font-bold text-slate-900 tracking-tight">
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span> Backup &amp; Restore Sistem
<span>Backup & Restore Sistem</span>
</h1> </h1>
<p class="text-xs text-slate-500 mt-1"> <p class="text-xs text-slate-500 mt-0.5">
Pencadangan database MySQL dan file media sistem secara berkala untuk perlindungan data dan pemulihan bencana (<em>disaster recovery</em>). Pencadangan terenkripsi berformat <code>.kmh</code> khusus untuk sistem RKM-KMH. File tidak dapat dibaca oleh sistem luar.
</p> </p>
</div> </div>
<div class="flex items-center gap-2.5 flex-wrap"> <div class="flex items-center gap-2.5">
<button type="button" <button type="button"
onclick="openUploadBackupModal()" onclick="openUploadBackupModal()"
class="px-4 py-2.5 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-bold text-xs transition flex items-center gap-2 shadow-2xs"> class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-semibold transition shadow-2xs">
<i class="fa-solid fa-cloud-arrow-up text-indigo-600"></i> Unggah File .kmh
<span>Unggah File Backup</span>
</button> </button>
<button type="button" <button type="button"
onclick="openCreateBackupModal()" onclick="openCreateBackupModal()"
class="px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs transition flex items-center gap-2 shadow-sm shadow-indigo-600/20"> class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs">
<i class="fa-solid fa-database text-xs"></i> Buat Backup Baru
<span>Buat Backup Baru</span>
</button> </button>
</div> </div>
</div> </div>
<!-- Alert Notifikasi Flash --> <!-- Alert Notifikasi Flash -->
@if(session('success')) @if(session('success'))
<div class="p-4 bg-emerald-50 border border-emerald-200 rounded-2xl flex items-center justify-between text-emerald-800 text-xs font-semibold animate-scale-in"> <div class="p-3.5 bg-emerald-50 border border-emerald-200 rounded-xl flex items-center justify-between text-emerald-900 text-xs font-medium">
<div class="flex items-center gap-2.5"> <span>{{ session('success') }}</span>
<i class="fa-solid fa-circle-check text-emerald-600 text-base flex-shrink-0"></i> <button type="button" onclick="this.parentElement.remove()" class="text-emerald-500 hover:text-emerald-700 ml-3 text-sm">&times;</button>
<span>{{ session('success') }}</span>
</div>
<button type="button" onclick="this.parentElement.remove()" class="text-emerald-500 hover:text-emerald-700 p-1">
<i class="fa-solid fa-xmark"></i>
</button>
</div> </div>
@endif @endif
@if(session('error')) @if(session('error'))
<div class="p-4 bg-rose-50 border border-rose-200 rounded-2xl flex items-center justify-between text-rose-800 text-xs font-semibold animate-scale-in"> <div class="p-3.5 bg-rose-50 border border-rose-200 rounded-xl flex items-center justify-between text-rose-900 text-xs font-medium">
<div class="flex items-center gap-2.5"> <span>{{ session('error') }}</span>
<i class="fa-solid fa-triangle-exclamation text-rose-600 text-base flex-shrink-0"></i> <button type="button" onclick="this.parentElement.remove()" class="text-rose-500 hover:text-rose-700 ml-3 text-sm">&times;</button>
<span>{{ session('error') }}</span>
</div>
<button type="button" onclick="this.parentElement.remove()" class="text-rose-500 hover:text-rose-700 p-1">
<i class="fa-solid fa-xmark"></i>
</button>
</div> </div>
@endif @endif
<!-- Kartu Metrik Ringkasan Backup & Database --> <!-- Ringkasan Metrik (Clean & Tanpa Ikon Berlebihan) -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4"> <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<!-- Total File Backup --> <div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs relative overflow-hidden group hover:border-indigo-300 transition"> <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Total File Backup</span>
<div class="flex items-center justify-between"> <div class="flex items-baseline gap-2 mt-1.5">
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Total File Backup</span> <span class="text-2xl font-bold text-slate-900">{{ number_format($stats['total_backups']) }}</span>
<span class="w-8 h-8 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-xs"> <span class="text-xs text-slate-500 font-medium">file (.kmh)</span>
<i class="fa-solid fa-server"></i>
</span>
</div> </div>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-2 block">{{ number_format($stats['total_backups']) }}</span> <span class="text-[11px] text-slate-400 block mt-1">Total kapasitas: {{ $stats['total_size_human'] }}</span>
<span class="text-[10px] text-slate-400 font-medium block mt-1">Arsip tersimpan di server</span>
</div> </div>
<!-- Total Ukuran Storage --> <div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs relative overflow-hidden group hover:border-indigo-300 transition"> <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Backup Terakhir</span>
<div class="flex items-center justify-between"> <div class="mt-1.5">
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Ukuran Arsip</span> <span class="text-sm font-bold text-slate-900 block truncate">
<span class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center text-xs"> {{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }}
<i class="fa-solid fa-hard-drive"></i> </span>
<span class="text-[11px] text-slate-400 block mt-1 truncate font-mono">
{{ $stats['last_backup']['filename'] ?? '-' }}
</span> </span>
</div> </div>
<span class="text-xl sm:text-2xl font-black text-slate-900 mt-2 block">{{ $stats['total_size_human'] }}</span>
<span class="text-[10px] text-slate-400 font-medium block mt-1">Kapasitas folder storage/app/backups</span>
</div> </div>
<!-- Backup Terakhir --> <div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs relative overflow-hidden group hover:border-indigo-300 transition"> <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Database Aktif</span>
<div class="flex items-center justify-between"> <div class="flex items-baseline gap-2 mt-1.5">
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Backup Terakhir</span> <span class="text-base font-bold text-slate-900 font-mono">{{ $stats['database_name'] }}</span>
<span class="w-8 h-8 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center text-xs"> <span class="text-xs text-slate-500">({{ $stats['table_count'] }} Tabel)</span>
<i class="fa-solid fa-clock-rotate-left"></i>
</span>
</div> </div>
<span class="text-sm sm:text-base font-bold text-slate-900 mt-2 block truncate" title="{{ $stats['last_backup']['created_at_human'] ?? '-' }}"> <span class="text-[11px] text-slate-400 block mt-1">Estimasi data: {{ $stats['estimated_db_size_human'] }}</span>
{{ $stats['last_backup']['created_at_human'] ?? 'Belum ada backup' }}
</span>
<span class="text-[10px] text-slate-400 font-medium block mt-1 truncate" title="{{ $stats['last_backup']['filename'] ?? '-' }}">
{{ $stats['last_backup']['filename'] ?? 'Klik Buat Backup Baru' }}
</span>
</div> </div>
<!-- Info Database Aktif -->
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs relative overflow-hidden group hover:border-indigo-300 transition">
<div class="flex items-center justify-between">
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Database Aktif</span>
<span class="w-8 h-8 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center text-xs">
<i class="fa-solid fa-database"></i>
</span>
</div>
<span class="text-sm sm:text-base font-bold text-slate-900 mt-2 block truncate">
{{ $stats['database_name'] }}
</span>
<span class="text-[10px] text-slate-400 font-medium block mt-1">
{{ $stats['table_count'] }} Tabel &bull; Estimasi {{ $stats['estimated_db_size_human'] }}
</span>
</div>
</div>
<!-- Banner Panduan Praktik Terbaik Backup -->
<div class="bg-gradient-to-r from-indigo-50/80 via-slate-50 to-emerald-50/60 border border-indigo-100 rounded-2xl p-4 sm:p-5 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div class="flex items-start gap-3.5">
<div class="w-10 h-10 rounded-2xl bg-indigo-600 text-white flex items-center justify-center text-base flex-shrink-0 shadow-sm shadow-indigo-600/20">
<i class="fa-solid fa-shield-halved"></i>
</div>
<div class="space-y-0.5">
<h4 class="text-xs font-bold text-slate-800 flex items-center gap-2">
<span>Panduan Keamanan & Pemulihan Sistem</span>
<span class="px-2 py-0.5 rounded-md bg-indigo-100 text-indigo-700 text-[10px] font-bold">Rekomendasi</span>
</h4>
<p class="text-[11px] text-slate-600 leading-relaxed max-w-3xl">
Disarankan untuk mengunduh arsip backup secara teratur ke perangkat fisik atau penyimpanan cloud terpisah. Sebelum melakukan pembaruan besar atau perubahan skema data, buat selalu backup terbaru sebagai cadangan darurat.
</p>
</div>
</div>
<button type="button"
onclick="openCreateBackupModal()"
class="px-3.5 py-2 rounded-xl bg-white border border-indigo-200 text-indigo-700 hover:bg-indigo-50 font-bold text-xs transition flex items-center gap-1.5 flex-shrink-0 shadow-2xs">
<i class="fa-solid fa-circle-plus text-indigo-600"></i>
<span>Cadangkan Sekarang</span>
</button>
</div> </div>
<!-- Tabel Daftar File Backup --> <!-- Tabel Daftar File Backup -->
<div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden"> <div class="bg-white border border-slate-200/80 rounded-2xl shadow-2xs overflow-hidden">
<div class="p-4 sm:px-6 border-b border-slate-100 flex items-center justify-between gap-4 flex-wrap"> <div class="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
<div> <h2 class="text-xs font-bold uppercase tracking-wider text-slate-600">
<h3 class="text-sm font-bold text-slate-900 flex items-center gap-2"> Daftar Arsip Backup
<i class="fa-solid fa-folder-open text-indigo-600"></i> </h2>
<span>Daftar Arsip Backup Tersimpan</span> <span class="text-[11px] text-slate-400 font-mono">
</h3> storage/app/backups/
<p class="text-[11px] text-slate-400 mt-0.5">Seluruh file tersimpan secara aman di direktori lokal server <code>storage/app/backups/</code></p> </span>
</div>
<div class="text-[11px] font-bold text-slate-500 bg-slate-50 border border-slate-200 px-3 py-1 rounded-xl">
<span>{{ count($backups) }} File Tersedia</span>
</div>
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="w-full text-left text-xs"> <table class="w-full text-left text-xs">
<thead> <thead>
<tr class="bg-slate-50/80 border-b border-slate-100 text-slate-500 font-bold uppercase tracking-wider text-[11px]"> <tr class="bg-slate-50/70 border-b border-slate-100 text-slate-400 font-bold uppercase tracking-wider text-[10px]">
<th class="py-3 px-4 sm:px-6">Nama File Backup</th> <th class="py-3 px-5">Nama File</th>
<th class="py-3 px-4">Jenis Backup</th> <th class="py-3 px-4">Tipe Backup</th>
<th class="py-3 px-4">Ukuran File</th> <th class="py-3 px-4">Ukuran</th>
<th class="py-3 px-4">Tanggal Dibuat</th> <th class="py-3 px-4">Tanggal Dibuat</th>
<th class="py-3 px-4 sm:px-6 text-center">Aksi & Pemulihan</th> <th class="py-3 px-5 text-right">Aksi</th>
</tr> </tr>
</thead> </thead>
<tbody class="divide-y divide-slate-100 font-medium"> <tbody class="divide-y divide-slate-100 font-medium">
@forelse($backups as $b) @forelse($backups as $b)
@php @php
$isFull = ($b['type'] === 'full'); $isFull = ($b['type'] === 'semua');
@endphp @endphp
<tr class="hover:bg-slate-50/70 transition"> <tr class="hover:bg-slate-50/50 transition">
<!-- Nama File --> <!-- Nama File -->
<td class="py-3.5 px-4 sm:px-6"> <td class="py-3 px-5">
<div class="flex items-center gap-3"> <div class="flex items-center gap-2">
<div class="w-9 h-9 rounded-xl flex items-center justify-center text-sm flex-shrink-0 {{ $isFull ? 'bg-amber-50 text-amber-600 border border-amber-200' : 'bg-indigo-50 text-indigo-600 border border-indigo-200' }}"> <span class="font-mono font-semibold text-slate-800 text-xs">
@if($isFull) {{ $b['filename'] }}
<i class="fa-solid fa-file-zipper"></i> </span>
@else @if($b['is_kmh'])
<i class="fa-solid fa-file-code"></i> <span class="px-1.5 py-0.2 rounded text-[9px] font-bold bg-indigo-50 text-indigo-700 border border-indigo-200">
@endif .kmh
</div> </span>
<div class="min-w-0"> @endif
<p class="font-bold text-slate-900 text-xs font-mono truncate" title="{{ $b['filename'] }}">
{{ $b['filename'] }}
</p>
<p class="text-[10px] text-slate-400 mt-0.5">
{{ $isFull ? 'Arsip ZIP (Database + Media Upload)' : 'File Skrip SQL Murni' }}
</p>
</div>
</div> </div>
</td> </td>
<!-- Jenis Backup --> <!-- Tipe Backup -->
<td class="py-3.5 px-4 whitespace-nowrap"> <td class="py-3 px-4 whitespace-nowrap">
@if($isFull) @if($isFull)
<span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[10px] font-bold bg-amber-50 text-amber-800 border border-amber-200"> <span class="inline-block px-2 py-0.5 rounded text-[11px] font-semibold bg-emerald-50 text-emerald-800 border border-emerald-200">
<i class="fa-solid fa-box-archive text-[9px]"></i> Backup Semua
<span>Full Backup + Media</span>
</span> </span>
@else @else
<span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[10px] font-bold bg-indigo-50 text-indigo-700 border border-indigo-200"> <span class="inline-block px-2 py-0.5 rounded text-[11px] font-semibold bg-slate-100 text-slate-700 border border-slate-200">
<i class="fa-solid fa-database text-[9px]"></i> Pilih Backup
<span>Database SQL</span>
</span> </span>
@endif @endif
</td> </td>
<!-- Ukuran File --> <!-- Ukuran File -->
<td class="py-3.5 px-4 whitespace-nowrap font-mono text-slate-700 font-semibold text-xs"> <td class="py-3 px-4 whitespace-nowrap font-mono text-slate-600">
{{ $b['size_human'] }} {{ $b['size_human'] }}
</td> </td>
<!-- Tanggal Dibuat --> <!-- Tanggal Dibuat -->
<td class="py-3.5 px-4 whitespace-nowrap"> <td class="py-3 px-4 whitespace-nowrap text-slate-600">
<span class="text-slate-800 font-semibold block text-xs">{{ $b['created_at_human'] }}</span> <span>{{ $b['created_at_human'] }}</span>
<span class="text-[10px] text-slate-400">{{ $b['created_at']->diffForHumans() }}</span>
</td> </td>
<!-- Aksi --> <!-- Aksi (Clean text buttons) -->
<td class="py-3.5 px-4 sm:px-6 text-center whitespace-nowrap"> <td class="py-3 px-5 text-right whitespace-nowrap">
<div class="inline-flex items-center gap-2"> <div class="inline-flex items-center gap-1.5">
<!-- Unduh -->
<a href="{{ route('admin.backups.download', $b['filename']) }}" <a href="{{ route('admin.backups.download', $b['filename']) }}"
class="px-2.5 py-1.5 rounded-xl bg-slate-100 hover:bg-indigo-50 text-slate-700 hover:text-indigo-700 text-xs font-bold transition flex items-center gap-1.5 border border-slate-200 hover:border-indigo-200" class="px-2.5 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-[11px] transition">
title="Unduh file backup ke komputer lokal"> Unduh
<i class="fa-solid fa-download text-[11px]"></i>
<span class="hidden sm:inline">Unduh</span>
</a> </a>
<!-- Pulihkan / Restore -->
<button type="button" <button type="button"
onclick="openRestoreModal('{{ $b['filename'] }}', '{{ $b['type_label'] }}', '{{ $b['size_human'] }}')" onclick="openRestoreModal('{{ $b['filename'] }}', '{{ $b['type_label'] }}', '{{ $b['size_human'] }}')"
class="px-2.5 py-1.5 rounded-xl bg-amber-50 hover:bg-amber-100 text-amber-800 hover:text-amber-900 text-xs font-bold transition flex items-center gap-1.5 border border-amber-200" class="px-2.5 py-1 rounded-lg border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 font-semibold text-[11px] transition">
title="Pulihkan database & data sistem dari backup ini"> Pulihkan
<i class="fa-solid fa-rotate-left text-[11px]"></i>
<span>Pulihkan</span>
</button> </button>
<!-- Hapus -->
<button type="button" <button type="button"
onclick="openDeleteBackupModal('{{ $b['filename'] }}')" onclick="openDeleteBackupModal('{{ $b['filename'] }}')"
class="w-8 h-8 rounded-xl bg-slate-100 hover:bg-rose-50 text-slate-400 hover:text-rose-600 flex items-center justify-center transition border border-transparent hover:border-rose-200" class="px-2.5 py-1 rounded-lg border border-rose-200 bg-white hover:bg-rose-50 text-rose-700 font-semibold text-[11px] transition">
title="Hapus file backup ini dari server"> Hapus
<i class="fa-solid fa-trash-can text-xs"></i>
</button> </button>
</div> </div>
</td> </td>
</tr> </tr>
@empty @empty
<tr> <tr>
<td colspan="5" class="py-12 px-4 text-center"> <td colspan="5" class="py-10 text-center">
<div class="w-14 h-14 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-2xl mx-auto mb-3"> <p class="text-xs text-slate-500 font-medium">Belum ada file backup yang tersimpan di server.</p>
<i class="fa-solid fa-database"></i>
</div>
<h4 class="text-sm font-bold text-slate-800">Belum Ada File Backup Tersimpan</h4>
<p class="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
Amankan data sistem Anda dengan membuat cadangan database pertama sekarang.
</p>
<button type="button" <button type="button"
onclick="openCreateBackupModal()" onclick="openCreateBackupModal()"
class="mt-4 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-sm transition inline-flex items-center gap-2"> class="mt-2.5 px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-semibold transition">
<i class="fa-solid fa-circle-plus"></i> Buat Backup Pertama
<span>Buat Backup Baru</span>
</button> </button>
</td> </td>
</tr> </tr>
@@ -274,70 +182,132 @@
</div> </div>
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- MODAL: BUAT BACKUP BARU --> <!-- MODAL: BUAT BACKUP (2 PILIHAN: PILIH BACKUP / BACKUP SEMUA) -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
<div id="createBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto"> <div id="createBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
<div class="bg-white rounded-3xl max-w-md w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100"> <div class="bg-white rounded-2xl max-w-2xl w-full shadow-xl overflow-hidden animate-scale-in border border-slate-100 flex flex-col max-h-[92vh]">
<div class="px-6 py-4.5 border-b border-slate-100 flex items-center justify-between"> <!-- Header Modal -->
<h3 class="text-base font-bold text-slate-800 flex items-center gap-2"> <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between flex-shrink-0">
<i class="fa-solid fa-database text-indigo-600"></i> <div>
<span>Buat Backup Baru</span> <h3 class="text-base font-bold text-slate-900">Buat Backup Baru</h3>
</h3> <p class="text-xs text-slate-400 mt-0.5">Pilih mode pencadangan terenkripsi berformat .kmh.</p>
<button type="button" onclick="closeCreateBackupModal()" class="text-slate-400 hover:text-slate-600 p-1"> </div>
<i class="fa-solid fa-xmark text-lg"></i> <button type="button" onclick="closeCreateBackupModal()" class="text-slate-400 hover:text-slate-600 text-lg p-1">&times;</button>
</button>
</div> </div>
<form id="createBackupForm" method="POST" action="{{ route('admin.backups.store') }}" onsubmit="handleBackupSubmit(this)" class="p-6 space-y-4"> <form id="createBackupForm" method="POST" action="{{ route('admin.backups.store') }}" onsubmit="handleBackupSubmit(this)" class="flex flex-col flex-1 min-h-0">
@csrf @csrf
<p class="text-xs text-slate-500 leading-relaxed"> <div class="p-5 space-y-4 overflow-y-auto flex-1">
Pilih cakupan data yang ingin dicadangkan. Proses ini akan berjalan di latar belakang dan menyimpan file hasil cadangan di server. <!-- Dua Pilihan Utama -->
</p> <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<!-- Opsi 1: Pilih Backup (Tabel Tertentu) -->
<label id="scopeCardPilihan" class="p-4 rounded-xl border-2 border-indigo-600 bg-indigo-50/30 cursor-pointer transition block">
<div class="flex items-start gap-2.5">
<input type="radio"
name="backup_scope"
value="pilihan"
id="radioScopePilihan"
checked
onchange="toggleBackupScopeUI('pilihan')"
class="mt-0.5 text-indigo-600 focus:ring-indigo-500">
<div>
<span class="block text-xs font-bold text-slate-900">Pilih Backup</span>
<span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed">
Pilih tabel atau modul data tertentu yang ingin dicadangkan sesuai kebutuhan.
</span>
</div>
</div>
</label>
<!-- Pilihan Jenis Backup --> <!-- Opsi 2: Backup Semua -->
<div class="space-y-3"> <label id="scopeCardSemua" class="p-4 rounded-xl border-2 border-slate-200 hover:border-slate-300 bg-white cursor-pointer transition block">
<!-- Opsi 1: Database Saja --> <div class="flex items-start gap-2.5">
<label class="block p-4 rounded-2xl border-2 border-indigo-600 bg-indigo-50/40 cursor-pointer transition relative has-[:checked]:border-indigo-600 has-[:checked]:bg-indigo-50/40"> <input type="radio"
<div class="flex items-start gap-3"> name="backup_scope"
<input type="radio" name="type" value="database" checked class="mt-0.5 text-indigo-600 focus:ring-indigo-500"> value="semua"
<div class="flex-1"> id="radioScopeSemua"
<span class="block text-xs font-bold text-slate-900">Database Saja (.sql)</span> onchange="toggleBackupScopeUI('semua')"
<span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed"> class="mt-0.5 text-indigo-600 focus:ring-indigo-500">
Mencadangkan seluruh 29 tabel aktif MySQL dan data operasional. Proses sangat cepat dan ukuran file ringan (~500 KB). <div>
</span> <span class="block text-xs font-bold text-slate-900">Backup Semua</span>
<span class="inline-block mt-2 px-2 py-0.5 rounded-md bg-emerald-100 text-emerald-800 font-bold text-[10px]"> <span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed">
Direkomendasikan Rutin Cadangkan seluruh tabel database (29 tabel) + seluruh file media upload.
</span> </span>
</div>
</div>
</label>
</div>
<!-- Bagian Detail Checklist untuk "Pilih Backup" -->
<div id="pilihanTableSection" class="space-y-3 pt-2">
<div class="flex items-center justify-between pb-1 border-b border-slate-100">
<div>
<span class="text-xs font-bold text-slate-800">Daftar Tabel yang Dicadangkan</span>
<span class="text-[11px] text-slate-400 block">Centang tabel yang ingin dimasukkan ke dalam file .kmh</span>
</div>
<div class="flex items-center gap-2">
<button type="button" onclick="selectAllTables(true)" class="text-[11px] text-indigo-600 hover:underline font-semibold">
Pilih Semua
</button>
<span class="text-slate-300">&bull;</span>
<button type="button" onclick="selectAllTables(false)" class="text-[11px] text-slate-500 hover:underline font-semibold">
Batal Pilih
</button>
</div> </div>
</div> </div>
</label>
<!-- Opsi 2: Full Backup --> <!-- Kelompok Modul Tabel -->
<label class="block p-4 rounded-2xl border-2 border-slate-200 hover:border-slate-300 bg-white cursor-pointer transition relative has-[:checked]:border-indigo-600 has-[:checked]:bg-indigo-50/40"> <div class="space-y-3 max-h-64 overflow-y-auto pr-1">
<div class="flex items-start gap-3"> @foreach($tableGroups as $groupKey => $group)
<input type="radio" name="type" value="full" class="mt-0.5 text-indigo-600 focus:ring-indigo-500"> @if(!empty($group['tables']))
<div class="flex-1"> <div class="border border-slate-200/80 rounded-xl p-3 bg-slate-50/50">
<span class="block text-xs font-bold text-slate-900">Full Backup Lengkap (.zip)</span> <div class="flex items-center justify-between mb-1.5">
<span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed"> <span class="text-xs font-bold text-slate-800">{{ $group['name'] }}</span>
Mencadangkan Database SQL + seluruh berkas media upload di <code>storage/app/public</code> (foto karyawan, foto kendaraan, SIMPER). <span class="text-[10px] text-slate-400">{{ count($group['tables']) }} Tabel</span>
</span> </div>
<span class="inline-block mt-2 px-2 py-0.5 rounded-md bg-slate-100 text-slate-600 font-bold text-[10px]"> <div class="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
Menyeluruh & Total @foreach($group['tables'] as $tbl)
</span> <label class="flex items-center gap-2 text-xs text-slate-700 cursor-pointer select-none py-0.5 hover:text-slate-900">
</div> <input type="checkbox"
name="selected_tables[]"
value="{{ $tbl }}"
checked
class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 table-checkbox">
<span class="font-mono text-[11px]">{{ $tbl }}</span>
</label>
@endforeach
</div>
</div>
@endif
@endforeach
</div> </div>
</label>
<!-- Opsi Sertakan Media untuk Pilih Backup -->
<label class="flex items-center gap-2 text-xs text-slate-700 cursor-pointer pt-2 select-none border-t border-slate-100">
<input type="checkbox" name="include_media" value="1" class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
<span class="text-xs font-medium">Sertakan juga berkas media upload di <code>storage/app/public</code></span>
</label>
</div>
<!-- Bagian Penjelasan Ringkas untuk "Backup Semua" -->
<div id="semuaTableSection" class="hidden p-4 rounded-xl bg-slate-50 border border-slate-200 text-xs text-slate-600 space-y-1 leading-relaxed">
<p class="font-bold text-slate-800">Cakupan Backup Semua:</p>
<ul class="list-disc list-inside text-[11px] space-y-0.5 text-slate-600 pl-1">
<li>Seluruh tabel dan struktur database MySQL sistem RKM-KMH.</li>
<li>Seluruh file media upload (foto profil karyawan, foto armada kendaraan, stiker izin SIMPER).</li>
<li>Dikompresi dan dienkripsi AES-256-CBC ke dalam format tunggal <strong>.kmh</strong>.</li>
</ul>
</div>
</div> </div>
<!-- Tombol Footer --> <!-- Footer Modal -->
<div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-2.5"> <div class="px-5 py-3.5 bg-slate-50 border-t border-slate-100 flex items-center justify-end gap-2.5 flex-shrink-0">
<button type="button" onclick="closeCreateBackupModal()" class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition"> <button type="button" onclick="closeCreateBackupModal()" class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white text-slate-600 font-semibold text-xs transition">
Batal Batal
</button> </button>
<button type="submit" id="createBackupSubmitBtn" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-sm transition flex items-center gap-2"> <button type="submit" id="createBackupSubmitBtn" class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-xs transition shadow-xs">
<i class="fa-solid fa-play text-[10px]"></i> <span id="createBackupBtnText">Mulai Pencadangan (.kmh)</span>
<span id="createBackupBtnText">Mulai Pencadangan</span>
</button> </button>
</div> </div>
</form> </form>
@@ -345,52 +315,40 @@
</div> </div>
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- MODAL: UNGGAH FILE BACKUP --> <!-- MODAL: UNGGAH FILE BACKUP (.KMH) -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
<div id="uploadBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto"> <div id="uploadBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-md w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100"> <div class="bg-white rounded-2xl max-w-md w-full shadow-xl overflow-hidden animate-scale-in border border-slate-100">
<div class="px-6 py-4.5 border-b border-slate-100 flex items-center justify-between"> <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
<h3 class="text-base font-bold text-slate-800 flex items-center gap-2"> <h3 class="text-base font-bold text-slate-900">Unggah File Backup (.kmh)</h3>
<i class="fa-solid fa-cloud-arrow-up text-indigo-600"></i> <button type="button" onclick="closeUploadBackupModal()" class="text-slate-400 hover:text-slate-600 text-lg p-1">&times;</button>
<span>Unggah File Backup</span>
</h3>
<button type="button" onclick="closeUploadBackupModal()" class="text-slate-400 hover:text-slate-600 p-1">
<i class="fa-solid fa-xmark text-lg"></i>
</button>
</div> </div>
<form id="uploadBackupForm" method="POST" action="{{ route('admin.backups.upload') }}" enctype="multipart/form-data" class="p-6 space-y-4"> <form id="uploadBackupForm" method="POST" action="{{ route('admin.backups.upload') }}" enctype="multipart/form-data" class="p-5 space-y-4">
@csrf @csrf
<!-- Upload Drop Area -->
<div> <div>
<label class="block text-xs font-bold text-slate-700 mb-2">Pilih File Arsip Backup <span class="text-rose-500">*</span></label> <label class="block text-xs font-semibold text-slate-700 mb-2">Pilih File .kmh</label>
<div class="border-2 border-dashed border-slate-300 hover:border-indigo-500 rounded-2xl p-6 text-center bg-slate-50/60 hover:bg-white transition cursor-pointer relative" <div class="border-2 border-dashed border-slate-300 hover:border-indigo-500 rounded-xl p-5 text-center bg-slate-50 hover:bg-white transition cursor-pointer"
onclick="document.getElementById('backupFileInput').click()"> onclick="document.getElementById('backupFileInput').click()">
<i class="fa-solid fa-file-arrow-up text-3xl text-indigo-600 mb-2 block"></i> <p class="text-xs font-bold text-slate-800" id="uploadFileName">Klik untuk memilih file</p>
<p class="text-xs font-bold text-slate-800" id="uploadFileName">Klik untuk memilih file backup</p> <p class="text-[11px] text-slate-400 mt-1">Format arsip terenkripsi: .kmh (Maks. 200 MB)</p>
<p class="text-[11px] text-slate-400 mt-1">Mendukung format SQL (.sql), Arsip ZIP (.zip), atau Gzip (.sql.gz)</p>
<input type="file" <input type="file"
name="backup_file" name="backup_file"
id="backupFileInput" id="backupFileInput"
accept=".sql,.zip,.gz" accept=".kmh,.sql,.zip"
required required
class="hidden" class="hidden"
onchange="handleUploadFileChange(this)"> onchange="handleUploadFileChange(this)">
</div> </div>
<p class="text-[10px] text-slate-400 mt-1.5 flex items-center gap-1">
<i class="fa-solid fa-circle-info text-indigo-600"></i>
<span>Ukuran maksimal yang diizinkan hingga 200 MB.</span>
</p>
</div> </div>
<div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-2.5"> <div class="pt-3 border-t border-slate-100 flex items-center justify-end gap-2.5">
<button type="button" onclick="closeUploadBackupModal()" class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition"> <button type="button" onclick="closeUploadBackupModal()" class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white text-slate-600 font-semibold text-xs transition">
Batal Batal
</button> </button>
<button type="submit" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold shadow-sm transition flex items-center gap-2"> <button type="submit" class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-xs transition shadow-xs">
<i class="fa-solid fa-upload text-xs"></i> Unggah File
<span>Unggah ke Server</span>
</button> </button>
</div> </div>
</form> </form>
@@ -400,70 +358,46 @@
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- MODAL: KONFIRMASI PEMULIHAN (RESTORE) --> <!-- MODAL: KONFIRMASI PEMULIHAN (RESTORE) -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
<div id="restoreModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto"> <div id="restoreModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-lg w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100"> <div class="bg-white rounded-2xl max-w-md w-full shadow-xl overflow-hidden animate-scale-in border border-slate-100">
<!-- Header Bahaya --> <div class="px-5 py-4 bg-amber-50/70 border-b border-amber-100 flex items-center justify-between">
<div class="px-6 py-4.5 bg-amber-50/80 border-b border-amber-100 flex items-center justify-between"> <h3 class="text-base font-bold text-amber-900">Konfirmasi Pemulihan Sistem</h3>
<h3 class="text-base font-bold text-amber-900 flex items-center gap-2"> <button type="button" onclick="closeRestoreModal()" class="text-slate-400 hover:text-slate-600 text-lg p-1">&times;</button>
<i class="fa-solid fa-triangle-exclamation text-amber-600"></i>
<span>Konfirmasi Pemulihan Sistem (Restore)</span>
</h3>
<button type="button" onclick="closeRestoreModal()" class="text-slate-400 hover:text-slate-600 p-1">
<i class="fa-solid fa-xmark text-lg"></i>
</button>
</div> </div>
<form id="restoreForm" method="POST" action="" onsubmit="handleRestoreSubmit(this)" class="p-6 space-y-4"> <form id="restoreForm" method="POST" action="" onsubmit="handleRestoreSubmit(this)" class="p-5 space-y-4">
@csrf @csrf
<!-- Warning Card --> <div class="p-3 rounded-xl bg-rose-50 border border-rose-200 text-xs text-rose-900 leading-relaxed">
<div class="p-4 rounded-2xl bg-rose-50 border border-rose-200 text-xs text-rose-900 space-y-1.5"> <strong>Peringatan:</strong> Proses ini akan menimpa data di database saat ini dengan isi arsip backup yang dipilih.
<p class="font-black text-rose-950 flex items-center gap-2">
<i class="fa-solid fa-circle-exclamation text-rose-600 text-sm"></i>
<span>PERINGATAN KRITIKAL: TINDAKAN INI AKAN MENIMPA DATA</span>
</p>
<p class="text-[11px] leading-relaxed text-rose-800">
Proses pemulihan akan menimpa (overwrite) seluruh database saat ini dengan isi arsip backup yang dipilih. Data yang dibuat setelah tanggal backup ini akan tergantikan.
</p>
</div> </div>
<!-- Rincian Target File Backup --> <div class="bg-slate-50 p-3 rounded-xl border border-slate-200 text-xs space-y-1 font-mono">
<div class="bg-slate-50 rounded-2xl p-3.5 border border-slate-200/80 text-xs space-y-1">
<div class="flex justify-between"> <div class="flex justify-between">
<span class="text-slate-400 text-[11px]">Nama Arsip:</span> <span class="text-slate-400">File:</span>
<span id="restoreTargetFilename" class="font-bold font-mono text-slate-800"></span> <span id="restoreTargetFilename" class="font-bold text-slate-800"></span>
</div>
<div class="flex justify-between">
<span class="text-slate-400 text-[11px]">Tipe & Ukuran:</span>
<span id="restoreTargetMeta" class="font-semibold text-slate-700"></span>
</div> </div>
</div> </div>
<!-- Input Verifikasi Keamanan -->
<div> <div>
<label class="block text-xs font-bold text-slate-800 mb-1"> <label class="block text-xs font-semibold text-slate-800 mb-1">
Konfirmasi Keamanan <span class="text-rose-500">*</span> Ketik kata <span class="font-mono font-bold text-slate-900 bg-slate-100 px-1 py-0.5 rounded">PULIHKAN</span> atau masukkan password Anda:
</label> </label>
<p class="text-[11px] text-slate-500 mb-2 leading-relaxed">
Untuk melanjutkan, ketik kata <strong class="text-slate-900 font-mono bg-slate-100 px-1.5 py-0.5 rounded border border-slate-200">PULIHKAN</strong> pada kolom di bawah atau masukkan password akun Super Admin Anda:
</p>
<input type="text" <input type="text"
name="confirmation" name="confirmation"
id="restoreConfirmationInput" id="restoreConfirmationInput"
placeholder="Ketik PULIHKAN atau password akun Anda..." placeholder="PULIHKAN atau password..."
required required
autocomplete="off" autocomplete="off"
class="w-full text-xs px-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-slate-800 font-bold focus:outline-none focus:border-amber-500 focus:ring-2 focus:ring-amber-500/10"> class="w-full text-xs px-3 py-2 rounded-xl border border-slate-200 focus:outline-none focus:border-amber-500 font-semibold">
</div> </div>
<!-- Tombol Footer --> <div class="pt-3 border-t border-slate-100 flex items-center justify-end gap-2.5">
<div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-2.5"> <button type="button" onclick="closeRestoreModal()" class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white text-slate-600 font-semibold text-xs transition">
<button type="button" onclick="closeRestoreModal()" class="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-xl text-xs font-bold transition">
Batal Batal
</button> </button>
<button type="submit" id="restoreSubmitBtn" class="px-5 py-2.5 bg-amber-600 hover:bg-amber-700 text-white rounded-xl text-xs font-bold shadow-sm transition flex items-center gap-2"> <button type="submit" id="restoreSubmitBtn" class="px-4 py-2 rounded-xl bg-amber-600 hover:bg-amber-700 text-white font-semibold text-xs transition shadow-xs">
<i class="fa-solid fa-rotate-left text-xs"></i> <span id="restoreBtnText">Ya, Pulihkan Sistem</span>
<span id="restoreBtnText">Ya, Pulihkan Sistem Sekarang</span>
</button> </button>
</div> </div>
</form> </form>
@@ -471,35 +405,63 @@
</div> </div>
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- MODAL: KONFIRMASI HAPUS BACKUP --> <!-- MODAL: KONFIRMASI HAPUS -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
<div id="deleteBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4"> <div id="deleteBackupModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/50 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-sm w-full p-6 shadow-2xl overflow-hidden animate-scale-in border border-slate-100 text-center"> <div class="bg-white rounded-2xl max-w-sm w-full p-5 shadow-xl border border-slate-100 text-center">
<div class="w-12 h-12 rounded-2xl bg-rose-50 text-rose-600 flex items-center justify-center text-xl mx-auto mb-3"> <h3 class="text-sm font-bold text-slate-900">Hapus File Backup?</h3>
<i class="fa-solid fa-trash-can"></i> <p class="text-xs text-slate-500 mt-1">
</div> File <span id="deleteBackupFilename" class="font-mono font-semibold text-slate-800"></span> akan dihapus permanen dari server.
<h3 class="text-base font-bold text-slate-900">Hapus File Backup?</h3>
<p class="text-xs text-slate-500 mt-1.5 leading-relaxed">
Apakah Anda yakin ingin menghapus file backup <span id="deleteBackupFilename" class="font-mono font-bold text-slate-800"></span> dari server? File yang dihapus tidak dapat dipulihkan kembali.
</p> </p>
<form id="deleteBackupForm" method="POST" action="" class="mt-6 flex items-center justify-center gap-2.5"> <form id="deleteBackupForm" method="POST" action="" class="mt-5 flex items-center justify-center gap-2">
@csrf @csrf
@method('DELETE') @method('DELETE')
<button type="button" onclick="closeDeleteBackupModal()" class="flex-1 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition"> <button type="button" onclick="closeDeleteBackupModal()" class="flex-1 px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-semibold transition">
Batal Batal
</button> </button>
<button type="submit" class="flex-1 px-4 py-2.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl text-xs font-bold shadow-sm transition"> <button type="submit" class="flex-1 px-3 py-2 bg-rose-600 hover:bg-rose-700 text-white rounded-xl text-xs font-semibold transition">
Hapus File Hapus
</button> </button>
</form> </form>
</div> </div>
</div> </div>
<!-- ========================================================================= --> <!-- ========================================================================= -->
<!-- JAVASCRIPT HELPER MODAL & INTERAKSI --> <!-- JAVASCRIPT LOGIC INTERAKTIF -->
<!-- ========================================================================= --> <!-- ========================================================================= -->
<script> <script>
function toggleBackupScopeUI(scope) {
const cardPilihan = document.getElementById('scopeCardPilihan');
const cardSemua = document.getElementById('scopeCardSemua');
const sectionPilihan = document.getElementById('pilihanTableSection');
const sectionSemua = document.getElementById('semuaTableSection');
if (scope === 'pilihan') {
cardPilihan.classList.add('border-indigo-600', 'bg-indigo-50/30');
cardPilihan.classList.remove('border-slate-200', 'bg-white');
cardSemua.classList.remove('border-indigo-600', 'bg-indigo-50/30');
cardSemua.classList.add('border-slate-200', 'bg-white');
sectionPilihan.classList.remove('hidden');
sectionSemua.classList.add('hidden');
} else {
cardSemua.classList.add('border-indigo-600', 'bg-indigo-50/30');
cardSemua.classList.remove('border-slate-200', 'bg-white');
cardPilihan.classList.remove('border-indigo-600', 'bg-indigo-50/30');
cardPilihan.classList.add('border-slate-200', 'bg-white');
sectionPilihan.classList.add('hidden');
sectionSemua.classList.remove('hidden');
}
}
function selectAllTables(checked) {
document.querySelectorAll('.table-checkbox').forEach(cb => {
cb.checked = checked;
});
}
function openCreateBackupModal() { function openCreateBackupModal() {
document.getElementById('createBackupModal').classList.remove('hidden'); document.getElementById('createBackupModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open'); document.documentElement.classList.add('modal-open');
@@ -517,9 +479,7 @@
btn.disabled = true; btn.disabled = true;
btn.classList.add('opacity-75', 'cursor-not-allowed'); btn.classList.add('opacity-75', 'cursor-not-allowed');
} }
if (text) { if (text) text.textContent = 'Memproses Arsip .kmh...';
text.textContent = 'Memproses Pencadangan...';
}
} }
function openUploadBackupModal() { function openUploadBackupModal() {
@@ -542,7 +502,6 @@
function openRestoreModal(filename, typeLabel, sizeHuman) { function openRestoreModal(filename, typeLabel, sizeHuman) {
document.getElementById('restoreForm').action = `/admin/backups/${encodeURIComponent(filename)}/restore`; document.getElementById('restoreForm').action = `/admin/backups/${encodeURIComponent(filename)}/restore`;
document.getElementById('restoreTargetFilename').textContent = filename; document.getElementById('restoreTargetFilename').textContent = filename;
document.getElementById('restoreTargetMeta').textContent = `${typeLabel} (${sizeHuman})`;
document.getElementById('restoreConfirmationInput').value = ''; document.getElementById('restoreConfirmationInput').value = '';
document.getElementById('restoreModal').classList.remove('hidden'); document.getElementById('restoreModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open'); document.documentElement.classList.add('modal-open');
@@ -560,9 +519,7 @@
btn.disabled = true; btn.disabled = true;
btn.classList.add('opacity-75', 'cursor-not-allowed'); btn.classList.add('opacity-75', 'cursor-not-allowed');
} }
if (text) { if (text) text.textContent = 'Memulihkan Sistem...';
text.textContent = 'Memulihkan Sistem (Mohon Tunggu)...';
}
} }
function openDeleteBackupModal(filename) { function openDeleteBackupModal(filename) {
+68 -62
View File
@@ -2,7 +2,6 @@
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\AdminActivityLog;
use App\Models\User; use App\Models\User;
use App\Services\DatabaseBackupService; use App\Services\DatabaseBackupService;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -57,9 +56,10 @@ class BackupAndRestoreTest extends TestCase
$response->assertViewIs('admin.backups.index'); $response->assertViewIs('admin.backups.index');
$response->assertViewHas('backups'); $response->assertViewHas('backups');
$response->assertViewHas('stats'); $response->assertViewHas('stats');
$response->assertSee('Backup & Restore Sistem'); $response->assertViewHas('tableGroups');
$response->assertSee('Backup &amp; Restore Sistem', false);
$response->assertSee('Buat Backup Baru'); $response->assertSee('Buat Backup Baru');
$response->assertSee('Unggah File Backup'); $response->assertSee('.kmh');
} }
public function test_non_super_admin_cannot_access_backup_page(): void public function test_non_super_admin_cannot_access_backup_page(): void
@@ -77,11 +77,12 @@ class BackupAndRestoreTest extends TestCase
$response->assertStatus(403); $response->assertStatus(403);
} }
public function test_super_admin_can_create_database_backup(): void public function test_super_admin_can_create_pilihan_backup_kmh(): void
{ {
$response = $this->actingAs($this->superAdmin) $response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.store'), [ ->post(route('admin.backups.store'), [
'type' => 'database', 'backup_scope' => 'pilihan',
'selected_tables' => ['users', 'roles'],
]); ]);
$response->assertSessionHas('success'); $response->assertSessionHas('success');
@@ -89,8 +90,17 @@ class BackupAndRestoreTest extends TestCase
$backups = $this->backupService->listBackups(); $backups = $this->backupService->listBackups();
$this->assertNotEmpty($backups); $this->assertNotEmpty($backups);
$this->assertEquals('database', $backups[0]['type']); $latest = $backups[0];
$this->assertStringEndsWith('.sql', $backups[0]['filename']);
$this->assertEquals('pilihan', $latest['type']);
$this->assertTrue($latest['is_kmh']);
$this->assertStringEndsWith('.kmh', $latest['filename']);
// Verifikasi enkripsi: File harus diawali header magic KMH dan isinya terenkripsi
$rawContent = file_get_contents($latest['path']);
$this->assertStringStartsWith(DatabaseBackupService::KMH_MAGIC_HEADER, $rawContent);
// Pastikan tidak ada plain text SQL di file mentah
$this->assertStringNotContainsString('INSERT INTO `users`', $rawContent);
// Verifikasi log aktivitas // Verifikasi log aktivitas
$this->assertDatabaseHas('admin_activity_logs', [ $this->assertDatabaseHas('admin_activity_logs', [
@@ -100,9 +110,28 @@ class BackupAndRestoreTest extends TestCase
]); ]);
} }
public function test_super_admin_can_download_backup_file(): void public function test_super_admin_can_create_semua_backup_kmh(): void
{ {
$filename = $this->backupService->createDatabaseBackup('test_dl.sql'); $response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.store'), [
'backup_scope' => 'semua',
]);
$response->assertSessionHas('success');
$response->assertRedirect();
$backups = $this->backupService->listBackups();
$this->assertNotEmpty($backups);
$latest = $backups[0];
$this->assertEquals('semua', $latest['type']);
$this->assertTrue($latest['is_kmh']);
$this->assertStringEndsWith('.kmh', $latest['filename']);
}
public function test_super_admin_can_download_kmh_backup_file(): void
{
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_dl.kmh');
$response = $this->actingAs($this->superAdmin) $response = $this->actingAs($this->superAdmin)
->get(route('admin.backups.download', $filename)); ->get(route('admin.backups.download', $filename));
@@ -111,9 +140,10 @@ class BackupAndRestoreTest extends TestCase
$response->assertHeader('content-disposition'); $response->assertHeader('content-disposition');
} }
public function test_super_admin_can_upload_backup_file(): void public function test_super_admin_can_upload_kmh_backup_file(): void
{ {
$file = UploadedFile::fake()->createWithContent('test_uploaded_backup.sql', '-- MySQL dump test\nSET FOREIGN_KEY_CHECKS=0;\n'); $validKmhContent = $this->backupService->encryptToKmh('dummy zip or sql content');
$file = UploadedFile::fake()->createWithContent('test_uploaded.kmh', $validKmhContent);
$response = $this->actingAs($this->superAdmin) $response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.upload'), [ ->post(route('admin.backups.upload'), [
@@ -122,21 +152,14 @@ class BackupAndRestoreTest extends TestCase
$response->assertSessionHas('success'); $response->assertSessionHas('success');
$targetPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_uploaded_backup.sql'; $targetPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_uploaded.kmh';
$this->assertTrue(File::exists($targetPath)); $this->assertTrue(File::exists($targetPath));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'create',
'module' => 'Backup & Restore',
'target_name' => 'test_uploaded_backup.sql',
]);
} }
public function test_restore_requires_valid_confirmation_or_password(): void public function test_restore_requires_valid_confirmation_or_password(): void
{ {
$filename = $this->backupService->createDatabaseBackup('test_for_restore.sql'); $filename = $this->backupService->createKmhBackup(['users'], false, 'test_for_restore.kmh');
// Percobaan tanpa konfirmasi yang benar
$response = $this->actingAs($this->superAdmin) $response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', $filename), [ ->post(route('admin.backups.restore', $filename), [
'confirmation' => 'SALAH', 'confirmation' => 'SALAH',
@@ -146,9 +169,9 @@ class BackupAndRestoreTest extends TestCase
$response->assertSessionHas('error'); $response->assertSessionHas('error');
} }
public function test_super_admin_can_restore_from_backup_with_confirmation_string(): void public function test_super_admin_can_restore_from_kmh_backup(): void
{ {
$filename = $this->backupService->createDatabaseBackup('test_real_restore.sql'); $filename = $this->backupService->createKmhBackup(['users'], false, 'test_real_restore.kmh');
$response = $this->actingAs($this->superAdmin) $response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', $filename), [ ->post(route('admin.backups.restore', $filename), [
@@ -164,9 +187,23 @@ class BackupAndRestoreTest extends TestCase
]); ]);
} }
public function test_super_admin_can_delete_backup_file(): void public function test_restore_rejects_tampered_or_unauthorized_external_file(): void
{ {
$filename = $this->backupService->createDatabaseBackup('test_to_delete.sql'); $fakeKmh = DatabaseBackupService::KMH_MAGIC_HEADER . random_bytes(16) . random_bytes(32) . 'corrupted_ciphertext';
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_corrupt.kmh';
file_put_contents($fullPath, $fakeKmh);
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', 'test_corrupt.kmh'), [
'confirmation' => 'PULIHKAN',
]);
$response->assertSessionHas('error');
}
public function test_super_admin_can_delete_kmh_backup_file(): void
{
$filename = $this->backupService->createKmhBackup(['users'], false, 'test_to_delete.kmh');
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename; $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$this->assertTrue(File::exists($fullPath)); $this->assertTrue(File::exists($fullPath));
@@ -175,50 +212,19 @@ class BackupAndRestoreTest extends TestCase
$response->assertSessionHas('success'); $response->assertSessionHas('success');
$this->assertFalse(File::exists($fullPath)); $this->assertFalse(File::exists($fullPath));
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'delete',
'module' => 'Backup & Restore',
'target_name' => $filename,
]);
} }
public function test_super_admin_can_create_full_backup(): void public function test_cli_artisan_backup_create_command_creates_kmh(): void
{
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.store'), [
'type' => 'full',
]);
$response->assertSessionHas('success');
$response->assertRedirect();
$backups = $this->backupService->listBackups();
$this->assertNotEmpty($backups);
$this->assertEquals('full', $backups[0]['type']);
$this->assertStringEndsWith('.zip', $backups[0]['filename']);
}
public function test_super_admin_can_restore_from_backup_with_password(): void
{
$filename = $this->backupService->createDatabaseBackup('test_pwd_restore.sql');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', $filename), [
'password' => 'password123',
]);
$response->assertSessionHas('success');
}
public function test_cli_artisan_backup_create_command(): void
{ {
$this->artisan('backup:create', [ $this->artisan('backup:create', [
'--type' => 'database', '--scope' => 'semua',
'--filename' => 'test_cli_db.sql', '--filename' => 'test_cli_backup.kmh',
])->assertSuccessful(); ])->assertSuccessful();
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_cli_db.sql'; $fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_cli_backup.kmh';
$this->assertTrue(File::exists($fullPath)); $this->assertTrue(File::exists($fullPath));
$content = file_get_contents($fullPath);
$this->assertStringStartsWith(DatabaseBackupService::KMH_MAGIC_HEADER, $content);
} }
} }