feat(admin): implement complete backup and restore system for database and media files

This commit is contained in:
Ray1111-aa
2026-10-28 09:09:04 +07:00
parent 49359d1ba1
commit 238ec128d2
8 changed files with 1785 additions and 0 deletions
@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Services\DatabaseBackupService;
use Illuminate\Console\Command;
class CreateBackupCommand extends Command
{
/**
* Nama dan signature perintah CLI.
*/
protected $signature = 'backup:create
{--type=database : Jenis backup: database atau full}
{--filename= : Nama kustom untuk file backup}';
/**
* Deskripsi perintah.
*/
protected $description = 'Buat backup database MySQL atau Full Backup (+ media upload) sistem RKM-KMH';
public function handle(DatabaseBackupService $service): int
{
$type = strtolower($this->option('type') ?: 'database');
$customName = $this->option('filename');
if (!in_array($type, ['database', 'full'])) {
$this->error("Pilihan --type tidak valid. Gunakan 'database' atau 'full'.");
return Command::FAILURE;
}
$this->info("Memulai pembuatan backup sistem RKM-KMH [Tipe: " . strtoupper($type) . "]...");
try {
$startTime = microtime(true);
if ($type === 'full') {
$filename = $service->createFullBackup($customName);
} else {
$filename = $service->createDatabaseBackup($customName);
}
$duration = round(microtime(true) - $startTime, 2);
$fullPath = $service->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$sizeHuman = FileSizeHelper::format(file_exists($fullPath) ? filesize($fullPath) : 0);
$this->newLine();
$this->info("✓ Backup berhasil dibuat!");
$this->line(" File : <comment>{$filename}</comment>");
$this->line(" Lokasi : {$fullPath}");
$this->line(" Ukuran : {$sizeHuman}");
$this->line(" Waktu : {$duration} detik");
return Command::SUCCESS;
} catch (\Throwable $e) {
$this->error("Gagal membuat backup: " . $e->getMessage());
return Command::FAILURE;
}
}
}
class FileSizeHelper
{
public static function format(int $bytes): string
{
if ($bytes <= 0) return '0 B';
$units = ['B', 'KB', 'MB', 'GB'];
$power = min((int) floor(log($bytes, 1024)), count($units) - 1);
return round($bytes / pow(1024, $power), 2) . ' ' . $units[$power];
}
}
@@ -0,0 +1,218 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Services\DatabaseBackupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;
use Spatie\Permission\PermissionRegistrar;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class BackupController extends Controller
{
public function __construct(
protected DatabaseBackupService $backupService
) {}
/**
* Tampilkan halaman manajemen backup & restore sistem.
*/
public function index(): View
{
$backups = $this->backupService->listBackups();
$stats = $this->backupService->getSystemStats();
return view('admin.backups.index', compact('backups', 'stats'));
}
/**
* Buat file backup baru (Database Saja atau Full Backup + Media).
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'type' => ['required', 'in:database,full'],
], [
'type.required' => 'Pilih jenis backup yang ingin dibuat.',
'type.in' => 'Jenis backup harus bernilai database atau full.',
]);
$type = $validated['type'];
try {
if ($type === 'full') {
$filename = $this->backupService->createFullBackup();
$typeLabel = 'Full Backup (+ Media)';
} else {
$filename = $this->backupService->createDatabaseBackup();
$typeLabel = 'Database SQL';
}
// Catat ke Log Aktivitas Super Admin
AdminActivityLog::record(
actionType: 'create',
module: 'Backup & Restore',
description: "Membuat {$typeLabel} baru dengan nama file: {$filename}.",
targetType: 'BackupFile',
targetName: $filename,
newValues: [
'filename' => $filename,
'type' => $type,
'created_at' => now()->toIso8601String(),
]
);
return back()->with('success', "{$typeLabel} ({$filename}) berhasil dibuat dan disimpan di server.");
} catch (\Throwable $e) {
return back()->with('error', 'Gagal membuat backup: ' . $e->getMessage());
}
}
/**
* Unduh file backup ke penyimpanan lokal administrator.
*/
public function download(string $filename): BinaryFileResponse|RedirectResponse
{
$filename = basename($filename);
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
if (!File::exists($fullPath)) {
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server.");
}
AdminActivityLog::record(
actionType: 'export',
module: 'Backup & Restore',
description: "Mengunduh file backup: {$filename}.",
targetType: 'BackupFile',
targetName: $filename
);
return response()->download($fullPath, $filename, [
'Cache-Control' => 'no-cache, no-store, must-revalidate',
'Pragma' => 'no-cache',
'Expires' => '0',
]);
}
/**
* Unggah file backup (.sql, .zip, .gz) dari komputer lokal ke server.
*/
public function upload(Request $request): RedirectResponse
{
$request->validate([
'backup_file' => ['required', 'file', 'max:204800'], // Maks. 200 MB
], [
'backup_file.required' => 'Pilih file backup yang ingin diunggah.',
'backup_file.file' => 'File yang diunggah tidak valid.',
'backup_file.max' => 'Ukuran file backup maksimal 200 MB.',
]);
$file = $request->file('backup_file');
$originalName = basename($file->getClientOriginalName());
$ext = strtolower($file->getClientOriginalExtension());
if (!in_array($ext, ['sql', 'zip', 'gz'])) {
return back()->with('error', 'Format file tidak didukung. File backup harus berekstensi .sql, .zip, atau .gz.');
}
// Cegah nama ganda dengan menambahkan timestamp jika file sudah ada
$targetDir = $this->backupService->getBackupDirectory();
$targetFilename = $originalName;
if (File::exists($targetDir . DIRECTORY_SEPARATOR . $targetFilename)) {
$nameOnly = pathinfo($originalName, PATHINFO_FILENAME);
$targetFilename = $nameOnly . '_' . now()->format('Ymd_His') . '.' . $ext;
}
try {
$file->move($targetDir, $targetFilename);
AdminActivityLog::record(
actionType: 'create',
module: 'Backup & Restore',
description: "Mengunggah file backup eksternal: {$targetFilename}.",
targetType: 'BackupFile',
targetName: $targetFilename
);
return back()->with('success', "File backup '{$targetFilename}' berhasil diunggah dan siap dipulihkan jika diperlukan.");
} catch (\Throwable $e) {
return back()->with('error', 'Gagal menyimpan file backup yang diunggah: ' . $e->getMessage());
}
}
/**
* Pulihkan (Restore) database & aset sistem dari file backup.
*/
public function restore(Request $request, string $filename): RedirectResponse
{
$filename = basename($filename);
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
if (!File::exists($fullPath)) {
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server.");
}
// Verifikasi Keamanan: Harap 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.');
}
try {
// Jalankan proses restore
$this->backupService->restore($fullPath);
// 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) database dan aset sistem dari file backup: {$filename}.",
targetType: 'BackupFile',
targetName: $filename
);
return back()->with('success', "Sistem berhasil dipulihkan dari file backup '{$filename}'. Seluruh data dan tabel telah disinkronkan kembali.");
} catch (\Throwable $e) {
return back()->with('error', 'Terjadi kesalahan saat memulihkan sistem: ' . $e->getMessage());
}
}
/**
* Hapus file backup dari penyimpanan server.
*/
public function destroy(string $filename): RedirectResponse
{
$filename = basename($filename);
if ($this->backupService->deleteBackup($filename)) {
AdminActivityLog::record(
actionType: 'delete',
module: 'Backup & Restore',
description: "Menghapus file backup: {$filename}.",
targetType: 'BackupFile',
targetName: $filename
);
return back()->with('success', "File backup '{$filename}' berhasil dihapus dari server.");
}
return back()->with('error', "File backup '{$filename}' tidak ditemukan atau gagal dihapus.");
}
}
+643
View File
@@ -0,0 +1,643 @@
<?php
namespace App\Services;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use PDO;
use RuntimeException;
use ZipArchive;
class DatabaseBackupService
{
protected string $backupDir;
public function __construct()
{
$this->backupDir = storage_path('app/backups');
if (!File::isDirectory($this->backupDir)) {
File::makeDirectory($this->backupDir, 0755, true);
}
}
/**
* Dapatkan path direktori penyimpanan backup.
*/
public function getBackupDirectory(): string
{
return $this->backupDir;
}
/**
* Dapatkan daftar seluruh file backup yang tersedia, diurutkan dari yang terbaru.
*
* @return array<int, array{
* filename: string,
* path: string,
* type: string,
* type_label: string,
* size_raw: int,
* size_human: string,
* created_at: Carbon,
* created_at_human: string
* }>
*/
public function listBackups(): array
{
$files = File::files($this->backupDir);
$backups = [];
foreach ($files as $file) {
$extension = strtolower($file->getExtension());
if (!in_array($extension, ['sql', 'zip', 'gz'])) {
continue;
}
$filename = $file->getFilename();
$size = $file->getSize();
$createdAt = Carbon::createFromTimestamp($file->getMTime());
$isFull = str_ends_with($filename, '.zip') || str_contains($filename, '_full_');
$type = $isFull ? 'full' : 'database';
$typeLabel = $isFull ? 'Full Backup (+ File Media)' : 'Database SQL';
$backups[] = [
'filename' => $filename,
'path' => $file->getPathname(),
'type' => $type,
'type_label' => $typeLabel,
'size_raw' => $size,
'size_human' => $this->formatBytes($size),
'created_at' => $createdAt,
'created_at_human' => $createdAt->translatedFormat('d M Y, H:i') . ' WIB',
];
}
usort($backups, fn ($a, $b) => $b['created_at']->timestamp <=> $a['created_at']->timestamp);
return $backups;
}
/**
* Buat backup database (MySQL / SQLite) ke dalam file .sql murni.
* Menggunakan PDO stream generator mandiri tanpa ketergantungan mysqldump eksternal.
*/
public function createDatabaseBackup(?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);
@ini_set('memory_limit', '512M');
if (!class_exists('ZipArchive')) {
throw new RuntimeException('Ekstensi PHP ZipArchive tidak tersedia di server ini.');
}
$database = config('database.connections.' . config('database.default') . '.database', 'database');
$cleanDbName = str_replace([':', '/', '\\'], '_', (string) $database);
$timestamp = now()->format('Ymd_His');
$zipFilename = $customFilename ?: "backup_full_{$cleanDbName}_{$timestamp}.zip";
$zipFilename = basename($zipFilename);
if (!str_ends_with($zipFilename, '.zip')) {
$zipFilename .= '.zip';
}
$zipFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $zipFilename;
// 1. Buat temporary SQL dump terlebih dahulu
$tempSqlName = "temp_db_{$timestamp}.sql";
$this->createDatabaseBackup($tempSqlName);
$tempSqlFullPath = $this->backupDir . DIRECTORY_SEPARATOR . $tempSqlName;
$zip = new ZipArchive();
if ($zip->open($zipFullPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
throw new RuntimeException("Gagal membuat file ZIP di: {$zipFullPath}");
}
try {
// Masukkan database SQL ke dalam root arsip ZIP
$zip->addFile($tempSqlFullPath, 'database.sql');
// Masukkan seluruh file media yang ada di storage/app/public (misal foto profil, foto kendaraan, simper)
$publicStorageDir = storage_path('app/public');
if (File::isDirectory($publicStorageDir)) {
$files = File::allFiles($publicStorageDir);
foreach ($files as $file) {
$relativePath = 'storage/' . $file->getRelativePathname();
$zip->addFile($file->getRealPath(), str_replace('\\', '/', $relativePath));
}
}
// Tambahkan metadata ringkas manifest.json
$manifest = [
'system' => 'RKM-KMH (PT Kerinci Merangin Hidro)',
'created_at' => now()->toIso8601String(),
'type' => 'full',
'database' => $database,
'laravel_version' => app()->version(),
'php_version' => PHP_VERSION,
];
$zip->addFromString('manifest.json', json_encode($manifest, JSON_PRETTY_PRINT));
$zip->close();
// Hapus file temporary SQL
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
return $zipFilename;
} catch (\Throwable $e) {
$zip->close();
if (File::exists($tempSqlFullPath)) {
File::delete($tempSqlFullPath);
}
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).
*/
public function restore(string $backupFilenameOrPath): void
{
@set_time_limit(600);
@ini_set('memory_limit', '512M');
$filePath = File::exists($backupFilenameOrPath)
? $backupFilenameOrPath
: $this->backupDir . DIRECTORY_SEPARATOR . basename($backupFilenameOrPath);
if (!File::exists($filePath)) {
throw new RuntimeException("File backup tidak ditemukan: {$filePath}");
}
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if ($extension === 'zip') {
$this->restoreFromZip($filePath);
} elseif ($extension === 'sql') {
$this->restoreFromSql($filePath);
} elseif ($extension === 'gz') {
$this->restoreFromGzip($filePath);
} else {
throw new RuntimeException("Format file tidak didukung untuk pemulihan: .{$extension}");
}
}
/**
* Pulihkan dari file SQL langsung.
*/
public function restoreFromSql(string $sqlFilePath): void
{
$pdo = DB::connection()->getPdo();
$driver = DB::connection()->getDriverName();
// Nonaktifkan pemeriksaan foreign key untuk mencegah deadlock/relasi urutan
if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = OFF;");
} else {
$pdo->exec("SET FOREIGN_KEY_CHECKS = 0;");
$pdo->exec("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';");
}
$handle = fopen($sqlFilePath, 'r');
if (!$handle) {
if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = ON;");
} else {
$pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
}
throw new RuntimeException("Gagal membaca file SQL: {$sqlFilePath}");
}
$currentQuery = '';
$inQuotes = false;
$quoteChar = '';
$escaped = false;
try {
while (($line = fgets($handle)) !== false) {
$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, '#'))) {
// Cek jika komentar multi baris
if (str_starts_with($trimmed, '/*') && !str_ends_with($trimmed, '*/')) {
while (($line = fgets($handle)) !== false) {
if (str_contains($line, '*/')) break;
}
}
continue;
}
$len = strlen($line);
for ($i = 0; $i < $len; $i++) {
$char = $line[$i];
if ($escaped) {
$currentQuery .= $char;
$escaped = false;
continue;
}
if ($char === '\\') {
$escaped = true;
$currentQuery .= $char;
continue;
}
if ($inQuotes) {
if ($char === $quoteChar) {
$inQuotes = false;
}
$currentQuery .= $char;
} else {
if ($char === "'" || $char === '"' || $char === '`') {
$inQuotes = true;
$quoteChar = $char;
$currentQuery .= $char;
} elseif ($char === ';') {
// Akhir dari sebuah statement SQL
$statement = trim($currentQuery);
if ($statement !== '') {
$pdo->exec($statement);
}
$currentQuery = '';
} else {
$currentQuery .= $char;
}
}
}
}
// Jalankan statement terakhir jika ada yang tersisa tanpa titik koma
$finalStatement = trim($currentQuery);
if ($finalStatement !== '') {
$pdo->exec($finalStatement);
}
fclose($handle);
if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = ON;");
} else {
$pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
}
} catch (\Throwable $e) {
if (is_resource($handle)) {
fclose($handle);
}
if ($driver === 'sqlite') {
$pdo->exec("PRAGMA foreign_keys = ON;");
} else {
$pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
}
throw new RuntimeException("Gagal mengeksekusi restore SQL: " . $e->getMessage(), 0, $e);
}
}
/**
* 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.
*/
public function deleteBackup(string $filename): bool
{
$filename = basename($filename);
$fullPath = $this->backupDir . DIRECTORY_SEPARATOR . $filename;
if (File::exists($fullPath)) {
return File::delete($fullPath);
}
return false;
}
/**
* 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
{
$backups = $this->listBackups();
$totalSize = array_sum(array_column($backups, 'size_raw'));
$driver = DB::connection()->getDriverName();
$tableNames = $this->getAllTableNames();
$tableCount = count($tableNames);
$dbSizeBytes = 0;
$databaseName = config('database.connections.' . config('database.default') . '.database', 'database');
if ($driver === 'mysql') {
$sizeResult = DB::selectOne("
SELECT SUM(data_length + index_length) AS size
FROM information_schema.TABLES
WHERE table_schema = ?
", [$databaseName]);
$dbSizeBytes = (int) ($sizeResult->size ?? 0);
}
return [
'total_backups' => count($backups),
'total_size_raw' => $totalSize,
'total_size_human' => $this->formatBytes($totalSize),
'database_name' => (string) $databaseName,
'table_count' => $tableCount,
'estimated_db_size_human' => $this->formatBytes($dbSizeBytes),
'last_backup' => $backups[0] ?? null,
];
}
/**
* Dapatkan daftar seluruh nama tabel aktif di database.
*
* @return array<int, string>
*/
public function getAllTableNames(): array
{
$driver = DB::connection()->getDriverName();
if ($driver === 'sqlite') {
$rows = DB::select("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
return array_values(array_map(fn ($r) => $r->name, $rows));
}
// MySQL
$database = config('database.connections.' . config('database.default') . '.database');
$tables = DB::select("SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'");
$tableKey = "Tables_in_{$database}";
$names = [];
foreach ($tables as $tRow) {
$names[] = $tRow->$tableKey ?? current((array) $tRow);
}
return $names;
}
/**
* Dump struktur dan data satu tabel database.
*/
protected function dumpTableStructureAndData($handle, PDO $pdo, string $tableName, string $driver): void
{
fwrite($handle, "\n-- -------------------------------------------------------------\n");
fwrite($handle, "-- Struktur Tabel untuk `{$tableName}`\n");
fwrite($handle, "-- -------------------------------------------------------------\n");
fwrite($handle, "DROP TABLE IF EXISTS `{$tableName}`;\n");
if ($driver === 'sqlite') {
$createResult = DB::selectOne("SELECT sql FROM sqlite_master WHERE type='table' AND name = ?", [$tableName]);
$createTableSql = $createResult->sql ?? '';
} else {
$createResult = DB::selectOne("SHOW CREATE TABLE `{$tableName}`");
$createSqlKey = 'Create Table';
$createTableSql = $createResult->$createSqlKey ?? current((array) $createResult);
}
if ($createTableSql) {
fwrite($handle, $createTableSql . ";\n\n");
}
// Dump Data Baris (chunk 200 baris untuk efisiensi RAM)
fwrite($handle, "-- Dumping Data untuk `{$tableName}`\n");
$query = DB::table($tableName);
$totalRows = $query->count();
if ($totalRows === 0) {
fwrite($handle, "-- (Tabel kosong)\n\n");
return;
}
$query->orderBy(DB::raw('1'))->chunk(200, function ($rows) use ($handle, $pdo, $tableName) {
if ($rows->isEmpty()) return;
$columns = array_keys((array) $rows->first());
$escapedColumns = array_map(fn ($c) => "`{$c}`", $columns);
$columnsStr = implode(', ', $escapedColumns);
fwrite($handle, "INSERT INTO `{$tableName}` ({$columnsStr}) VALUES\n");
$rowCount = count($rows);
$i = 0;
foreach ($rows as $row) {
$i++;
$values = [];
foreach ((array) $row as $val) {
if (is_null($val)) {
$values[] = 'NULL';
} elseif (is_int($val) || is_float($val)) {
$values[] = (string) $val;
} elseif (is_bool($val)) {
$values[] = $val ? '1' : '0';
} else {
$values[] = $pdo->quote((string) $val);
}
}
$line = ' (' . implode(', ', $values) . ')';
$line .= ($i === $rowCount) ? ";\n" : ",\n";
fwrite($handle, $line);
}
});
fwrite($handle, "\n");
}
/**
* Format byte ke satuan yang mudah dibaca (KB, MB, GB).
*/
protected function formatBytes(int $bytes, int $precision = 2): string
{
if ($bytes <= 0) return '0 B';
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$power = min((int) floor(log($bytes, 1024)), count($units) - 1);
$size = $bytes / pow(1024, $power);
return round($size, $precision) . ' ' . $units[$power];
}
}
+26
View File
@@ -54,6 +54,32 @@ return [
], ],
], ],
], ],
'backups' => [
'name' => 'Backup & Restore Sistem',
'icon' => 'fa-solid fa-database',
'permissions' => [
'backups.view' => [
'label' => 'Melihat Daftar Backup Sistem',
'description' => 'Melihat daftar riwayat backup database dan file media di server.',
],
'backups.create' => [
'label' => 'Membuat File Backup Baru',
'description' => 'Mencadangkan database SQL dan file media sistem secara manual.',
],
'backups.download' => [
'label' => 'Mengunduh File Backup',
'description' => 'Mengunduh file arsip backup (.sql / .zip) ke komputer lokal.',
],
'backups.restore' => [
'label' => 'Memulihkan (Restore) Sistem',
'description' => 'Melakukan pemulihan bencana (disaster recovery) database dan file media.',
],
'backups.delete' => [
'label' => 'Menghapus File Backup',
'description' => 'Menghapus arsip backup lama dari media penyimpanan server.',
],
],
],
'hse' => [ 'hse' => [
'name' => 'Modul K3 / HSE (Karyawan & SIMPER)', 'name' => 'Modul K3 / HSE (Karyawan & SIMPER)',
'icon' => 'fa-solid fa-id-card', 'icon' => 'fa-solid fa-id-card',
@@ -0,0 +1,580 @@
@extends('layouts.app')
@section('title', 'Backup & Restore Sistem - Super Admin RKM')
@section('content')
<div class="space-y-6">
<!-- Header Halaman -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-2.5">
<span class="w-2.5 h-7 rounded-full bg-indigo-600 inline-block"></span>
<span>Backup & Restore Sistem</span>
</h1>
<p class="text-xs text-slate-500 mt-1">
Pencadangan database MySQL dan file media sistem secara berkala untuk perlindungan data dan pemulihan bencana (<em>disaster recovery</em>).
</p>
</div>
<div class="flex items-center gap-2.5 flex-wrap">
<button type="button"
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">
<i class="fa-solid fa-cloud-arrow-up text-indigo-600"></i>
<span>Unggah File Backup</span>
</button>
<button type="button"
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">
<i class="fa-solid fa-database text-xs"></i>
<span>Buat Backup Baru</span>
</button>
</div>
</div>
<!-- Alert Notifikasi Flash -->
@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="flex items-center gap-2.5">
<i class="fa-solid fa-circle-check text-emerald-600 text-base flex-shrink-0"></i>
<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>
@endif
@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="flex items-center gap-2.5">
<i class="fa-solid fa-triangle-exclamation text-rose-600 text-base flex-shrink-0"></i>
<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>
@endif
<!-- Kartu Metrik Ringkasan Backup & Database -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
<!-- Total File Backup -->
<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">Total File Backup</span>
<span class="w-8 h-8 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-xs">
<i class="fa-solid fa-server"></i>
</span>
</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-[10px] text-slate-400 font-medium block mt-1">Arsip tersimpan di server</span>
</div>
<!-- Total Ukuran Storage -->
<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">Ukuran Arsip</span>
<span class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center text-xs">
<i class="fa-solid fa-hard-drive"></i>
</span>
</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>
<!-- Backup Terakhir -->
<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">Backup Terakhir</span>
<span class="w-8 h-8 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center text-xs">
<i class="fa-solid fa-clock-rotate-left"></i>
</span>
</div>
<span class="text-sm sm:text-base font-bold text-slate-900 mt-2 block truncate" title="{{ $stats['last_backup']['created_at_human'] ?? '-' }}">
{{ $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>
<!-- 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>
<!-- Tabel Daftar File Backup -->
<div class="bg-white border border-slate-200/80 rounded-2xl shadow-sm overflow-hidden">
<div class="p-4 sm:px-6 border-b border-slate-100 flex items-center justify-between gap-4 flex-wrap">
<div>
<h3 class="text-sm font-bold text-slate-900 flex items-center gap-2">
<i class="fa-solid fa-folder-open text-indigo-600"></i>
<span>Daftar Arsip Backup Tersimpan</span>
</h3>
<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>
</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 class="overflow-x-auto">
<table class="w-full text-left text-xs">
<thead>
<tr class="bg-slate-50/80 border-b border-slate-100 text-slate-500 font-bold uppercase tracking-wider text-[11px]">
<th class="py-3 px-4 sm:px-6">Nama File Backup</th>
<th class="py-3 px-4">Jenis Backup</th>
<th class="py-3 px-4">Ukuran File</th>
<th class="py-3 px-4">Tanggal Dibuat</th>
<th class="py-3 px-4 sm:px-6 text-center">Aksi & Pemulihan</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 font-medium">
@forelse($backups as $b)
@php
$isFull = ($b['type'] === 'full');
@endphp
<tr class="hover:bg-slate-50/70 transition">
<!-- Nama File -->
<td class="py-3.5 px-4 sm:px-6">
<div class="flex items-center gap-3">
<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' }}">
@if($isFull)
<i class="fa-solid fa-file-zipper"></i>
@else
<i class="fa-solid fa-file-code"></i>
@endif
</div>
<div class="min-w-0">
<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>
</td>
<!-- Jenis Backup -->
<td class="py-3.5 px-4 whitespace-nowrap">
@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">
<i class="fa-solid fa-box-archive text-[9px]"></i>
<span>Full Backup + Media</span>
</span>
@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">
<i class="fa-solid fa-database text-[9px]"></i>
<span>Database SQL</span>
</span>
@endif
</td>
<!-- Ukuran File -->
<td class="py-3.5 px-4 whitespace-nowrap font-mono text-slate-700 font-semibold text-xs">
{{ $b['size_human'] }}
</td>
<!-- Tanggal Dibuat -->
<td class="py-3.5 px-4 whitespace-nowrap">
<span class="text-slate-800 font-semibold block text-xs">{{ $b['created_at_human'] }}</span>
<span class="text-[10px] text-slate-400">{{ $b['created_at']->diffForHumans() }}</span>
</td>
<!-- Aksi -->
<td class="py-3.5 px-4 sm:px-6 text-center whitespace-nowrap">
<div class="inline-flex items-center gap-2">
<!-- Unduh -->
<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"
title="Unduh file backup ke komputer lokal">
<i class="fa-solid fa-download text-[11px]"></i>
<span class="hidden sm:inline">Unduh</span>
</a>
<!-- Pulihkan / Restore -->
<button type="button"
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"
title="Pulihkan database & data sistem dari backup ini">
<i class="fa-solid fa-rotate-left text-[11px]"></i>
<span>Pulihkan</span>
</button>
<!-- Hapus -->
<button type="button"
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"
title="Hapus file backup ini dari server">
<i class="fa-solid fa-trash-can text-xs"></i>
</button>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="5" class="py-12 px-4 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">
<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"
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">
<i class="fa-solid fa-circle-plus"></i>
<span>Buat Backup Baru</span>
</button>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
<!-- ========================================================================= -->
<!-- MODAL: BUAT BACKUP BARU -->
<!-- ========================================================================= -->
<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 class="bg-white rounded-3xl max-w-md w-full shadow-2xl 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">
<h3 class="text-base font-bold text-slate-800 flex items-center gap-2">
<i class="fa-solid fa-database text-indigo-600"></i>
<span>Buat Backup Baru</span>
</h3>
<button type="button" onclick="closeCreateBackupModal()" class="text-slate-400 hover:text-slate-600 p-1">
<i class="fa-solid fa-xmark text-lg"></i>
</button>
</div>
<form id="createBackupForm" method="POST" action="{{ route('admin.backups.store') }}" onsubmit="handleBackupSubmit(this)" class="p-6 space-y-4">
@csrf
<p class="text-xs text-slate-500 leading-relaxed">
Pilih cakupan data yang ingin dicadangkan. Proses ini akan berjalan di latar belakang dan menyimpan file hasil cadangan di server.
</p>
<!-- Pilihan Jenis Backup -->
<div class="space-y-3">
<!-- Opsi 1: Database Saja -->
<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">
<div class="flex items-start gap-3">
<input type="radio" name="type" value="database" checked class="mt-0.5 text-indigo-600 focus:ring-indigo-500">
<div class="flex-1">
<span class="block text-xs font-bold text-slate-900">Database Saja (.sql)</span>
<span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed">
Mencadangkan seluruh 29 tabel aktif MySQL dan data operasional. Proses sangat cepat dan ukuran file ringan (~500 KB).
</span>
<span class="inline-block mt-2 px-2 py-0.5 rounded-md bg-emerald-100 text-emerald-800 font-bold text-[10px]">
Direkomendasikan Rutin
</span>
</div>
</div>
</label>
<!-- Opsi 2: Full Backup -->
<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="flex items-start gap-3">
<input type="radio" name="type" value="full" class="mt-0.5 text-indigo-600 focus:ring-indigo-500">
<div class="flex-1">
<span class="block text-xs font-bold text-slate-900">Full Backup Lengkap (.zip)</span>
<span class="block text-[11px] text-slate-500 mt-0.5 leading-relaxed">
Mencadangkan Database SQL + seluruh berkas media upload di <code>storage/app/public</code> (foto karyawan, foto kendaraan, SIMPER).
</span>
<span class="inline-block mt-2 px-2 py-0.5 rounded-md bg-slate-100 text-slate-600 font-bold text-[10px]">
Menyeluruh & Total
</span>
</div>
</div>
</label>
</div>
<!-- Tombol Footer -->
<div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-2.5">
<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">
Batal
</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">
<i class="fa-solid fa-play text-[10px]"></i>
<span id="createBackupBtnText">Mulai Pencadangan</span>
</button>
</div>
</form>
</div>
</div>
<!-- ========================================================================= -->
<!-- MODAL: UNGGAH FILE BACKUP -->
<!-- ========================================================================= -->
<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 class="bg-white rounded-3xl max-w-md w-full shadow-2xl 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">
<h3 class="text-base font-bold text-slate-800 flex items-center gap-2">
<i class="fa-solid fa-cloud-arrow-up text-indigo-600"></i>
<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>
<form id="uploadBackupForm" method="POST" action="{{ route('admin.backups.upload') }}" enctype="multipart/form-data" class="p-6 space-y-4">
@csrf
<!-- Upload Drop Area -->
<div>
<label class="block text-xs font-bold text-slate-700 mb-2">Pilih File Arsip Backup <span class="text-rose-500">*</span></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"
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 backup</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"
name="backup_file"
id="backupFileInput"
accept=".sql,.zip,.gz"
required
class="hidden"
onchange="handleUploadFileChange(this)">
</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 class="pt-4 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">
Batal
</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">
<i class="fa-solid fa-upload text-xs"></i>
<span>Unggah ke Server</span>
</button>
</div>
</form>
</div>
</div>
<!-- ========================================================================= -->
<!-- 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 class="bg-white rounded-3xl max-w-lg w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100">
<!-- Header Bahaya -->
<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 flex items-center gap-2">
<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>
<form id="restoreForm" method="POST" action="" onsubmit="handleRestoreSubmit(this)" class="p-6 space-y-4">
@csrf
<!-- Warning Card -->
<div class="p-4 rounded-2xl bg-rose-50 border border-rose-200 text-xs text-rose-900 space-y-1.5">
<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>
<!-- Rincian Target File Backup -->
<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">
<span class="text-slate-400 text-[11px]">Nama Arsip:</span>
<span id="restoreTargetFilename" class="font-bold font-mono 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>
<!-- Input Verifikasi Keamanan -->
<div>
<label class="block text-xs font-bold text-slate-800 mb-1">
Konfirmasi Keamanan <span class="text-rose-500">*</span>
</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"
name="confirmation"
id="restoreConfirmationInput"
placeholder="Ketik PULIHKAN atau password akun Anda..."
required
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">
</div>
<!-- Tombol Footer -->
<div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-2.5">
<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
</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">
<i class="fa-solid fa-rotate-left text-xs"></i>
<span id="restoreBtnText">Ya, Pulihkan Sistem Sekarang</span>
</button>
</div>
</form>
</div>
</div>
<!-- ========================================================================= -->
<!-- MODAL: KONFIRMASI HAPUS BACKUP -->
<!-- ========================================================================= -->
<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 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="w-12 h-12 rounded-2xl bg-rose-50 text-rose-600 flex items-center justify-center text-xl mx-auto mb-3">
<i class="fa-solid fa-trash-can"></i>
</div>
<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>
<form id="deleteBackupForm" method="POST" action="" class="mt-6 flex items-center justify-center gap-2.5">
@csrf
@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">
Batal
</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">
Hapus File
</button>
</form>
</div>
</div>
<!-- ========================================================================= -->
<!-- JAVASCRIPT HELPER MODAL & INTERAKSI -->
<!-- ========================================================================= -->
<script>
function openCreateBackupModal() {
document.getElementById('createBackupModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
}
function closeCreateBackupModal() {
document.getElementById('createBackupModal').classList.add('hidden');
document.documentElement.classList.remove('modal-open');
}
function handleBackupSubmit(form) {
const btn = document.getElementById('createBackupSubmitBtn');
const text = document.getElementById('createBackupBtnText');
if (btn) {
btn.disabled = true;
btn.classList.add('opacity-75', 'cursor-not-allowed');
}
if (text) {
text.textContent = 'Memproses Pencadangan...';
}
}
function openUploadBackupModal() {
document.getElementById('uploadBackupModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
}
function closeUploadBackupModal() {
document.getElementById('uploadBackupModal').classList.add('hidden');
document.documentElement.classList.remove('modal-open');
}
function handleUploadFileChange(input) {
const nameDisplay = document.getElementById('uploadFileName');
if (input.files && input.files[0]) {
nameDisplay.textContent = input.files[0].name + ' (' + (input.files[0].size / 1024 / 1024).toFixed(2) + ' MB)';
}
}
function openRestoreModal(filename, typeLabel, sizeHuman) {
document.getElementById('restoreForm').action = `/admin/backups/${encodeURIComponent(filename)}/restore`;
document.getElementById('restoreTargetFilename').textContent = filename;
document.getElementById('restoreTargetMeta').textContent = `${typeLabel} (${sizeHuman})`;
document.getElementById('restoreConfirmationInput').value = '';
document.getElementById('restoreModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
}
function closeRestoreModal() {
document.getElementById('restoreModal').classList.add('hidden');
document.documentElement.classList.remove('modal-open');
}
function handleRestoreSubmit(form) {
const btn = document.getElementById('restoreSubmitBtn');
const text = document.getElementById('restoreBtnText');
if (btn) {
btn.disabled = true;
btn.classList.add('opacity-75', 'cursor-not-allowed');
}
if (text) {
text.textContent = 'Memulihkan Sistem (Mohon Tunggu)...';
}
}
function openDeleteBackupModal(filename) {
document.getElementById('deleteBackupForm').action = `/admin/backups/${encodeURIComponent(filename)}`;
document.getElementById('deleteBackupFilename').textContent = filename;
document.getElementById('deleteBackupModal').classList.remove('hidden');
document.documentElement.classList.add('modal-open');
}
function closeDeleteBackupModal() {
document.getElementById('deleteBackupModal').classList.add('hidden');
document.documentElement.classList.remove('modal-open');
}
</script>
@endsection
+14
View File
@@ -248,6 +248,12 @@
<i class="fa-solid fa-clock-rotate-left text-base w-5 text-center"></i> <i class="fa-solid fa-clock-rotate-left text-base w-5 text-center"></i>
<span>Log Aktivitas Admin</span> <span>Log Aktivitas Admin</span>
</a> </a>
<a href="{{ route('admin.backups.index') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.backups.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-database text-base w-5 text-center"></i>
<span>Backup & Restore</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
@@ -630,6 +636,10 @@
<i class="fa-solid fa-clock-rotate-left w-5 text-center"></i> <i class="fa-solid fa-clock-rotate-left w-5 text-center"></i>
<span>Log Aktivitas Admin</span> <span>Log Aktivitas Admin</span>
</a> </a>
<a href="{{ route('admin.backups.index') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.backups.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-database w-5 text-center"></i>
<span>Backup & Restore</span>
</a>
</nav> </nav>
</div> </div>
@endif @endif
@@ -915,6 +925,10 @@
Kelola Pengguna Kelola Pengguna
@elseif(request()->routeIs('admin.roles.*')) @elseif(request()->routeIs('admin.roles.*'))
Role & Permission Role & Permission
@elseif(request()->routeIs('admin.backups.*'))
Backup & Restore
@elseif(request()->routeIs('admin.activity_logs.*'))
Log Aktivitas Admin
@elseif(request()->routeIs('hse.dashboard') || request()->routeIs('qma.dashboard')) @elseif(request()->routeIs('hse.dashboard') || request()->routeIs('qma.dashboard'))
Dashboard Dashboard
@elseif(request()->routeIs('hse.employees.*')) @elseif(request()->routeIs('hse.employees.*'))
+9
View File
@@ -1,6 +1,7 @@
<?php <?php
use App\Http\Controllers\Admin\AdminActivityLogController; use App\Http\Controllers\Admin\AdminActivityLogController;
use App\Http\Controllers\Admin\BackupController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController; use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\RolePermissionController; use App\Http\Controllers\Admin\RolePermissionController;
use App\Http\Controllers\Admin\UserController; use App\Http\Controllers\Admin\UserController;
@@ -215,5 +216,13 @@ Route::middleware('auth')->group(function () {
// Log Riwayat Aktivitas Super Admin // Log Riwayat Aktivitas Super Admin
Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index'); Route::get('/activity-logs', [AdminActivityLogController::class, 'index'])->name('activity_logs.index');
// Backup & Restore Sistem (Database & Media)
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download');
Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload');
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore');
Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy');
}); });
}); });
+224
View File
@@ -0,0 +1,224 @@
<?php
namespace Tests\Feature;
use App\Models\AdminActivityLog;
use App\Models\User;
use App\Services\DatabaseBackupService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class BackupAndRestoreTest extends TestCase
{
use RefreshDatabase;
private User $superAdmin;
private DatabaseBackupService $backupService;
protected function setUp(): void
{
parent::setUp();
$role = Role::firstOrCreate(['name' => 'super_admin']);
$this->superAdmin = User::factory()->create([
'username' => 'superadmin_backup_test',
'role' => 'super_admin',
'password' => bcrypt('password123'),
]);
$this->superAdmin->assignRole($role);
$this->backupService = new DatabaseBackupService();
}
protected function tearDown(): void
{
// Bersihkan seluruh file uji coba di storage/app/backups
$dir = $this->backupService->getBackupDirectory();
if (File::isDirectory($dir)) {
foreach (File::files($dir) as $f) {
if (str_starts_with($f->getFilename(), 'test_') || str_starts_with($f->getFilename(), 'backup_')) {
@unlink($f->getPathname());
}
}
}
parent::tearDown();
}
public function test_super_admin_can_access_backup_page(): void
{
$response = $this->actingAs($this->superAdmin)
->get(route('admin.backups.index'));
$response->assertStatus(200);
$response->assertViewIs('admin.backups.index');
$response->assertViewHas('backups');
$response->assertViewHas('stats');
$response->assertSee('Backup & Restore Sistem');
$response->assertSee('Buat Backup Baru');
$response->assertSee('Unggah File Backup');
}
public function test_non_super_admin_cannot_access_backup_page(): void
{
$regularUser = User::factory()->create([
'username' => 'regular_user_test',
'role' => 'employee',
]);
$employeeRole = Role::firstOrCreate(['name' => 'employee']);
$regularUser->assignRole($employeeRole);
$response = $this->actingAs($regularUser)
->get(route('admin.backups.index'));
$response->assertStatus(403);
}
public function test_super_admin_can_create_database_backup(): void
{
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.store'), [
'type' => 'database',
]);
$response->assertSessionHas('success');
$response->assertRedirect();
$backups = $this->backupService->listBackups();
$this->assertNotEmpty($backups);
$this->assertEquals('database', $backups[0]['type']);
$this->assertStringEndsWith('.sql', $backups[0]['filename']);
// Verifikasi log aktivitas
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'create',
'module' => 'Backup & Restore',
'user_id' => $this->superAdmin->id,
]);
}
public function test_super_admin_can_download_backup_file(): void
{
$filename = $this->backupService->createDatabaseBackup('test_dl.sql');
$response = $this->actingAs($this->superAdmin)
->get(route('admin.backups.download', $filename));
$response->assertStatus(200);
$response->assertHeader('content-disposition');
}
public function test_super_admin_can_upload_backup_file(): void
{
$file = UploadedFile::fake()->createWithContent('test_uploaded_backup.sql', '-- MySQL dump test\nSET FOREIGN_KEY_CHECKS=0;\n');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.upload'), [
'backup_file' => $file,
]);
$response->assertSessionHas('success');
$targetPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_uploaded_backup.sql';
$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
{
$filename = $this->backupService->createDatabaseBackup('test_for_restore.sql');
// Percobaan tanpa konfirmasi yang benar
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', $filename), [
'confirmation' => 'SALAH',
'password' => 'passwordsalah',
]);
$response->assertSessionHas('error');
}
public function test_super_admin_can_restore_from_backup_with_confirmation_string(): void
{
$filename = $this->backupService->createDatabaseBackup('test_real_restore.sql');
$response = $this->actingAs($this->superAdmin)
->post(route('admin.backups.restore', $filename), [
'confirmation' => 'PULIHKAN',
]);
$response->assertSessionHas('success');
$this->assertDatabaseHas('admin_activity_logs', [
'action_type' => 'update',
'module' => 'Backup & Restore',
'target_name' => $filename,
]);
}
public function test_super_admin_can_delete_backup_file(): void
{
$filename = $this->backupService->createDatabaseBackup('test_to_delete.sql');
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
$this->assertTrue(File::exists($fullPath));
$response = $this->actingAs($this->superAdmin)
->delete(route('admin.backups.destroy', $filename));
$response->assertSessionHas('success');
$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
{
$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', [
'--type' => 'database',
'--filename' => 'test_cli_db.sql',
])->assertSuccessful();
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . 'test_cli_db.sql';
$this->assertTrue(File::exists($fullPath));
}
}