feat(backup): add standalone in-portal .kmh converter to Excel, CSV, and SQL with zero storage retention
This commit is contained in:
@@ -6,6 +6,8 @@ use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminActivityLog;
|
||||
use App\Models\BackupLog;
|
||||
use App\Services\DatabaseBackupService;
|
||||
use App\Services\KmhConverterService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
@@ -18,7 +20,8 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
class BackupController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected DatabaseBackupService $backupService
|
||||
protected DatabaseBackupService $backupService,
|
||||
protected KmhConverterService $converterService
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -409,4 +412,94 @@ class BackupController extends Controller
|
||||
|
||||
return back()->with('error', "File backup '{$filename}' tidak ditemukan di server atau sudah pernah dihapus.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Periksa metadata & daftar tabel dari berkas .kmh yang diunggah dari komputer.
|
||||
* Mengembalikan informasi file dan tabel dalam format JSON tanpa menyimpan data di server (0 Byte retained).
|
||||
*/
|
||||
public function converterInspect(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'backup_file' => 'required|file',
|
||||
]);
|
||||
|
||||
$file = $request->file('backup_file');
|
||||
$originalName = $file->getClientOriginalName();
|
||||
|
||||
if (!str_ends_with(strtolower($originalName), '.kmh')) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$metadata = $this->converterService->inspectUploadedFile($file);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => $metadata,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => $e->getMessage(),
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Konversi berkas .kmh yang diunggah ke format pilihan (xlsx, csv, sql) untuk tabel-tabel yang dicentang.
|
||||
* Mengalirkan file hasil langsung ke browser dan segera menghapus semua file sementara (Zero Disk Retention).
|
||||
*/
|
||||
public function converterExecute(Request $request): BinaryFileResponse|JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'backup_file' => 'required|file',
|
||||
'tables' => 'required|array|min:1',
|
||||
'tables.*' => 'required|string',
|
||||
'format' => 'required|in:xlsx,csv,sql',
|
||||
]);
|
||||
|
||||
$file = $request->file('backup_file');
|
||||
$selectedTables = $request->input('tables');
|
||||
$format = $request->input('format');
|
||||
$originalName = $file->getClientOriginalName();
|
||||
|
||||
if (!str_ends_with(strtolower($originalName), '.kmh')) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->converterService->convertUploadedFile($file, $selectedTables, $format);
|
||||
|
||||
AdminActivityLog::record(
|
||||
actionType: 'export',
|
||||
module: 'Backup & Restore',
|
||||
description: "Mengonversi arsip .kmh '{$originalName}' ke format " . strtoupper($format) . " untuk " . count($selectedTables) . " tabel.",
|
||||
targetType: 'BackupFile',
|
||||
targetName: $originalName
|
||||
);
|
||||
|
||||
$workDir = $result['work_dir'];
|
||||
register_shutdown_function(function () use ($workDir) {
|
||||
if (is_dir($workDir)) {
|
||||
File::deleteDirectory($workDir);
|
||||
}
|
||||
});
|
||||
|
||||
return response()->download($result['path'], $result['filename'], [
|
||||
'Content-Type' => $result['mime'],
|
||||
'Access-Control-Expose-Headers' => 'Content-Disposition',
|
||||
])->deleteFileAfterSend(true);
|
||||
} catch (\Throwable $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Gagal melakukan konversi arsip: ' . $e->getMessage(),
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use RuntimeException;
|
||||
use ZipArchive;
|
||||
|
||||
class KmhConverterService
|
||||
{
|
||||
public function __construct(
|
||||
protected DatabaseBackupService $backupService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Periksa metadata dan daftar tabel dari berkas .kmh yang diunggah dari PC.
|
||||
* Mengembalikan informasi file dan tabel tanpa menyimpan data di server (Zero Storage Retention).
|
||||
*
|
||||
* @return array{
|
||||
* filename: string,
|
||||
* size_human: string,
|
||||
* created_at_human: string,
|
||||
* created_at_diff: string,
|
||||
* table_count: int,
|
||||
* tables: array<string>,
|
||||
* database: string,
|
||||
* has_media: bool
|
||||
* }
|
||||
*/
|
||||
public function inspectUploadedFile(UploadedFile $file): array
|
||||
{
|
||||
$realPath = $file->getRealPath();
|
||||
if (!$realPath || !is_file($realPath)) {
|
||||
throw new RuntimeException("Berkas unggahan tidak ditemukan atau korup.");
|
||||
}
|
||||
|
||||
$kmhContent = file_get_contents($realPath);
|
||||
if ($kmhContent === false) {
|
||||
throw new RuntimeException("Gagal membaca berkas .kmh yang diunggah.");
|
||||
}
|
||||
|
||||
// Dekripsi arsip .kmh menggunakan kunci sistem
|
||||
$decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
|
||||
unset($kmhContent);
|
||||
|
||||
$tempZipPath = storage_path('app/temp_inspect_' . uniqid() . '.zip');
|
||||
file_put_contents($tempZipPath, $decryptedZipContent);
|
||||
unset($decryptedZipContent);
|
||||
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($tempZipPath) !== true) {
|
||||
@unlink($tempZipPath);
|
||||
throw new RuntimeException("Konten terdekripsi bukan merupakan arsip ZIP yang sah.");
|
||||
}
|
||||
|
||||
try {
|
||||
$manifestJson = $zip->getFromName('manifest.json');
|
||||
$manifest = $manifestJson ? json_decode($manifestJson, true) : [];
|
||||
|
||||
$tables = $manifest['tables'] ?? [];
|
||||
|
||||
// Jika manifest tidak memiliki daftar tabel, baca cepat dari struktur database.sql
|
||||
if (empty($tables)) {
|
||||
$sqlContent = $zip->getFromName('database.sql');
|
||||
if ($sqlContent) {
|
||||
preg_match_all('/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?([a-zA-Z0-9_]+)`?/i', $sqlContent, $matches);
|
||||
$tables = array_values(array_unique($matches[1] ?? []));
|
||||
}
|
||||
}
|
||||
|
||||
sort($tables);
|
||||
|
||||
$createdAt = isset($manifest['created_at'])
|
||||
? Carbon::parse($manifest['created_at'])
|
||||
: Carbon::createFromTimestamp($file->getMTime());
|
||||
|
||||
return [
|
||||
'filename' => $file->getClientOriginalName(),
|
||||
'size_human' => $this->backupService->formatBytes($file->getSize()),
|
||||
'created_at_human' => $createdAt->translatedFormat('d F Y, H:i') . ' WIB',
|
||||
'created_at_diff' => $createdAt->diffForHumans(),
|
||||
'table_count' => count($tables),
|
||||
'tables' => $tables,
|
||||
'database' => $manifest['database'] ?? 'rkm_kmh',
|
||||
'has_media' => (bool) ($manifest['has_media'] ?? false),
|
||||
];
|
||||
} finally {
|
||||
$zip->close();
|
||||
if (is_file($tempZipPath)) {
|
||||
@unlink($tempZipPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Konversi berkas .kmh yang diunggah ke format pilihan (xlsx, csv, sql) untuk tabel-tabel terpilih.
|
||||
*
|
||||
* @param UploadedFile $file
|
||||
* @param array<string> $selectedTables
|
||||
* @param string $format 'xlsx' | 'csv' | 'sql'
|
||||
* @return array{
|
||||
* path: string,
|
||||
* filename: string,
|
||||
* mime: string,
|
||||
* work_dir: string
|
||||
* }
|
||||
*/
|
||||
public function convertUploadedFile(UploadedFile $file, array $selectedTables, string $format): array
|
||||
{
|
||||
$realPath = $file->getRealPath();
|
||||
if (!$realPath || !is_file($realPath)) {
|
||||
throw new RuntimeException("Berkas unggahan tidak ditemukan.");
|
||||
}
|
||||
|
||||
if (empty($selectedTables)) {
|
||||
throw new RuntimeException("Silakan pilih minimal 1 tabel untuk dikonversi.");
|
||||
}
|
||||
|
||||
$format = strtolower($format);
|
||||
if (!in_array($format, ['xlsx', 'csv', 'sql'], true)) {
|
||||
throw new RuntimeException("Format konversi tidak didukung: {$format}");
|
||||
}
|
||||
|
||||
$workDir = storage_path('app/temp_kmh_conv_' . uniqid());
|
||||
File::ensureDirectoryExists($workDir);
|
||||
|
||||
$tempZipPath = $workDir . '/package.zip';
|
||||
$sqlPath = $workDir . '/database.sql';
|
||||
|
||||
try {
|
||||
// 1. Dekripsi payload .kmh
|
||||
$kmhContent = file_get_contents($realPath);
|
||||
$decryptedZipContent = $this->backupService->decryptFromKmh($kmhContent);
|
||||
unset($kmhContent);
|
||||
|
||||
file_put_contents($tempZipPath, $decryptedZipContent);
|
||||
unset($decryptedZipContent);
|
||||
|
||||
// 2. Ekstrak database.sql saja
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($tempZipPath) !== true) {
|
||||
throw new RuntimeException("Gagal membuka arsip kontainer backup.");
|
||||
}
|
||||
|
||||
$zip->extractTo($workDir, ['database.sql']);
|
||||
$zip->close();
|
||||
@unlink($tempZipPath);
|
||||
|
||||
if (!is_file($sqlPath)) {
|
||||
throw new RuntimeException("Berkas database.sql tidak ditemukan di dalam arsip .kmh.");
|
||||
}
|
||||
|
||||
$timestamp = now()->format('Ymd_His');
|
||||
|
||||
// 3. Proses berdasarkan format
|
||||
if ($format === 'sql') {
|
||||
$outputFilename = 'Arsip_KMH_SQL_' . $timestamp . '.sql';
|
||||
$outputPath = $workDir . '/' . $outputFilename;
|
||||
$this->extractFilteredSql($sqlPath, $selectedTables, $outputPath);
|
||||
@unlink($sqlPath);
|
||||
|
||||
return [
|
||||
'path' => $outputPath,
|
||||
'filename' => $outputFilename,
|
||||
'mime' => 'application/sql',
|
||||
'work_dir' => $workDir,
|
||||
];
|
||||
}
|
||||
|
||||
// Ekstrak data tabel ke bentuk CSV sementara di disk
|
||||
$csvDir = $workDir . '/csv_tables';
|
||||
File::ensureDirectoryExists($csvDir);
|
||||
$extractedTables = $this->streamSqlToCsvFiles($sqlPath, $selectedTables, $csvDir);
|
||||
@unlink($sqlPath);
|
||||
|
||||
if ($format === 'csv') {
|
||||
$outputFilename = 'Arsip_KMH_CSV_' . $timestamp . '.zip';
|
||||
$outputPath = $workDir . '/' . $outputFilename;
|
||||
|
||||
$zipOut = new ZipArchive();
|
||||
if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
||||
throw new RuntimeException("Gagal membuat arsip ZIP untuk file CSV.");
|
||||
}
|
||||
|
||||
foreach ($extractedTables as $tbl => $csvFile) {
|
||||
if (is_file($csvFile)) {
|
||||
$zipOut->addFile($csvFile, $tbl . '.csv');
|
||||
}
|
||||
}
|
||||
$zipOut->close();
|
||||
File::deleteDirectory($csvDir);
|
||||
|
||||
return [
|
||||
'path' => $outputPath,
|
||||
'filename' => $outputFilename,
|
||||
'mime' => 'application/zip',
|
||||
'work_dir' => $workDir,
|
||||
];
|
||||
}
|
||||
|
||||
// Format XLSX
|
||||
if (count($selectedTables) === 1) {
|
||||
// Single table -> langsung 1 file .xlsx
|
||||
$tbl = $selectedTables[0];
|
||||
$outputFilename = 'Tabel_' . $tbl . '_' . $timestamp . '.xlsx';
|
||||
$outputPath = $workDir . '/' . $outputFilename;
|
||||
|
||||
$csvFile = $csvDir . '/' . $tbl . '.csv';
|
||||
$this->convertCsvToXlsx($csvFile, $tbl, $outputPath);
|
||||
File::deleteDirectory($csvDir);
|
||||
|
||||
return [
|
||||
'path' => $outputPath,
|
||||
'filename' => $outputFilename,
|
||||
'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'work_dir' => $workDir,
|
||||
];
|
||||
} else {
|
||||
// Multiple tables -> dikemas dalam 1 file .zip berisi masing-masing .xlsx
|
||||
$outputFilename = 'Arsip_KMH_Excel_' . $timestamp . '.zip';
|
||||
$outputPath = $workDir . '/' . $outputFilename;
|
||||
|
||||
$zipOut = new ZipArchive();
|
||||
if ($zipOut->open($outputPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
|
||||
throw new RuntimeException("Gagal membuat paket ZIP Excel.");
|
||||
}
|
||||
|
||||
foreach ($extractedTables as $tbl => $csvFile) {
|
||||
if (is_file($csvFile)) {
|
||||
$tblXlsxPath = $workDir . '/' . $tbl . '.xlsx';
|
||||
$this->convertCsvToXlsx($csvFile, $tbl, $tblXlsxPath);
|
||||
$zipOut->addFile($tblXlsxPath, $tbl . '.xlsx');
|
||||
}
|
||||
}
|
||||
$zipOut->close();
|
||||
File::deleteDirectory($csvDir);
|
||||
|
||||
return [
|
||||
'path' => $outputPath,
|
||||
'filename' => $outputFilename,
|
||||
'mime' => 'application/zip',
|
||||
'work_dir' => $workDir,
|
||||
];
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$this->cleanDirectory($workDir);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Memfilter isi database.sql hanya untuk tabel terpilih dan menulis ke file output SQL.
|
||||
*/
|
||||
protected function extractFilteredSql(string $inputSqlPath, array $selectedTables, string $outputSqlPath): void
|
||||
{
|
||||
$inHandle = fopen($inputSqlPath, 'r');
|
||||
$outHandle = fopen($outputSqlPath, 'w');
|
||||
|
||||
if (!$inHandle || !$outHandle) {
|
||||
if ($inHandle) fclose($inHandle);
|
||||
if ($outHandle) fclose($outHandle);
|
||||
throw new RuntimeException("Gagal membuka berkas SQL untuk operasi filter.");
|
||||
}
|
||||
|
||||
try {
|
||||
$nowStr = now()->format('Y-m-d H:i:s');
|
||||
$tablesStr = implode(', ', $selectedTables);
|
||||
fwrite($outHandle, "-- ==============================================================\n");
|
||||
fwrite($outHandle, "-- RKM-KMH SECURE DATABASE DUMP - HASIL FILTER KONVERSI\n");
|
||||
fwrite($outHandle, "-- Waktu Ekstrak : {$nowStr} WIB\n");
|
||||
fwrite($outHandle, "-- Tabel Terpilih: {$tablesStr}\n");
|
||||
fwrite($outHandle, "-- ==============================================================\n\n");
|
||||
fwrite($outHandle, "SET NAMES utf8mb4;\n");
|
||||
fwrite($outHandle, "SET FOREIGN_KEY_CHECKS = 0;\n\n");
|
||||
|
||||
$selectedMap = array_fill_keys($selectedTables, true);
|
||||
$currentTable = null;
|
||||
$writing = false;
|
||||
|
||||
while (($line = fgets($inHandle)) !== false) {
|
||||
// Deteksi nama tabel pada komentar, DROP TABLE, CREATE TABLE, atau INSERT INTO
|
||||
if (preg_match('/(?:DROP\s+TABLE\s+IF\s+EXISTS|CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|INSERT\s+INTO)\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
|
||||
$tbl = $m[1];
|
||||
$currentTable = $tbl;
|
||||
$writing = isset($selectedMap[$tbl]);
|
||||
} elseif (preg_match('/^--\s+(?:Struktur|Dumping\s+Data)\s+untuk\s+`?([a-zA-Z0-9_]+)`?/i', $line, $m)) {
|
||||
$tbl = $m[1];
|
||||
$currentTable = $tbl;
|
||||
$writing = isset($selectedMap[$tbl]);
|
||||
}
|
||||
|
||||
if ($writing) {
|
||||
fwrite($outHandle, $line);
|
||||
}
|
||||
}
|
||||
|
||||
fwrite($outHandle, "\nSET FOREIGN_KEY_CHECKS = 1;\n");
|
||||
fwrite($outHandle, "-- END OF FILTERED DUMP\n");
|
||||
} finally {
|
||||
fclose($inHandle);
|
||||
fclose($outHandle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Membaca stream SQL dan mengekstrak tabel-tabel yang dipilih ke file CSV terpisah.
|
||||
* Sangat hemat memori (RAM usage < 5MB).
|
||||
*
|
||||
* @return array<string, string> Map tableName => csvFilePath
|
||||
*/
|
||||
protected function streamSqlToCsvFiles(string $sqlPath, array $selectedTables, string $csvOutputDir): array
|
||||
{
|
||||
$handle = fopen($sqlPath, 'r');
|
||||
if (!$handle) {
|
||||
throw new RuntimeException("Gagal membuka file database.sql untuk pembacaan stream.");
|
||||
}
|
||||
|
||||
$selectedMap = array_fill_keys($selectedTables, true);
|
||||
$csvHandles = [];
|
||||
$headerWritten = [];
|
||||
$activeTable = null;
|
||||
$activeColumns = [];
|
||||
|
||||
try {
|
||||
while (($line = fgets($handle)) !== false) {
|
||||
$trimmed = trim($line);
|
||||
if ($trimmed === '' || str_starts_with($trimmed, '--') || str_starts_with($trimmed, '/*')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cek baris INSERT INTO `tableName` (`col1`, `col2`, ...) VALUES
|
||||
if (preg_match('/^INSERT\s+INTO\s+`?([a-zA-Z0-9_]+)`?\s*(?:\(([^)]+)\))?\s*VALUES/i', $trimmed, $m)) {
|
||||
$tbl = $m[1];
|
||||
if (isset($selectedMap[$tbl])) {
|
||||
$activeTable = $tbl;
|
||||
if (!isset($csvHandles[$tbl])) {
|
||||
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
|
||||
$csvHandles[$tbl] = fopen($csvPath, 'w');
|
||||
// Tulis UTF-8 BOM agar Excel membukanya dengan karakter yang sempurna
|
||||
fwrite($csvHandles[$tbl], "\xEF\xBB\xBF");
|
||||
}
|
||||
|
||||
if (!empty($m[2]) && empty($headerWritten[$tbl])) {
|
||||
preg_match_all('/`?([a-zA-Z0-9_]+)`?/', $m[2], $colMatches);
|
||||
$activeColumns = array_values(array_filter(array_map('trim', $colMatches[1] ?? [])));
|
||||
if (!empty($activeColumns)) {
|
||||
fputcsv($csvHandles[$tbl], $activeColumns);
|
||||
$headerWritten[$tbl] = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$activeTable = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Jika sedang membaca baris data dari activeTable
|
||||
if ($activeTable && isset($csvHandles[$activeTable])) {
|
||||
$tuples = $this->extractTuplesFromSqlLine($trimmed);
|
||||
foreach ($tuples as $tupleStr) {
|
||||
$values = $this->parseTupleValues($tupleStr);
|
||||
fputcsv($csvHandles[$activeTable], $values);
|
||||
}
|
||||
|
||||
if (str_ends_with($trimmed, ';')) {
|
||||
$activeTable = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pastikan semua tabel terpilih memiliki file CSV, meskipun kosong
|
||||
foreach ($selectedTables as $tbl) {
|
||||
if (!isset($csvHandles[$tbl])) {
|
||||
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
|
||||
$h = fopen($csvPath, 'w');
|
||||
fwrite($h, "\xEF\xBB\xBF");
|
||||
fputcsv($h, ['(Tabel kosong / Tidak ada data)']);
|
||||
fclose($h);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fclose($handle);
|
||||
foreach ($csvHandles as $h) {
|
||||
if (is_resource($h)) fclose($h);
|
||||
}
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($selectedTables as $tbl) {
|
||||
$csvPath = $csvOutputDir . '/' . $tbl . '.csv';
|
||||
if (is_file($csvPath)) {
|
||||
$result[$tbl] = $csvPath;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengonversi berkas CSV tabel menjadi berkas OpenXML .xlsx menggunakan SimpleXlsxExporter.
|
||||
*/
|
||||
protected function convertCsvToXlsx(string $csvPath, string $tableName, string $targetXlsxPath): void
|
||||
{
|
||||
if (!is_file($csvPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$h = fopen($csvPath, 'r');
|
||||
if (!$h) return;
|
||||
|
||||
// Skip UTF-8 BOM jika ada
|
||||
$bom = fread($h, 3);
|
||||
if ($bom !== "\xEF\xBB\xBF") {
|
||||
rewind($h);
|
||||
}
|
||||
|
||||
$headers = [];
|
||||
$rows = [];
|
||||
$rowCount = 0;
|
||||
|
||||
$firstRow = fgetcsv($h);
|
||||
if ($firstRow && !empty($firstRow)) {
|
||||
$headerMap = [];
|
||||
foreach ($firstRow as $idx => $colName) {
|
||||
$headerMap[$colName ?: ('Kolom_' . ($idx + 1))] = 18;
|
||||
}
|
||||
$headers = $headerMap;
|
||||
|
||||
// Baca baris data (maksimal 50.000 baris untuk kenyamanan memori sheet tunggal)
|
||||
while (($row = fgetcsv($h)) !== false && $rowCount < 50000) {
|
||||
$rowCount++;
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
fclose($h);
|
||||
|
||||
if (empty($headers)) {
|
||||
$headers = ['Kolom' => 20];
|
||||
$rows = [['(Tabel kosong)']];
|
||||
}
|
||||
|
||||
$title = 'DATA ARSIP TABEL: ' . strtoupper($tableName);
|
||||
$metaLines = [
|
||||
'Total Data: ' . count($rows) . ' Baris Data',
|
||||
'Diekstrak dari Arsip .kmh pada: ' . now()->translatedFormat('d F Y, H:i') . ' WIB',
|
||||
];
|
||||
|
||||
$xlsxBinary = SimpleXlsxExporter::create($title, $metaLines, $headers, $rows, [], $tableName);
|
||||
file_put_contents($targetXlsxPath, $xlsxBinary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ekstrak potongan tuple tuple '(val1, val2, ...)' dari satu baris SQL.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
protected function extractTuplesFromSqlLine(string $content): array
|
||||
{
|
||||
$tuples = [];
|
||||
$inQuotes = false;
|
||||
$quoteChar = "'";
|
||||
$inTuple = false;
|
||||
$tupleBuffer = '';
|
||||
$len = strlen($content);
|
||||
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$c = $content[$i];
|
||||
|
||||
if ($inQuotes) {
|
||||
$tupleBuffer .= $c;
|
||||
if ($c === '\\') {
|
||||
$i++;
|
||||
if ($i < $len) {
|
||||
$tupleBuffer .= $content[$i];
|
||||
}
|
||||
} elseif ($c === $quoteChar) {
|
||||
if ($i + 1 < $len && $content[$i + 1] === $quoteChar) {
|
||||
$tupleBuffer .= $content[$i + 1];
|
||||
$i++;
|
||||
} else {
|
||||
$inQuotes = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ($c === "'" || $c === '"') {
|
||||
$inQuotes = true;
|
||||
$quoteChar = $c;
|
||||
if ($inTuple) {
|
||||
$tupleBuffer .= $c;
|
||||
}
|
||||
} elseif ($c === '(') {
|
||||
$inTuple = true;
|
||||
$tupleBuffer = '';
|
||||
} elseif ($c === ')' && $inTuple) {
|
||||
$inTuple = false;
|
||||
$tuples[] = $tupleBuffer;
|
||||
$tupleBuffer = '';
|
||||
} elseif ($inTuple) {
|
||||
$tupleBuffer .= $c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $tuples;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsing nilai-nilai di dalam satu tuple SQL menjadi array PHP yang bersih.
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
protected function parseTupleValues(string $tupleStr): array
|
||||
{
|
||||
$values = [];
|
||||
$len = strlen($tupleStr);
|
||||
$inQuotes = false;
|
||||
$curr = '';
|
||||
$quoteChar = "'";
|
||||
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$char = $tupleStr[$i];
|
||||
|
||||
if ($inQuotes) {
|
||||
if ($char === '\\') {
|
||||
$next = $tupleStr[$i + 1] ?? '';
|
||||
$curr .= match($next) {
|
||||
'n' => "\n",
|
||||
'r' => "\r",
|
||||
't' => "\t",
|
||||
"'" => "'",
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
default => $next
|
||||
};
|
||||
$i++;
|
||||
} elseif ($char === $quoteChar) {
|
||||
if (($tupleStr[$i + 1] ?? '') === $quoteChar) {
|
||||
$curr .= $quoteChar;
|
||||
$i++;
|
||||
} else {
|
||||
$inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
$curr .= $char;
|
||||
}
|
||||
} else {
|
||||
if ($char === "'" || $char === '"') {
|
||||
$inQuotes = true;
|
||||
$quoteChar = $char;
|
||||
} elseif ($char === ',') {
|
||||
$val = trim($curr);
|
||||
$values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
|
||||
$curr = '';
|
||||
} else {
|
||||
$curr .= $char;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$val = trim($curr);
|
||||
$values[] = (strcasecmp($val, 'NULL') === 0) ? null : $val;
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus direktori kerja sementara secara menyeluruh.
|
||||
*/
|
||||
public function cleanDirectory(?string $directory): void
|
||||
{
|
||||
if ($directory && File::isDirectory($directory)) {
|
||||
File::deleteDirectory($directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ class SimpleXlsxExporter
|
||||
* @param array $alignments Optional per-column alignment: 'center' or 'left'
|
||||
* @return string Raw zip content
|
||||
*/
|
||||
public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = []): string
|
||||
public static function create(string $title, array $metaLines, array $headers, array $rows, array $alignments = [], ?string $sheetName = null): string
|
||||
{
|
||||
$numCols = count($headers);
|
||||
$lastColLetter = self::colLetter($numCols);
|
||||
@@ -143,10 +143,11 @@ class SimpleXlsxExporter
|
||||
</cellXfs>
|
||||
</styleSheet>';
|
||||
|
||||
$cleanSheetName = htmlspecialchars(mb_substr($sheetName ?: 'Data', 0, 31), ENT_XML1);
|
||||
$workbookXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
<sheets>
|
||||
<sheet name="Data SIMPER" sheetId="1" r:id="rId1" />
|
||||
<sheet name="' . $cleanSheetName . '" sheetId="1" r:id="rId1" />
|
||||
</sheets>
|
||||
</workbook>';
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2.5 shrink-0 self-start md:self-auto">
|
||||
<button type="button"
|
||||
onclick="openConverterModal()"
|
||||
class="whitespace-nowrap px-4 py-2.5 rounded-xl border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-emerald-900 text-xs font-semibold transition shadow-2xs inline-flex items-center gap-1.5">
|
||||
Konversi Berkas .kmh
|
||||
</button>
|
||||
<button type="button"
|
||||
onclick="openDirectRestoreModal()"
|
||||
class="whitespace-nowrap px-4 py-2.5 rounded-xl border border-amber-300 bg-amber-50 hover:bg-amber-100 text-amber-900 text-xs font-semibold transition shadow-2xs inline-flex items-center gap-1.5">
|
||||
@@ -632,6 +637,163 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========================================================================= -->
|
||||
<!-- MODAL: KONVERTER ARSIP BERKAS .KMH KE EXCEL / CSV / SQL -->
|
||||
<!-- ========================================================================= -->
|
||||
<div id="kmhConverterModal" data-backdrop="static" class="fixed inset-0 z-50 hidden bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
|
||||
<div class="bg-white rounded-2xl max-w-3xl w-full shadow-2xl overflow-hidden animate-scale-in border border-slate-100 my-8">
|
||||
<!-- Header Modal -->
|
||||
<div class="px-6 py-4 bg-slate-50 border-b border-slate-200/80 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||
KMH CONVERTER
|
||||
</span>
|
||||
<div>
|
||||
<h3 class="text-base font-bold text-slate-900">Konversi Berkas .kmh ke Excel / CSV / SQL</h3>
|
||||
<p class="text-xs text-slate-500 mt-0.5">Unggah berkas .kmh dari komputer untuk dikonversi menjadi format siap olah tanpa menyentuh database aktif.</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onclick="closeConverterModal()" class="text-slate-400 hover:text-slate-600 text-xl p-1 leading-none">×</button>
|
||||
</div>
|
||||
|
||||
<div class="p-6 space-y-5">
|
||||
<!-- Alert Zero Retention & Database Safety -->
|
||||
<div class="p-3 bg-emerald-50/70 border border-emerald-200/80 rounded-xl text-xs text-emerald-950 flex items-start gap-2.5">
|
||||
<span class="inline-block w-2 h-2 rounded-full bg-emerald-600 mt-1 shrink-0"></span>
|
||||
<div>
|
||||
<strong class="font-semibold text-emerald-900">Keamanan Total & Bebas Kapasitas Server:</strong>
|
||||
Proses konversi bersifat <em>read-only</em> dan <strong>sama sekali tidak menyentuh database aktif MySQL</strong>. Berkas yang diunggah hanya diproses sementara di memori dan langsung dihapus otomatis seketika setelah unduhan dimulai (0 Byte tertinggal di VPS).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Banner -->
|
||||
<div id="converterError" class="hidden p-3 bg-rose-50 border border-rose-200 rounded-xl text-xs text-rose-800 font-medium">
|
||||
<span id="converterErrorMessage"></span>
|
||||
</div>
|
||||
|
||||
<!-- Step 1: Area Dropzone Upload dari PC -->
|
||||
<div id="panelConverterUpload" class="space-y-3">
|
||||
<div id="converterDropzone"
|
||||
class="border-2 border-dashed border-slate-300 hover:border-emerald-500 rounded-2xl p-7 text-center bg-slate-50 hover:bg-emerald-50/20 transition cursor-pointer select-none"
|
||||
onclick="document.getElementById('converterFileInput').click()"
|
||||
ondragover="handleDropzoneDragOver(event, this)"
|
||||
ondragleave="handleDropzoneDragLeave(event, this)"
|
||||
ondrop="handleConverterFileDrop(event, this)">
|
||||
<p class="text-xs font-bold text-slate-800" id="converterDropzonePrompt">Tarik & Letakkan berkas .kmh di sini</p>
|
||||
<p class="text-[11px] text-slate-400 mt-1">atau <span class="text-emerald-600 font-semibold underline">klik untuk memilih dari komputer Anda</span></p>
|
||||
<p class="text-[10px] text-slate-400 mt-2">Mendukung berkas arsip .kmh terenkripsi (Maks. 500 MB)</p>
|
||||
<input type="file" id="converterFileInput" accept=".kmh" class="hidden" onchange="handleConverterFileInput(this)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading Spinner State -->
|
||||
<div id="converterLoading" class="hidden py-8 text-center space-y-2">
|
||||
<div class="inline-block w-8 h-8 border-3 border-emerald-600 border-t-transparent rounded-full animate-spin"></div>
|
||||
<p class="text-xs font-semibold text-slate-700" id="converterLoadingText">Mendekripsi & memeriksa integritas berkas .kmh...</p>
|
||||
<p class="text-[11px] text-slate-400">Verifikasi tanda tangan HMAC SHA-256 & membaca daftar tabel</p>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Konfigurasi Format & Pilihan Tabel (Muncul setelah inspect sukses) -->
|
||||
<div id="panelConverterConfig" class="hidden space-y-5">
|
||||
<!-- Metadata Strip -->
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-2.5 p-3.5 bg-slate-50 border border-slate-200/80 rounded-xl text-xs">
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Nama Berkas</span>
|
||||
<span class="font-mono font-semibold text-slate-800 truncate block mt-0.5" id="convFilename">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Ukuran Arsip</span>
|
||||
<span class="font-semibold text-slate-800 block mt-0.5" id="convFileSize">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Tanggal Dibuat</span>
|
||||
<span class="font-semibold text-slate-800 block mt-0.5" id="convCreatedAt">-</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-[10px] uppercase font-bold text-slate-400 block">Database Asal</span>
|
||||
<span class="font-mono font-semibold text-slate-800 block mt-0.5" id="convDatabase">-</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Pilihan Format Keluaran -->
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs font-bold text-slate-800 block">Pilih Format Hasil Konversi:</label>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="xlsx" checked class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">Microsoft Excel (.xlsx)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">File spreadsheet siap buka di Excel dengan filter header.</span>
|
||||
</label>
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="csv" class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">Kumpulan CSV (.zip)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">File .csv per tabel di dalam paket zip, sangat ringan.</span>
|
||||
</label>
|
||||
<label class="relative flex flex-col p-3 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50/30">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="radio" name="convFormat" value="sql" class="text-emerald-600 focus:ring-emerald-500">
|
||||
<span class="text-xs font-bold text-slate-900">SQL Mentah (.sql)</span>
|
||||
</div>
|
||||
<span class="text-[11px] text-slate-500 mt-1 pl-5">Dump DDL & data bersih siap impor ke MySQL/HeidiSQL.</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Pemilihan Tabel (Checklist) -->
|
||||
<div class="bg-white rounded-xl border border-slate-200 p-4 space-y-3">
|
||||
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-2.5 pb-2.5 border-b border-slate-100">
|
||||
<div>
|
||||
<span class="text-xs font-bold text-slate-800 block">
|
||||
Pilih Tabel yang Ingin Dikonversi:
|
||||
</span>
|
||||
<span class="text-[11px] text-slate-500">
|
||||
Terpilih: <strong id="convSelectedCount" class="text-emerald-700 font-bold">0</strong> dari <span id="convTotalTableCount">0</span> tabel
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="text" id="convTableFilterInput" oninput="filterConverterTables(this.value)" placeholder="Cari nama tabel..." class="text-[11px] px-2.5 py-1.5 rounded-lg border border-slate-200 focus:outline-none focus:border-emerald-500 w-full sm:w-44">
|
||||
<button type="button" onclick="toggleSelectAllConverterTables(true)" class="whitespace-nowrap px-2.5 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 text-[11px] font-semibold transition">
|
||||
Pilih Semua
|
||||
</button>
|
||||
<button type="button" onclick="toggleSelectAllConverterTables(false)" class="whitespace-nowrap px-2.5 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 text-[11px] font-semibold transition">
|
||||
Bersihkan
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Checklist Container -->
|
||||
<div id="convTableList" class="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-48 overflow-y-auto p-1.5 bg-slate-50/70 rounded-xl border border-slate-100">
|
||||
<!-- Checkboxes generated via JS -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Footer -->
|
||||
<div class="pt-3 border-t border-slate-100 flex flex-wrap items-center justify-between gap-3">
|
||||
<button type="button" onclick="resetConverterToUpload()" class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-xs transition">
|
||||
Ganti Berkas .kmh
|
||||
</button>
|
||||
<button type="button"
|
||||
id="btnExecuteConvert"
|
||||
onclick="executeConverterDownload()"
|
||||
class="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs transition shadow-xs inline-flex items-center gap-2">
|
||||
<span id="btnExecuteConvertText">Mulai Konversi & Unduh</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-6 py-3 bg-slate-50 border-t border-slate-100 flex items-center justify-end">
|
||||
<button type="button" onclick="closeConverterModal()" class="px-4 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-xs transition">
|
||||
Tutup
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Auto-Download Script jika ada sesi auto_download -->
|
||||
@if(session('auto_download'))
|
||||
<script>
|
||||
@@ -863,5 +1025,250 @@
|
||||
document.getElementById('deleteBackupModal').classList.add('hidden');
|
||||
document.documentElement.classList.remove('modal-open');
|
||||
}
|
||||
|
||||
/* ========================================================================= */
|
||||
/* LOGIKA JAVASCRIPT: KONVERTER ARSIP .KMH (MURNI UPLOAD DARI PC) */
|
||||
/* ========================================================================= */
|
||||
let currentConverterFile = null;
|
||||
let currentConverterTables = [];
|
||||
|
||||
function openConverterModal() {
|
||||
document.getElementById('kmhConverterModal').classList.remove('hidden');
|
||||
document.documentElement.classList.add('modal-open');
|
||||
resetConverterToUpload();
|
||||
}
|
||||
|
||||
function closeConverterModal() {
|
||||
document.getElementById('kmhConverterModal').classList.add('hidden');
|
||||
document.documentElement.classList.remove('modal-open');
|
||||
}
|
||||
|
||||
function resetConverterToUpload() {
|
||||
document.getElementById('converterLoading').classList.add('hidden');
|
||||
document.getElementById('converterError').classList.add('hidden');
|
||||
document.getElementById('panelConverterConfig').classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
const fileInput = document.getElementById('converterFileInput');
|
||||
if (fileInput) fileInput.value = '';
|
||||
currentConverterFile = null;
|
||||
currentConverterTables = [];
|
||||
}
|
||||
|
||||
function showConverterError(msg) {
|
||||
const errorDiv = document.getElementById('converterError');
|
||||
document.getElementById('converterErrorMessage').textContent = msg;
|
||||
errorDiv.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function handleConverterFileInput(input) {
|
||||
if (input.files && input.files[0]) {
|
||||
inspectConverterFile(input.files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function handleConverterFileDrop(e, dropzone) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dropzone.classList.remove('border-emerald-500', 'bg-emerald-50/20');
|
||||
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||
inspectConverterFile(e.dataTransfer.files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function inspectConverterFile(file) {
|
||||
if (!file.name.toLowerCase().endsWith('.kmh')) {
|
||||
alert('File yang dipilih harus berekstensi .kmh!');
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('converterError').classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.add('hidden');
|
||||
const loading = document.getElementById('converterLoading');
|
||||
document.getElementById('converterLoadingText').textContent = `Mendekripsi & memeriksa "${file.name}" (${(file.size / (1024 * 1024)).toFixed(1)} MB)...`;
|
||||
loading.classList.remove('hidden');
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('backup_file', file);
|
||||
formData.append('_token', '{{ csrf_token() }}');
|
||||
|
||||
fetch(`{{ route('admin.backups.converter.inspect') }}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
}
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
loading.classList.add('hidden');
|
||||
if (res.success && res.data) {
|
||||
currentConverterFile = file;
|
||||
currentConverterTables = res.data.tables || [];
|
||||
|
||||
document.getElementById('convFilename').textContent = res.data.filename;
|
||||
document.getElementById('convFileSize').textContent = res.data.size_human;
|
||||
document.getElementById('convCreatedAt').textContent = res.data.created_at_human;
|
||||
document.getElementById('convDatabase').textContent = res.data.database;
|
||||
|
||||
const filterInput = document.getElementById('convTableFilterInput');
|
||||
if (filterInput) filterInput.value = '';
|
||||
|
||||
renderConverterTableChecklist('');
|
||||
document.getElementById('panelConverterConfig').classList.remove('hidden');
|
||||
} else {
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError(res.message || 'Gagal membaca berkas arsip .kmh.');
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
loading.classList.add('hidden');
|
||||
document.getElementById('panelConverterUpload').classList.remove('hidden');
|
||||
showConverterError('Terjadi kesalahan saat memeriksa berkas: ' + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function renderConverterTableChecklist(filter = '') {
|
||||
const container = document.getElementById('convTableList');
|
||||
container.innerHTML = '';
|
||||
|
||||
const filtered = filter
|
||||
? currentConverterTables.filter(t => t.toLowerCase().includes(filter.toLowerCase()))
|
||||
: currentConverterTables;
|
||||
|
||||
document.getElementById('convTotalTableCount').textContent = currentConverterTables.length;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = '<span class="col-span-full text-xs text-slate-400 italic p-2">Tidak ada tabel yang cocok dengan pencarian.</span>';
|
||||
updateConverterSelectedCount();
|
||||
return;
|
||||
}
|
||||
|
||||
filtered.forEach(tbl => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'flex items-center gap-2 p-2 rounded-lg bg-white border border-slate-200 hover:border-emerald-400 hover:bg-emerald-50/20 transition cursor-pointer select-none';
|
||||
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.name = 'convSelectedTables';
|
||||
checkbox.value = tbl;
|
||||
checkbox.checked = true; // Terpilih secara default
|
||||
checkbox.className = 'conv-table-checkbox rounded text-emerald-600 focus:ring-emerald-500 w-3.5 h-3.5';
|
||||
checkbox.onchange = updateConverterSelectedCount;
|
||||
|
||||
const span = document.createElement('span');
|
||||
span.className = 'text-xs font-mono font-medium text-slate-800 truncate';
|
||||
span.textContent = tbl;
|
||||
span.title = tbl;
|
||||
|
||||
label.appendChild(checkbox);
|
||||
label.appendChild(span);
|
||||
container.appendChild(label);
|
||||
});
|
||||
|
||||
updateConverterSelectedCount();
|
||||
}
|
||||
|
||||
function filterConverterTables(query) {
|
||||
renderConverterTableChecklist(query);
|
||||
}
|
||||
|
||||
function toggleSelectAllConverterTables(selectAll) {
|
||||
const checkboxes = document.querySelectorAll('.conv-table-checkbox');
|
||||
checkboxes.forEach(cb => {
|
||||
cb.checked = selectAll;
|
||||
});
|
||||
updateConverterSelectedCount();
|
||||
}
|
||||
|
||||
function updateConverterSelectedCount() {
|
||||
const allCheckboxes = document.querySelectorAll('.conv-table-checkbox');
|
||||
let checkedCount = 0;
|
||||
allCheckboxes.forEach(cb => {
|
||||
if (cb.checked) checkedCount++;
|
||||
});
|
||||
document.getElementById('convSelectedCount').textContent = checkedCount;
|
||||
}
|
||||
|
||||
function executeConverterDownload() {
|
||||
if (!currentConverterFile) {
|
||||
alert('Silakan pilih berkas .kmh terlebih dahulu.');
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedTables = [];
|
||||
document.querySelectorAll('.conv-table-checkbox:checked').forEach(cb => {
|
||||
selectedTables.push(cb.value);
|
||||
});
|
||||
|
||||
if (selectedTables.length === 0) {
|
||||
alert('Silakan pilih minimal satu tabel untuk dikonversi.');
|
||||
return;
|
||||
}
|
||||
|
||||
const formatRadio = document.querySelector('input[name="convFormat"]:checked');
|
||||
const format = formatRadio ? formatRadio.value : 'xlsx';
|
||||
|
||||
const btn = document.getElementById('btnExecuteConvert');
|
||||
const btnText = document.getElementById('btnExecuteConvertText');
|
||||
btn.disabled = true;
|
||||
btn.classList.add('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Mengonversi & Menyiapkan Unduhan...';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('backup_file', currentConverterFile);
|
||||
formData.append('format', format);
|
||||
formData.append('_token', '{{ csrf_token() }}');
|
||||
selectedTables.forEach(t => {
|
||||
formData.append('tables[]', t);
|
||||
});
|
||||
|
||||
fetch(`{{ route('admin.backups.converter.execute') }}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
}
|
||||
})
|
||||
.then(async response => {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Mulai Konversi & Unduh';
|
||||
|
||||
if (!response.ok) {
|
||||
const errData = await response.json().catch(() => ({}));
|
||||
throw new Error(errData.message || 'Terjadi kesalahan pada server saat mengonversi berkas.');
|
||||
}
|
||||
|
||||
// Dapatkan nama file dari header Content-Disposition
|
||||
let filename = `hasil_konversi_${format}.${format === 'csv' ? 'zip' : (format === 'sql' ? 'sql' : 'xlsx')}`;
|
||||
const disposition = response.headers.get('Content-Disposition');
|
||||
if (disposition && disposition.indexOf('filename=') !== -1) {
|
||||
const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
|
||||
if (matches != null && matches[1]) {
|
||||
filename = matches[1].replace(/['"]/g, '');
|
||||
}
|
||||
}
|
||||
|
||||
return response.blob().then(blob => ({ blob, filename }));
|
||||
})
|
||||
.then(({ blob, filename }) => {
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.style.display = 'none';
|
||||
a.href = blobUrl;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
a.remove();
|
||||
})
|
||||
.catch(err => {
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('opacity-75', 'cursor-not-allowed');
|
||||
btnText.textContent = 'Mulai Konversi & Unduh';
|
||||
showConverterError(err.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
@endsection
|
||||
|
||||
@@ -219,6 +219,8 @@ Route::middleware('auth')->group(function () {
|
||||
Route::get('/backups', [BackupController::class, 'index'])->name('backups.index');
|
||||
Route::post('/backups', [BackupController::class, 'store'])->name('backups.store');
|
||||
Route::post('/backups/restore-file', [BackupController::class, 'restoreFromFile'])->name('backups.restore_file')->middleware('throttle:5,1');
|
||||
Route::post('/backups/converter/inspect', [BackupController::class, 'converterInspect'])->name('backups.converter.inspect');
|
||||
Route::post('/backups/converter/execute', [BackupController::class, 'converterExecute'])->name('backups.converter.execute');
|
||||
Route::get('/backups/{filename}/download', [BackupController::class, 'download'])->name('backups.download');
|
||||
Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload');
|
||||
Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore')->middleware('throttle:5,1');
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
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 BackupConverterTest 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_conv_test',
|
||||
'role' => 'super_admin',
|
||||
'password' => bcrypt('password123'),
|
||||
]);
|
||||
$this->superAdmin->assignRole($role);
|
||||
|
||||
$this->backupService = new DatabaseBackupService();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$dir = $this->backupService->getBackupDirectory();
|
||||
if (File::isDirectory($dir)) {
|
||||
foreach (File::files($dir) as $f) {
|
||||
if (str_starts_with($f->getFilename(), 'test_conv_')) {
|
||||
@unlink($f->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
protected function createSampleKmhFile(string $name = 'test_conv_sample.kmh'): UploadedFile
|
||||
{
|
||||
$filename = $this->backupService->createKmhBackup(['users', 'roles'], false, $name);
|
||||
$fullPath = $this->backupService->getBackupDirectory() . DIRECTORY_SEPARATOR . $filename;
|
||||
$content = file_get_contents($fullPath);
|
||||
@unlink($fullPath);
|
||||
|
||||
return UploadedFile::fake()->createWithContent($name, $content);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_inspect_uploaded_kmh_backup(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_inspect.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertJson([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'filename' => 'test_conv_inspect.kmh',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertContains('users', $response->json('data.tables'));
|
||||
$this->assertContains('roles', $response->json('data.tables'));
|
||||
}
|
||||
|
||||
public function test_inspect_rejects_non_kmh_file(): void
|
||||
{
|
||||
$fakeFile = UploadedFile::fake()->create('document.pdf', 100);
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'backup_file' => $fakeFile,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJson([
|
||||
'success' => false,
|
||||
'message' => 'Berkas yang dipilih harus berekstensi .kmh.',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_inspect_rejects_corrupted_kmh_content(): void
|
||||
{
|
||||
$corruptFile = UploadedFile::fake()->createWithContent('corrupted.kmh', "KMH_ENCRYPTED_BACKUP_V1\nCorruptedHMACandPayload12345");
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.inspect'), [
|
||||
'backup_file' => $corruptFile,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422);
|
||||
$response->assertJson([
|
||||
'success' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_convert_single_table_to_xlsx(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_single.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users'],
|
||||
'format' => 'xlsx',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
$disposition = $response->headers->get('Content-Disposition');
|
||||
$this->assertStringContainsString('Tabel_users_', $disposition);
|
||||
$this->assertStringEndsWith('.xlsx', $disposition);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_convert_multiple_tables_to_xlsx_zip(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_multi_xlsx.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users', 'roles'],
|
||||
'format' => 'xlsx',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertHeader('Content-Type', 'application/zip');
|
||||
$disposition = $response->headers->get('Content-Disposition');
|
||||
$this->assertStringContainsString('Arsip_KMH_Excel_', $disposition);
|
||||
$this->assertStringEndsWith('.zip', $disposition);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_convert_tables_to_csv_zip(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_csv.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users', 'roles'],
|
||||
'format' => 'csv',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertHeader('Content-Type', 'application/zip');
|
||||
$disposition = $response->headers->get('Content-Disposition');
|
||||
$this->assertStringContainsString('Arsip_KMH_CSV_', $disposition);
|
||||
$this->assertStringEndsWith('.zip', $disposition);
|
||||
}
|
||||
|
||||
public function test_super_admin_can_convert_tables_to_sql(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_sql.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users'],
|
||||
'format' => 'sql',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertHeader('Content-Type', 'application/sql');
|
||||
$disposition = $response->headers->get('Content-Disposition');
|
||||
$this->assertStringContainsString('Arsip_KMH_SQL_', $disposition);
|
||||
$this->assertStringEndsWith('.sql', $disposition);
|
||||
}
|
||||
|
||||
public function test_convert_validates_required_fields(): void
|
||||
{
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_val.kmh');
|
||||
|
||||
// Tanpa tabel
|
||||
$response1 = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => [],
|
||||
'format' => 'xlsx',
|
||||
]);
|
||||
$response1->assertStatus(422);
|
||||
|
||||
// Format tidak valid
|
||||
$response2 = $this->actingAs($this->superAdmin)
|
||||
->postJson(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users'],
|
||||
'format' => 'invalid_format',
|
||||
]);
|
||||
$response2->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_active_database_remains_unaffected_after_conversion(): void
|
||||
{
|
||||
$initialUserCount = User::count();
|
||||
$this->assertGreaterThan(0, $initialUserCount);
|
||||
|
||||
$uploadedFile = $this->createSampleKmhFile('test_conv_safety.kmh');
|
||||
|
||||
$response = $this->actingAs($this->superAdmin)
|
||||
->post(route('admin.backups.converter.execute'), [
|
||||
'backup_file' => $uploadedFile,
|
||||
'tables' => ['users'],
|
||||
'format' => 'xlsx',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// Pastikan jumlah user di database aktif tetap sama persis
|
||||
$this->assertEquals($initialUserCount, User::count());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user