« Back to History
import.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php /** * Mister Manager Cloud ERP - Super Admin Panel * Data Import (Schema Structure + Data Content) from Master Template to Company Tenant Database * File: /admin/master_database/import.php */ require_once __DIR__ . '/../includes/bootstrap.php'; global $pdo; // --- AJAX INTERCEPTOR FOR COOL REAL-TIME PROCESSING --- if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'run_migration') { header('Content-Type: application/json'); $selected_company_id = intval($_POST['company_id'] ?? 0); $selected_master_id = intval($_POST['master_id'] ?? 0); $confirm_replace = ($_POST['confirm_replace'] ?? '') === '1'; if (!$selected_company_id || !$selected_master_id || !$confirm_replace) { echo json_encode(['success' => false, 'error' => 'Validation failure. Check parameters.']); exit; } $source_pdo = null; $target_pdo = null; $logs = []; try { // 1. Read Master Database Credentials $stmt = $pdo->prepare("SELECT * FROM master_database_master WHERE id = ? AND is_active = 1 LIMIT 1"); $stmt->execute([$selected_master_id]); $master_db = $stmt->fetch(PDO::FETCH_ASSOC); if (!$master_db) throw new Exception("Selected Master Database is either invalid or inactive."); // 2. Read Company Database Credentials $stmt = $pdo->prepare("SELECT * FROM company_master WHERE id = ? AND status = 'Active' LIMIT 1"); $stmt->execute([$selected_company_id]); $company_db = $stmt->fetch(PDO::FETCH_ASSOC); if (!$company_db) throw new Exception("Selected Company Database is either invalid or inactive."); // 3. Connect Source (Master) Database $source_port = !empty($master_db['db_port']) ? $master_db['db_port'] : '3306'; $source_dsn = "mysql:host={$master_db['db_host']};port={$source_port};dbname={$master_db['db_name']};charset=utf8mb4"; $source_pdo = new PDO($source_dsn, $master_db['db_user'], $master_db['db_pass'], [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_TIMEOUT => 10 ]); // 4. Connect Target (Company) Database $target_port = '3306'; if (strpos($company_db['db_host'], ':') !== false) { list($target_host_clean, $target_port) = explode(':', $company_db['db_host']); } else { $target_host_clean = $company_db['db_host']; } $target_dsn = "mysql:host={$target_host_clean};port={$target_port};dbname={$company_db['db_name']};charset=utf8mb4"; $target_pdo = new PDO($target_dsn, $company_db['db_user'], $company_db['db_pass'], [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_TIMEOUT => 10 ]); // 5. Disable Foreign Key Checks globally for session $target_pdo->exec("SET FOREIGN_KEY_CHECKS = 0"); // 6. Discover all tables $table_query = $source_pdo->query("SHOW TABLES"); $tables = $table_query->fetchAll(PDO::FETCH_COLUMN); if (empty($tables)) throw new Exception("No tables discovered within the Master template database."); $skipped_tables = ['companies', 'users']; // Loop through tables to migrate foreach ($tables as $table) { if (in_array(strtolower($table), $skipped_tables)) { $logs[] = "ℹ Skipping protected infrastructure table: " . htmlspecialchars($table); continue; } // Fetch structural create DDL $create_stmt = $source_pdo->prepare("SHOW CREATE TABLE `" . $table . "`"); $create_stmt->execute(); $create_row = $create_stmt->fetch(); $create_sql = $create_row['Create Table'] ?? ''; if (empty($create_sql)) throw new Exception("Could not retrieve definition for " . $table); // Strip Foreign Key constraints to bypass structural mismatches $create_sql = preg_replace('/,\s*CONSTRAINT\s+`[^`]+`\s+FOREIGN\s+KEY\s*\([^)]+\)\s+REFERENCES\s+`[^`]+`\s*\([^)]+\)[^,\n]*/i', '', $create_sql); $create_sql = preg_replace('/,\s*FOREIGN\s+KEY\s*\([^)]+\)\s+REFERENCES\s+`[^`]+`\s*\([^)]+\)[^,\n]*/i', '', $create_sql); // Re-create Table Template Fresh $target_pdo->exec("DROP TABLE IF EXISTS `" . $table . "`"); $target_pdo->exec($create_sql); // Pushing content payload rows $src_stmt = $source_pdo->query("SELECT * FROM `" . $table . "`"); $rows = $src_stmt->fetchAll(); if (!empty($rows)) { $columns = array_keys($rows[0]); $company_id_column = null; foreach ($columns as $col) { $lowered_col = strtolower($col); if ($lowered_col === 'company_id' || $lowered_col === 'cid') { $company_id_column = $col; break; } } $col_list = implode(', ', array_map(function($c) { return "`$c`"; }, $columns)); $param_list = implode(', ', array_fill(0, count($columns), '?')); $insert_sql = "INSERT IGNORE INTO `" . $table . "` ($col_list) VALUES ($param_list)"; $ins_stmt = $target_pdo->prepare($insert_sql); $imported_count = 0; foreach ($rows as $row) { if ($company_id_column !== null) { $row[$company_id_column] = $selected_company_id; } $ins_stmt->execute(array_values($row)); if ($ins_stmt->rowCount() > 0) $imported_count++; } $logs[] = "✔ " . htmlspecialchars($table) . " Cloned successfully (Processed: " . $imported_count . " rows)."; } else { $logs[] = "ℹ " . htmlspecialchars($table) . " Created empty (No reference rows found)."; } } // Re-enable validation engine context $target_pdo->exec("SET FOREIGN_KEY_CHECKS = 1"); echo json_encode(['success' => true, 'logs' => $logs, 'message' => 'Master Database Initialization Completed successfully.']); } catch (Exception $e) { if ($target_pdo) { try { $target_pdo->exec("SET FOREIGN_KEY_CHECKS = 1"); } catch(Exception $ex){} } echo json_encode(['success' => false, 'error' => $e->getMessage(), 'logs' => $logs]); } exit; } // Fetch lists for HTML UI elements try { $stmt = $pdo->query("SELECT id, company_name, db_name FROM company_master WHERE status = 'Active' ORDER BY company_name ASC"); $companies = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { $companies = []; } try { $stmt = $pdo->query("SELECT id, master_name, db_name FROM master_database_master WHERE is_active = 1 ORDER BY master_name ASC"); $masters = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { $masters = []; } require_once __DIR__ . '/../includes/header.php'; require_once __DIR__ . '/../includes/sidebar.php'; ?> <div class="content-wrapper p-3"> <div class="container-fluid"> <!-- Header Section --> <div class="row mb-3"> <div class="col-12 d-flex justify-content-between align-items-center"> <div> <h5 class="mb-0 text-dark font-weight-bold">Tenant Data & Schema Initialization</h5> <span class="text-muted small">Clones tables, structures, indexes, and configuration data from master template</span> </div> </div> </div> <!-- Dynamic UI Alert Banner Elements --> <div id="alertWrapper"></div> <!-- Live Loader Progress Core Display Area (Cool Animations) --> <div id="progressContainer" class="d-none mb-3"> <div class="card border-0 shadow-sm p-3 bg-white"> <div class="d-flex justify-content-between align-items-center mb-1"> <span class="small font-weight-bold text-primary" id="progressStatusLabel"> <i class="fa fa-spinner fa-spin me-2"></i>Initializing Core Migration Pipeline... </span> <span class="badge bg-primary font-monospace" id="progressPercentage">0%</span> </div> <div class="progress" style="height: 12px; border-radius: 6px;"> <div id="migrationProgressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-gradient" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> </div> <div class="row g-3"> <!-- Configuration Setup Form Control Area --> <div class="col-lg-5"> <div class="card shadow-sm border-0 h-100"> <div class="card-header bg-white border-bottom py-2"> <span class="text-secondary small font-weight-bold">Import Configuration Controls</span> </div> <div class="card-body p-3"> <!-- Form method setup to block default native action routing --> <form id="migrationForm" onsubmit="return false;"> <div class="mb-3"> <label class="form-label small mb-1 font-weight-bold">Select Source Master Database <span class="text-danger">*</span></label> <select name="master_id" id="master_id" class="form-select form-select-sm" required> <option value="">-- Choose Master Reference Template --</option> <?php foreach ($masters as $m): ?> <option value="<?php echo $m['id']; ?>"> <?php echo htmlspecialchars($m['master_name'] . " (" . $m['db_name'] . ")"); ?> </option> <?php endforeach; ?> </select> </div> <div class="mb-3"> <label class="form-label small mb-1 font-weight-bold">Select Destination Target Company <span class="text-danger">*</span></label> <select name="company_id" id="company_id" class="form-select form-select-sm" required> <option value="">-- Choose Target Company Database --</option> <?php foreach ($companies as $c): ?> <option value="<?php echo $c['id']; ?>"> <?php echo htmlspecialchars($c['company_name'] . " (" . $c['db_name'] . ")"); ?> </option> <?php endforeach; ?> </select> </div> <div class="alert alert-warning border p-2 small mb-3"> <i class="fa fa-exclamation-circle text-warning me-1"></i> <strong>Warning:</strong> Protected tables like `companies` and `users` will be automatically skipped to safeguard deployment access keys. </div> <div class="form-check mb-4"> <input class="form-check-input" type="checkbox" name="confirm_replace" value="1" id="confirmReplaceCheck" required> <label class="form-check-input-label small text-dark user-select-none font-weight-bold" for="confirmReplaceCheck"> I understand that schema structures and core data sets will be newly initialized. </label> </div> <div class="border-top pt-2"> <button type="button" id="submitBtn" class="btn btn-sm btn-danger w-100"> <i class="fa fa-database me-1"></i> Clone Schema & Import Master Data </button> </div> </form> </div> </div> </div> <!-- Terminal Activity shell graphics console box --> <div class="col-lg-7"> <div class="card shadow-sm border-0 h-100 bg-light"> <div class="card-header bg-white border-bottom py-2 d-flex justify-content-between align-items-center"> <span class="text-secondary small font-weight-bold">Live Schema Clone & Progress Terminal Log</span> <span class="badge bg-dark font-monospace text-uppercase p-1" style="font-size:0.65rem;">Engine Shell v3.0</span> </div> <div class="card-body p-3 font-monospace small text-dark border-0" id="terminalBody" style="max-height: 480px; overflow-y: auto; background-color: #f8f9fa;"> <div id="idleStateText" class="text-muted text-center py-5"> <i class="fa fa-terminal d-block mb-2 fa-2x text-black-50"></i> System idle. Awaiting configuration targets... </div> <div id="liveTerminalContainer" class="bg-white border rounded p-2 d-none shadow-inner text-start font-monospace lh-lg" style="font-size: 0.8rem; border-left: 4px solid #0dcaf0 !important;"> <!-- AJAX injection target nodes --> </div> </div> </div> </div> </div> </div> </div> <!-- Smart Script Integration Logic --> <script> document.addEventListener('DOMContentLoaded', function() { const form = document.getElementById('migrationForm'); const submitBtn = document.getElementById('submitBtn'); // UI Display Elements const progressContainer = document.getElementById('progressContainer'); const progressBar = document.getElementById('migrationProgressBar'); const progressStatusLabel = document.getElementById('progressStatusLabel'); const progressPercentage = document.getElementById('progressPercentage'); const idleStateText = document.getElementById('idleStateText'); const liveTerminalContainer = document.getElementById('liveTerminalContainer'); const alertWrapper = document.getElementById('alertWrapper'); // Attach click directly to override native engine layout submissions submitBtn.addEventListener('click', function(e) { e.preventDefault(); // Form validations if (!form.checkValidity()) { form.reportValidity(); return false; } if(!confirm('Critical Synchronization Process: Double check target properties before confirmation. Proceed?')) { return false; } // Lock form execution state submitBtn.disabled = true; alertWrapper.innerHTML = ''; // Show terminal elements idleStateText.classList.add('d-none'); liveTerminalContainer.classList.remove('d-none'); liveTerminalContainer.innerHTML = '<div class="text-info font-weight-bold"><i class="fa fa-refresh fa-spin me-2"></i>Spawning isolated thread orchestrator...</div>'; // Trigger Progress Bar Graphical HUD progressContainer.classList.remove('d-none'); updateProgressBarState(15, 'Establishing handshake configurations...'); const formData = new FormData(form); // Simulated steps framework to animate progress fluidly during single-hit migration context let currentProgress = 15; let progressTimer = setInterval(() => { if (currentProgress < 90) { currentProgress += Math.floor(Math.random() * 5) + 1; if(currentProgress > 90) currentProgress = 90; updateProgressBarState(currentProgress, 'Synchronizing entities structure definitions and rows arrays...'); } }, 500); // Native Fetch Request payload delivery mechanism fetch('import.php?action=run_migration', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { clearInterval(progressTimer); if (data.success) { updateProgressBarState(100, 'Migration completed successfully!'); progressBar.classList.remove('progress-bar-animated', 'progress-bar-striped'); progressBar.classList.add('bg-success'); // Clear out structural layout array dumps to live shell console let logHtml = ''; if(data.logs && data.logs.length > 0) { data.logs.forEach(log => { logHtml += `<div class="border-bottom border-light py-1 font-monospace text-success"><i class="fa fa-check-circle me-2 small"></i>${log}</div>`; }); } logHtml += `<div class="py-1 font-weight-bold text-dark"><i class="fa fa-terminal me-2"></i>[Engine Shell] Pipeline process terminated clean.</div>`; liveTerminalContainer.innerHTML = logHtml; alertWrapper.innerHTML = ` <div class="alert alert-success alert-dismissible fade show p-2 small" role="alert"> <i class="fa fa-check-circle me-1"></i> ${data.message} <button type="button" class="btn-close p-2" data-bs-dismiss="alert" aria-label="Close"></button> </div>`; } else { handleFailureState(progressTimer, data.error, data.logs); } }) .catch(err => { handleFailureState(progressTimer, 'Network connection timed out or runtime panic occurred.'); }) .finally(() => { submitBtn.disabled = false; }); }); function updateProgressBarState(percent, statusText) { progressBar.style.width = percent + '%'; progressBar.setAttribute('aria-valuenow', percent); progressPercentage.innerText = percent + '%'; progressStatusLabel.innerHTML = `<i class="fa fa-spinner fa-spin me-2"></i>${statusText}`; } function handleFailureState(timer, errorMessage, partialLogs = []) { if(timer) clearInterval(timer); updateProgressBarState(100, 'Pipeline engine execution aborted.'); progressBar.classList.remove('bg-primary', 'progress-bar-animated'); progressBar.classList.add('bg-danger'); progressBar.style.width = '100%'; progressPercentage.innerText = 'FAIL'; let logHtml = ''; if(partialLogs && partialLogs.length > 0) { partialLogs.forEach(log => { logHtml += `<div class="border-bottom border-light py-1 text-muted"><i class="fa fa-angle-right me-2"></i>${log}</div>`; }); } logHtml += `<div class="py-1 text-danger font-weight-bold"><i class="fa fa-times-circle me-2"></i>FATAL CRASH: ${errorMessage}</div>`; liveTerminalContainer.innerHTML = logHtml; alertWrapper.innerHTML = ` <div class="alert alert-danger alert-dismissible fade show p-2 small" role="alert"> <strong><i class="fa fa-exclamation-triangle me-1"></i> Operations Interrupted:</strong> ${errorMessage} <button type="button" class="btn-close p-2" data-bs-dismiss="alert" aria-label="Close"></button> </div>`; } }); </script> <?php require_once __DIR__ . '/../includes/footer.php'; ?>