a2host/public/js/app.js

4166 lines
156 KiB
JavaScript

/**
* a2host - Main Application Controller (ES Module)
* Coordina la SPA sin frameworks pesados, con soporte reactivo, accesibilidad WCAG y manejo atómico de errores.
*/
import api, { ApiError } from './api.js';
import store from './state.js';
import toast from './toast.js';
import {
validateSubdomainName,
validatePort,
validateUsername,
validatePassword,
RESERVED_PORTS_MAP
} from './validators.js';
import { renderMarkdown } from './markdown.js';
// Constante de dominio base
const BASE_DOMAIN = 'elingejose.com';
// Inicialización cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', () => {
initApp();
});
async function initApp() {
// 1. Verificar Autenticación
try {
const user = await api.getMe();
if (!user || !user.id) {
window.location.href = '/login.html';
return;
}
store.setState({ currentUser: user });
setupUserProfileUI(user);
} catch (err) {
window.location.href = '/login.html';
return;
}
// 1b. Cargar Identidad y Tema Temprano
await loadIdentityAndThemes();
// 2. Configurar Navegación por Pestañas
setupTabs();
// 3. Inicializar Telemetría con Polling cada 6 segundos
fetchTelemetry();
setInterval(fetchTelemetry, 6000);
// 4. Configurar Buscadores y Filtros
setupFiltersAndSearch();
// 5. Configurar Modales y Controladores de Módulos
setupModals();
setupProjects();
setupFtp();
setupFileManager();
setupCodeEditor();
setupTerminal();
setupMonitor();
setupSettings();
// 6. Cargar datos iniciales
loadSubdomains();
loadProjects();
loadFolders();
loadDocs();
// 7. Configurar Botón de Logout
const btnLogout = document.getElementById('btn-logout');
if (btnLogout) {
btnLogout.addEventListener('click', handleLogout);
}
// Escuchar tecla Escape para cerrar modales
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeAllModals();
}
});
}
/* ==========================================================================
Perfil de Usuario y Telemetría
========================================================================== */
function setupUserProfileUI(user) {
const userNameEl = document.getElementById('user-full-name');
const userRoleEl = document.getElementById('user-role-badge');
if (userNameEl) {
userNameEl.textContent = user.fullName || user.username;
}
if (userRoleEl) {
userRoleEl.textContent = user.role;
userRoleEl.className = `user-role-tag role-${user.role}`;
}
// Si no es admin, ocultar botón de crear usuario o ajustar vista
if (user.role !== 'admin') {
const btnNewUser = document.getElementById('btn-open-create-user');
if (btnNewUser) btnNewUser.style.display = 'none';
}
}
async function fetchTelemetry() {
try {
const stats = await api.getSystemStats();
store.setState({ stats });
updateTelemetryUI(stats);
} catch (err) {
console.warn('[Telemetry] No se pudo obtener métricas:', err.message);
}
}
function updateTelemetryUI(stats) {
if (!stats) return;
// 1. Memoria PM2 contra límite estricto de 120MB
const rssBytes = stats.memory?.processRssBytes || 0;
const pm2LimitBytes = 120 * 1024 * 1024; // 120 MB
const percent = Math.min(100, Math.round((rssBytes / pm2LimitBytes) * 100));
const ramFill = document.getElementById('ram-bar-fill');
const ramText = document.getElementById('ram-usage-text');
if (ramFill) {
ramFill.style.width = `${percent}%`;
ramFill.classList.remove('ram-warning', 'ram-danger');
if (percent > 85) {
ramFill.classList.add('ram-danger');
} else if (percent > 65) {
ramFill.classList.add('ram-warning');
}
}
if (ramText) {
const formatted = stats.memory?.processRssFormatted || `${(rssBytes / (1024 * 1024)).toFixed(1)} MB`;
ramText.textContent = `${formatted} / 120 MB`;
}
// 2. Estado de Apache
const apacheDot = document.getElementById('apache-status-dot');
const apacheText = document.getElementById('apache-status-text');
if (apacheDot && apacheText) {
apacheDot.className = 'status-pulsing-dot';
if (stats.apache?.mockMode) {
apacheDot.classList.add('mock');
apacheText.textContent = 'Apache (Mock)';
apacheText.title = 'Modo desarrollo simulado activo';
} else if (stats.apache?.active) {
apacheText.textContent = 'Apache2 Activo';
apacheText.title = 'Servidor Apache2 operando en VPS';
} else {
apacheDot.classList.add('offline');
apacheText.textContent = 'Apache2 Inactivo';
}
}
// 3. Sistema y Uptime
const sysText = document.getElementById('system-uptime-text');
if (sysText && stats.server) {
sysText.textContent = `${stats.server.hostname} • ${stats.server.uptimeFormatted || 'Activo'}`;
}
}
async function handleLogout() {
try {
await api.logout();
toast.info('Sesión Finalizada', 'Hasta pronto');
setTimeout(() => {
window.location.href = '/login.html';
}, 400);
} catch (err) {
window.location.href = '/login.html';
}
}
/* ==========================================================================
Navegación por Pestañas (Tabs)
========================================================================== */
function setupTabs() {
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanels = document.querySelectorAll('.tab-panel');
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
const targetTab = btn.getAttribute('data-tab');
switchTab(targetTab);
});
});
store.subscribe('activeTab', (state) => {
const active = state.activeTab;
tabButtons.forEach(b => {
const isActive = b.getAttribute('data-tab') === active;
b.classList.toggle('active', isActive);
b.setAttribute('aria-selected', isActive ? 'true' : 'false');
});
tabPanels.forEach(p => {
p.classList.toggle('active', p.id === `tab-panel-${active}`);
});
});
}
function switchTab(tabName) {
store.setState({ activeTab: tabName });
if (tabName !== 'monitor') {
stopMonitorAutoRefresh();
}
if (tabName === 'subdomains') loadSubdomains();
if (tabName === 'projects') loadProjects();
if (tabName === 'folders') loadFolders();
if (tabName === 'ftp') loadFtpData();
if (tabName === 'terminal') initTerminalTab();
if (tabName === 'monitor') initMonitorTab();
if (tabName === 'docs') loadDocs();
if (tabName === 'settings') loadSettingsTab();
}
/* ==========================================================================
Pestaña 1: Subdominios
========================================================================== */
async function loadSubdomains() {
const tableBody = document.getElementById('subdomains-table-body');
const mobileContainer = document.getElementById('subdomains-mobile-list');
const badgeCount = document.getElementById('subdomains-count-badge');
store.setState({ subdomainsLoading: true });
try {
const list = await api.getSubdomains();
store.setState({ subdomains: list, subdomainsLoading: false });
if (badgeCount) badgeCount.textContent = list.length;
renderSubdomains();
} catch (err) {
store.setState({ subdomainsLoading: false });
toast.error('Error al cargar subdominios', err.message);
}
}
function renderSubdomains() {
const subdomains = store.getState('subdomains') || [];
const filter = store.getState('subdomainsFilter') || {};
const tableBody = document.getElementById('subdomains-table-body');
const mobileContainer = document.getElementById('subdomains-mobile-list');
const emptyState = document.getElementById('subdomains-empty-state');
// Filtrado reactivo
const filtered = subdomains.filter(item => {
// Búsqueda por texto
if (filter.search) {
const q = filter.search.toLowerCase();
const matchName = item.name.toLowerCase().includes(q);
const matchDomain = (item.fullDomain || '').toLowerCase().includes(q);
const matchTarget = (item.target || '').toLowerCase().includes(q);
if (!matchName && !matchDomain && !matchTarget) return false;
}
// Filtro por modo
if (filter.mode && filter.mode !== 'all') {
if (item.type !== filter.mode) return false;
}
// Filtro por estado
if (filter.status && filter.status !== 'all') {
const isEnabled = filter.status === 'enabled';
if (item.enabled !== isEnabled) return false;
}
return true;
});
if (filtered.length === 0) {
if (tableBody) tableBody.innerHTML = '';
if (mobileContainer) mobileContainer.innerHTML = '';
if (emptyState) emptyState.style.display = 'flex';
return;
}
if (emptyState) emptyState.style.display = 'none';
// Renderizar Tabla Desktop
if (tableBody) {
tableBody.innerHTML = filtered.map(item => `
<tr>
<td>
<a href="https://${item.fullDomain || `${item.name}.${BASE_DOMAIN}`}" target="_blank" rel="noopener noreferrer" class="subdomain-link">
<span>${escapeHtml(item.name)}</span>
<svg class="external-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4h-4m4 0v4m0-4L7 9m-1-4H3a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1v-3"></path>
</svg>
</a>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(item.fullDomain || `${item.name}.${BASE_DOMAIN}`)}</div>
</td>
<td>
${item.type === 'proxy'
? `<span class="badge badge-mode-proxy">Modo B • Proxy</span>`
: `<span class="badge badge-mode-static">Modo A • Estático</span>`
}
</td>
<td>
${item.type === 'proxy'
? `<span class="badge-port">:${item.port || '—'}</span> <span style="font-size: 0.78rem; color: var(--text-muted);">${escapeHtml(item.target || '')}</span>`
: `<span style="font-size: 0.8rem; color: var(--text-secondary); font-family: ui-monospace, monospace;">${escapeHtml(item.target || `/var/www/${item.name}`)}</span>`
}
</td>
<td>
<label class="switch-label">
<input
type="checkbox"
class="switch-input subdomain-toggle-switch"
data-name="${escapeHtml(item.name)}"
${item.enabled ? 'checked' : ''}
${item.protected ? 'disabled' : ''}
aria-label="Alternar estado de ${escapeHtml(item.name)}"
>
<span class="switch-slider"></span>
<span style="font-size: 0.75rem; color: ${item.enabled ? 'var(--accent-lime)' : 'var(--text-muted)'};">
${item.enabled ? 'Activo' : 'Pausado'}
</span>
</label>
</td>
<td>
${item.protected
? `<span class="badge badge-protected" title="Archivo de configuración protegido del sistema">Protegido</span>`
: `<span class="badge badge-status-active">Normal</span>`
}
</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.4rem;">
<button
type="button"
class="btn-icon btn-edit-subdomain"
data-name="${escapeHtml(item.name)}"
${item.protected ? 'disabled title="Sitio protegido no editable"' : 'title="Editar subdominio"'}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path>
</svg>
</button>
<button
type="button"
class="btn-icon btn-icon-danger btn-delete-subdomain"
data-name="${escapeHtml(item.name)}"
data-domain="${escapeHtml(item.fullDomain || item.name)}"
data-type="${item.type}"
${item.protected ? 'disabled title="Sitio protegido no eliminable"' : 'title="Eliminar subdominio"'}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</div>
</td>
</tr>
`).join('');
}
// Renderizar Tarjetas Mobile
if (mobileContainer) {
mobileContainer.innerHTML = filtered.map(item => `
<div class="mobile-card">
<div class="mobile-card-header">
<a href="https://${item.fullDomain || `${item.name}.${BASE_DOMAIN}`}" target="_blank" rel="noopener noreferrer" class="subdomain-link">
<span>${escapeHtml(item.name)}</span>
<svg class="external-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4h-4m4 0v4m0-4L7 9m-1-4H3a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1v-3"></path>
</svg>
</a>
<label class="switch-label">
<input
type="checkbox"
class="switch-input subdomain-toggle-switch"
data-name="${escapeHtml(item.name)}"
${item.enabled ? 'checked' : ''}
${item.protected ? 'disabled' : ''}
aria-label="Alternar estado de ${escapeHtml(item.name)}"
>
<span class="switch-slider"></span>
</label>
</div>
<div class="mobile-card-body">
<div class="mobile-card-row">
<span>Tipo / Modo:</span>
${item.type === 'proxy'
? `<span class="badge badge-mode-proxy">Modo B • Proxy :${item.port}</span>`
: `<span class="badge badge-mode-static">Modo A • Estático</span>`
}
</div>
<div class="mobile-card-row">
<span>Destino:</span>
<span style="font-family: ui-monospace, monospace; font-size: 0.78rem;">${escapeHtml(item.target || '')}</span>
</div>
<div class="mobile-card-row">
<span>Seguridad:</span>
${item.protected
? `<span class="badge badge-protected">Protegido</span>`
: `<span class="badge badge-status-active">Normal</span>`
}
</div>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-edit-subdomain"
data-name="${escapeHtml(item.name)}"
style="min-height: 38px; padding: 0.4rem 0.85rem;"
${item.protected ? 'disabled' : ''}
>
Editar
</button>
<button
type="button"
class="btn btn-danger btn-delete-subdomain"
data-name="${escapeHtml(item.name)}"
data-domain="${escapeHtml(item.fullDomain || item.name)}"
data-type="${item.type}"
style="min-height: 38px; padding: 0.4rem 0.85rem;"
${item.protected ? 'disabled' : ''}
>
Eliminar
</button>
</div>
</div>
`).join('');
}
// Vincular eventos a los nuevos elementos generados
attachSubdomainRowEvents();
}
function attachSubdomainRowEvents() {
// Switches de estado
document.querySelectorAll('.subdomain-toggle-switch').forEach(sw => {
sw.addEventListener('change', async (e) => {
const name = sw.getAttribute('data-name');
const targetState = sw.checked;
sw.disabled = true;
try {
const res = await api.toggleSubdomain(name, targetState);
toast.success(
`Subdominio ${targetState ? 'habilitado' : 'pausado'}`,
`'${name}' se encuentra ahora ${targetState ? 'activo' : 'inactivo'}.`
);
loadSubdomains();
} catch (err) {
// Revertir switch
sw.checked = !targetState;
toast.error('Error al alternar estado', err.detail || err.message);
} finally {
sw.disabled = false;
}
});
});
// Botones de editar
document.querySelectorAll('.btn-edit-subdomain').forEach(btn => {
btn.addEventListener('click', () => {
const name = btn.getAttribute('data-name');
openEditSubdomainModal(name);
});
});
// Botones de eliminar
document.querySelectorAll('.btn-delete-subdomain').forEach(btn => {
btn.addEventListener('click', () => {
const name = btn.getAttribute('data-name');
const domain = btn.getAttribute('data-domain');
const type = btn.getAttribute('data-type');
openDeleteSubdomainModal(name, domain, type);
});
});
}
function setupFiltersAndSearch() {
const inputSearch = document.getElementById('search-subdomains');
const selectMode = document.getElementById('filter-mode');
const selectStatus = document.getElementById('filter-status');
const btnRefresh = document.getElementById('btn-refresh-subdomains');
if (inputSearch) {
inputSearch.addEventListener('input', (e) => {
const filter = store.getState('subdomainsFilter');
store.setState({ subdomainsFilter: { ...filter, search: e.target.value.trim() } });
renderSubdomains();
});
}
if (selectMode) {
selectMode.addEventListener('change', (e) => {
const filter = store.getState('subdomainsFilter');
store.setState({ subdomainsFilter: { ...filter, mode: e.target.value } });
renderSubdomains();
});
}
if (selectStatus) {
selectStatus.addEventListener('change', (e) => {
const filter = store.getState('subdomainsFilter');
store.setState({ subdomainsFilter: { ...filter, status: e.target.value } });
renderSubdomains();
});
}
if (btnRefresh) {
btnRefresh.addEventListener('click', () => {
loadSubdomains();
toast.info('Actualizando subdominios', 'Consultando configuración de Apache...');
});
}
}
/* ==========================================================================
Modales: Crear / Editar Subdominio con Terminal de Rollback & Riesgo
========================================================================== */
let currentSubdomainModalMode = 'create'; // 'create' | 'edit'
let selectedSubdomainType = 'static'; // 'static' | 'proxy'
let currentEditingSubdomainName = '';
let currentRiskRequiresConfirmation = false;
function setupModals() {
// Botón abrir modal nuevo subdominio
const btnOpenCreate = document.getElementById('btn-open-create-subdomain');
if (btnOpenCreate) {
btnOpenCreate.addEventListener('click', () => {
openCreateSubdomainModal();
});
}
// Selector de Modo A vs Modo B
const modeBtnStatic = document.getElementById('mode-btn-static');
const modeBtnProxy = document.getElementById('mode-btn-proxy');
const proxyPortGroup = document.getElementById('form-group-port');
if (modeBtnStatic && modeBtnProxy) {
modeBtnStatic.addEventListener('click', () => {
selectedSubdomainType = 'static';
modeBtnStatic.classList.add('active');
modeBtnProxy.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'none';
validateSubdomainFormLive();
if (currentSubdomainModalMode === 'edit') {
evaluateSubdomainRisk(currentEditingSubdomainName);
}
});
modeBtnProxy.addEventListener('click', () => {
selectedSubdomainType = 'proxy';
modeBtnProxy.classList.add('active');
modeBtnStatic.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'flex';
validateSubdomainFormLive();
if (currentSubdomainModalMode === 'edit') {
evaluateSubdomainRisk(currentEditingSubdomainName);
}
});
}
// Validación en vivo del nombre y preview de URL
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
const chkConfirmRisk = document.getElementById('chk-confirm-subdomain-risk');
if (inputName) {
inputName.addEventListener('input', () => {
validateSubdomainFormLive();
});
}
if (inputPort) {
inputPort.addEventListener('input', () => {
validateSubdomainFormLive();
if (currentSubdomainModalMode === 'edit') {
evaluateSubdomainRisk(currentEditingSubdomainName);
}
});
}
if (chkConfirmRisk) {
chkConfirmRisk.addEventListener('change', () => {
validateSubdomainFormLive();
});
}
// Enviar Formulario Subdominio
const formSubdomain = document.getElementById('form-subdomain');
if (formSubdomain) {
formSubdomain.addEventListener('submit', handleSubdomainFormSubmit);
}
// Botón Copiar Stderr en Terminal Rollback
const btnCopyStderr = document.getElementById('btn-copy-terminal-stderr');
if (btnCopyStderr) {
btnCopyStderr.addEventListener('click', () => {
const text = document.getElementById('terminal-stderr-text')?.textContent || '';
navigator.clipboard.writeText(text).then(() => {
toast.info('Copiado al Portapapeles', 'Detalles de error copiados.');
});
});
}
// Botón Confirmar Eliminación
const btnConfirmDelete = document.getElementById('btn-confirm-delete-subdomain');
if (btnConfirmDelete) {
btnConfirmDelete.addEventListener('click', handleConfirmDeleteSubdomain);
}
// Botones de Cerrar Modales
document.querySelectorAll('.modal-close-btn, .btn-modal-cancel').forEach(btn => {
btn.addEventListener('click', closeAllModals);
});
}
function openCreateSubdomainModal() {
currentSubdomainModalMode = 'create';
selectedSubdomainType = 'static';
currentEditingSubdomainName = '';
currentRiskRequiresConfirmation = false;
const modal = document.getElementById('modal-subdomain');
const title = document.getElementById('modal-subdomain-title');
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
const proxyPortGroup = document.getElementById('form-group-port');
const btnStatic = document.getElementById('mode-btn-static');
const btnProxy = document.getElementById('mode-btn-proxy');
const terminal = document.getElementById('rollback-terminal');
const btnSubmit = document.getElementById('btn-submit-subdomain');
const riskContainer = document.getElementById('subdomain-risk-container');
const riskConfirmation = document.getElementById('subdomain-risk-confirmation');
const chkConfirm = document.getElementById('chk-confirm-subdomain-risk');
if (title) title.textContent = 'Crear Nuevo Subdominio';
if (btnSubmit) btnSubmit.textContent = 'Crear Subdominio';
if (inputName) {
inputName.value = '';
inputName.disabled = false;
}
if (inputPort) inputPort.value = '';
btnStatic?.classList.add('active');
btnProxy?.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'none';
if (riskContainer) riskContainer.style.display = 'none';
if (riskConfirmation) riskConfirmation.style.display = 'none';
if (chkConfirm) chkConfirm.checked = false;
// Ocultar terminal de rollback previo
if (terminal) terminal.classList.remove('active');
validateSubdomainFormLive();
openModal('modal-subdomain');
inputName?.focus();
}
async function openEditSubdomainModal(name) {
const subdomains = store.getState('subdomains') || [];
const item = subdomains.find(s => s.name === name);
if (!item) return;
currentSubdomainModalMode = 'edit';
currentEditingSubdomainName = name;
selectedSubdomainType = item.type || 'static';
currentRiskRequiresConfirmation = false;
const modal = document.getElementById('modal-subdomain');
const title = document.getElementById('modal-subdomain-title');
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
const proxyPortGroup = document.getElementById('form-group-port');
const btnStatic = document.getElementById('mode-btn-static');
const btnProxy = document.getElementById('mode-btn-proxy');
const terminal = document.getElementById('rollback-terminal');
const btnSubmit = document.getElementById('btn-submit-subdomain');
const riskContainer = document.getElementById('subdomain-risk-container');
const riskConfirmation = document.getElementById('subdomain-risk-confirmation');
const chkConfirm = document.getElementById('chk-confirm-subdomain-risk');
if (title) title.textContent = `Editar Subdominio: ${name}`;
if (btnSubmit) btnSubmit.textContent = 'Guardar Cambios';
if (inputName) {
inputName.value = name;
inputName.disabled = true; // El nombre en edición no se altera
}
if (item.type === 'proxy') {
btnProxy?.classList.add('active');
btnStatic?.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'flex';
if (inputPort) inputPort.value = item.port || '';
} else {
btnStatic?.classList.add('active');
btnProxy?.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'none';
if (inputPort) inputPort.value = '';
}
if (riskContainer) riskContainer.style.display = 'none';
if (riskConfirmation) riskConfirmation.style.display = 'none';
if (chkConfirm) chkConfirm.checked = false;
if (terminal) terminal.classList.remove('active');
validateSubdomainFormLive();
openModal('modal-subdomain');
// Evaluar riesgos en vivo
await evaluateSubdomainRisk(name);
}
let riskDebounceTimer = null;
async function evaluateSubdomainRisk(name) {
if (currentSubdomainModalMode !== 'edit' || !name) return;
clearTimeout(riskDebounceTimer);
riskDebounceTimer = setTimeout(async () => {
const inputPort = document.getElementById('subdomain-port-input');
const riskContainer = document.getElementById('subdomain-risk-container');
const riskList = document.getElementById('subdomain-risk-list');
const riskBadge = document.getElementById('subdomain-risk-level-badge');
const riskConfirmation = document.getElementById('subdomain-risk-confirmation');
const chkConfirm = document.getElementById('chk-confirm-subdomain-risk');
const portVal = selectedSubdomainType === 'proxy' && inputPort?.value ? Number(inputPort.value) : undefined;
try {
const response = await api.validateSubdomain(name, {
type: selectedSubdomainType,
port: portVal
});
const report = response?.data || response;
if (report && report.hasRisk && Array.isArray(report.risks) && report.risks.length > 0) {
currentRiskRequiresConfirmation = true;
if (riskContainer) riskContainer.style.display = 'flex';
if (riskConfirmation) riskConfirmation.style.display = 'flex';
const hasCritical = report.risks.some(r => r.level === 'critical');
const hasHigh = report.risks.some(r => r.level === 'high');
if (riskBadge) {
if (hasCritical) {
riskBadge.textContent = 'CRÍTICO';
riskBadge.style.background = '#ef4444';
} else if (hasHigh) {
riskBadge.textContent = 'ALTO RIESGO';
riskBadge.style.background = '#f97316';
} else {
riskBadge.textContent = 'ADVERTENCIA';
riskBadge.style.background = '#f59e0b';
}
}
if (riskList) {
riskList.innerHTML = report.risks.map(r => `
<div class="risk-alert-item ${r.level === 'warning' ? 'risk-warning' : ''}">
<strong>[${(r.level || 'aviso').toUpperCase()}]</strong> ${escapeHtml(r.message)}
</div>
`).join('');
}
} else {
currentRiskRequiresConfirmation = false;
if (riskContainer) riskContainer.style.display = 'none';
if (riskConfirmation) riskConfirmation.style.display = 'none';
if (chkConfirm) chkConfirm.checked = false;
}
} catch (err) {
console.warn('[RiskValidation] Error al validar riesgos:', err.message);
}
validateSubdomainFormLive();
}, 200);
}
function validateSubdomainFormLive() {
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
const nameFeedback = document.getElementById('subdomain-name-feedback');
const portFeedback = document.getElementById('subdomain-port-feedback');
const urlPreview = document.getElementById('preview-url-domain');
const btnSubmit = document.getElementById('btn-submit-subdomain');
const chkConfirm = document.getElementById('chk-confirm-subdomain-risk');
const rawName = inputName?.value || '';
const rawPort = inputPort?.value || '';
let isNameValid = false;
let isPortValid = true;
// 1. Validar Nombre
if (!rawName) {
if (nameFeedback) nameFeedback.textContent = '';
if (urlPreview) urlPreview.textContent = `subdominio.${BASE_DOMAIN}`;
inputName?.classList.remove('has-error');
} else {
const res = validateSubdomainName(rawName);
if (!res.valid) {
if (nameFeedback) nameFeedback.textContent = res.error;
inputName?.classList.add('has-error');
if (urlPreview) urlPreview.textContent = `${res.normalized || rawName}.${BASE_DOMAIN}`;
} else {
if (nameFeedback) nameFeedback.textContent = '';
inputName?.classList.remove('has-error');
if (urlPreview) urlPreview.textContent = `${res.normalized}.${BASE_DOMAIN}`;
isNameValid = true;
}
}
// 2. Validar Puerto si es Modo Proxy
if (selectedSubdomainType === 'proxy') {
const existing = store.getState('subdomains') || [];
const currentName = currentSubdomainModalMode === 'edit' ? rawName : '';
const portRes = validatePort(rawPort, existing, currentName);
if (!portRes.valid) {
isPortValid = false;
if (portFeedback) portFeedback.textContent = portRes.error;
inputPort?.classList.add('has-error');
} else {
isPortValid = true;
if (portFeedback) portFeedback.textContent = '';
inputPort?.classList.remove('has-error');
}
} else {
if (portFeedback) portFeedback.textContent = '';
inputPort?.classList.remove('has-error');
}
// 3. Validar Checkbox de Riesgo Obligatorio en Edición
let isRiskConfirmed = true;
if (currentSubdomainModalMode === 'edit' && currentRiskRequiresConfirmation) {
isRiskConfirmed = Boolean(chkConfirm && chkConfirm.checked);
}
const formValid = isNameValid && isPortValid && isRiskConfirmed;
if (btnSubmit) {
btnSubmit.disabled = !formValid;
}
return formValid;
}
async function handleSubdomainFormSubmit(e) {
e.preventDefault();
if (!validateSubdomainFormLive()) {
return;
}
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
const btnSubmit = document.getElementById('btn-submit-subdomain');
const terminal = document.getElementById('rollback-terminal');
const terminalText = document.getElementById('terminal-stderr-text');
const name = inputName.value.trim().toLowerCase();
const payload = {
name,
type: selectedSubdomainType,
...(selectedSubdomainType === 'proxy' ? { port: Number(inputPort.value) } : {})
};
btnSubmit.disabled = true;
btnSubmit.textContent = 'Aplicando en Apache2...';
if (terminal) terminal.classList.remove('active');
try {
if (currentSubdomainModalMode === 'create') {
const res = await api.createSubdomain(payload);
toast.success('Subdominio Aprovisionado', res.message || `Subdominio '${name}' creado exitosamente.`);
} else {
const res = await api.updateSubdomain(name, {
type: payload.type,
port: payload.port,
forceConfirmed: true
});
toast.success('Subdominio Actualizado', res.message || `Subdominio '${name}' reconfigurado.`);
}
closeAllModals();
loadSubdomains();
loadFolders(); // Si fue Modo A, refrescar carpetas
} catch (err) {
btnSubmit.disabled = false;
btnSubmit.textContent = currentSubdomainModalMode === 'create' ? 'Crear Subdominio' : 'Guardar Cambios';
// Manejo de Error 422 / Rollback Atómico de Apache
if (err.status === 422 || err.code === 'APACHE_CONFIGTEST_FAILED' || err.rollbackExecuted) {
if (terminal && terminalText) {
terminalText.textContent = err.detail || err.message || 'Error de sintaxis en archivo VirtualHost.';
terminal.classList.add('active');
terminal.scrollIntoView({ behavior: 'smooth' });
}
toast.error(
'Fallo en validación de Apache2 (Rollback Ejecutado)',
'Se restauró el estado previo para mantener el servidor web intacto.',
8000
);
} else {
toast.error('Error al guardar subdominio', err.detail || err.message);
}
}
}
let pendingDeleteSubdomain = null;
function openDeleteSubdomainModal(name, domain, type) {
pendingDeleteSubdomain = { name, domain, type };
const modal = document.getElementById('modal-delete-subdomain');
const targetText = document.getElementById('delete-subdomain-target-text');
const chkFiles = document.getElementById('chk-delete-files');
const filesContainer = document.getElementById('delete-files-checkbox-container');
if (targetText) {
targetText.textContent = `${name}.${BASE_DOMAIN}`;
}
// Mostrar checkbox de archivos solo si es Modo A o tiene carpeta
if (filesContainer) {
filesContainer.style.display = type === 'static' ? 'flex' : 'none';
}
if (chkFiles) {
chkFiles.checked = false;
}
openModal('modal-delete-subdomain');
}
async function handleConfirmDeleteSubdomain() {
if (!pendingDeleteSubdomain) return;
const btnConfirm = document.getElementById('btn-confirm-delete-subdomain');
const chkFiles = document.getElementById('chk-delete-files');
const deleteFiles = Boolean(chkFiles && chkFiles.checked);
btnConfirm.disabled = true;
btnConfirm.textContent = 'Eliminando...';
try {
const res = await api.deleteSubdomain(pendingDeleteSubdomain.name, deleteFiles);
toast.success('Subdominio Eliminado', res.message || 'Subdominio purgado exitosamente de Apache.');
closeAllModals();
loadSubdomains();
loadFolders();
} catch (err) {
btnConfirm.disabled = false;
btnConfirm.textContent = 'Confirmar Eliminación';
toast.error('Error al eliminar subdominio', err.detail || err.message);
}
}
/* ==========================================================================
Pestaña 2: Carpetas Web (/var/www)
========================================================================== */
async function loadFolders() {
const tableBody = document.getElementById('folders-table-body');
const mobileContainer = document.getElementById('folders-mobile-list');
const badgeCount = document.getElementById('folders-count-badge');
const btnRefresh = document.getElementById('btn-refresh-folders');
store.setState({ foldersLoading: true });
try {
const folders = await api.getFolders();
store.setState({ folders, foldersLoading: false });
if (badgeCount) badgeCount.textContent = folders.length;
renderFolders();
} catch (err) {
store.setState({ foldersLoading: false });
toast.error('Error al explorar /var/www', err.message);
}
}
function renderFolders() {
const folders = store.getState('folders') || [];
const tableBody = document.getElementById('folders-table-body');
const mobileContainer = document.getElementById('folders-mobile-list');
if (folders.length === 0) {
if (tableBody) tableBody.innerHTML = `<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">No se encontraron carpetas en /var/www</td></tr>`;
if (mobileContainer) mobileContainer.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem;">No se encontraron carpetas en /var/www</div>`;
return;
}
// Renderizar Desktop
if (tableBody) {
tableBody.innerHTML = folders.map(f => {
const isSGID = f.isSGID || f.permissions === '2775';
return `
<tr>
<td>
<div style="font-weight: 600; color: var(--text-primary);">${escapeHtml(f.folderName)}</div>
<div style="font-size: 0.74rem; color: var(--text-muted); font-family: ui-monospace, monospace;">${escapeHtml(f.path)}</div>
</td>
<td>${f.sizeFormatted || '—'}</td>
<td>${f.fileCount ?? 0} ficheros</td>
<td><code style="font-size: 0.78rem;">${escapeHtml(f.owner)}:${escapeHtml(f.group)}</code></td>
<td><code style="font-size: 0.78rem;">${escapeHtml(f.permissions)}</code></td>
<td>
${isSGID
? `<span class="badge badge-sgid-ok" title="Permisos óptimos de lectura y escritura">Acceso Web Óptimo</span>`
: `<span class="badge badge-sgid-warn" title="Permisos configurados">Lectura y Escritura (RW)</span>`
}
</td>
<td style="text-align: right;">
<button
type="button"
class="btn btn-secondary btn-inspect-folder"
data-name="${escapeHtml(f.folderName)}"
style="min-height: 34px; padding: 0.35rem 0.75rem; font-size: 0.8rem;"
>
Archivos
</button>
</td>
</tr>
`;
}).join('');
}
// Renderizar Mobile
if (mobileContainer) {
mobileContainer.innerHTML = folders.map(f => {
const isSGID = f.isSGID || f.permissions === '2775';
return `
<div class="mobile-card">
<div class="mobile-card-header">
<div>
<div style="font-weight: 600;">${escapeHtml(f.folderName)}</div>
<div style="font-size: 0.72rem; color: var(--text-muted);">${escapeHtml(f.path)}</div>
</div>
${isSGID
? `<span class="badge badge-sgid-ok">Acceso Web Óptimo</span>`
: `<span class="badge badge-sgid-warn">Lectura y Escritura (RW)</span>`
}
</div>
<div class="mobile-card-body">
<div class="mobile-card-row">
<span>Tamaño:</span>
<strong>${f.sizeFormatted || '—'}</strong>
</div>
<div class="mobile-card-row">
<span>Archivos:</span>
<span>${f.fileCount ?? 0} elementos</span>
</div>
<div class="mobile-card-row">
<span>Permisos:</span>
<code>${escapeHtml(f.owner)}:${escapeHtml(f.group)} (${f.permissions})</code>
</div>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-inspect-folder"
data-name="${escapeHtml(f.folderName)}"
style="width: 100%; min-height: 38px;"
>
Inspeccionar Archivos
</button>
</div>
</div>
`;
}).join('');
}
// Eventos de inspección de archivos -> Apertura de File Manager
document.querySelectorAll('.btn-inspect-folder').forEach(btn => {
btn.addEventListener('click', () => {
const folderName = btn.getAttribute('data-name');
openFileManager(folderName, '');
});
});
const btnRefresh = document.getElementById('btn-refresh-folders');
if (btnRefresh) {
btnRefresh.onclick = () => {
loadFolders();
toast.info('Actualizando carpetas', 'Escaneando /var/www...');
};
}
}
/* ==========================================================================
Gestor de Archivos (File Manager) para /var/www/<subdominio>
========================================================================== */
let fmCurrentFolder = '';
let fmCurrentPath = '';
let fmFiles = [];
let fmCreateType = 'file'; // 'file' | 'dir'
function setupFileManager() {
const btnUpload = document.getElementById('fm-btn-upload');
const fileInput = document.getElementById('fm-file-input');
const btnNewFile = document.getElementById('fm-btn-new-file');
const btnNewFolder = document.getElementById('fm-btn-new-folder');
const btnUpDir = document.getElementById('fm-btn-up-dir');
const btnRefresh = document.getElementById('fm-btn-refresh');
const btnConfirmCreate = document.getElementById('fm-btn-confirm-create-item');
const btnCancelCreate = document.getElementById('fm-btn-cancel-create-item');
const createInput = document.getElementById('fm-new-item-name-input');
if (btnUpload && fileInput) {
btnUpload.addEventListener('click', () => {
fileInput.value = '';
fileInput.click();
});
fileInput.addEventListener('change', async (e) => {
const file = e.target.files?.[0];
if (!file) return;
if (file.size > 20 * 1024 * 1024) {
toast.error('Archivo demasiado grande', 'El tamaño máximo permitido es 20 MB.');
return;
}
toast.info('Subiendo archivo...', `Subiendo '${file.name}'`);
const reader = new FileReader();
reader.onload = async () => {
try {
const result = reader.result;
const base64Content = typeof result === 'string' && result.includes(',')
? result.split(',')[1]
: result;
await api.uploadFile(fmCurrentFolder, fmCurrentPath, file.name, base64Content);
toast.success('Archivo Subido', `'${file.name}' se ha subido correctamente.`);
loadFileManagerFiles(fmCurrentFolder, fmCurrentPath);
} catch (err) {
toast.error('Error al subir archivo', err.detail || err.message);
}
};
reader.onerror = () => {
toast.error('Error de lectura', 'No se pudo leer el archivo seleccionado.');
};
reader.readAsDataURL(file);
});
}
if (btnNewFile) {
btnNewFile.addEventListener('click', () => {
fmCreateType = 'file';
const row = document.getElementById('fm-new-item-row');
const badge = document.getElementById('fm-create-type-label');
if (badge) {
badge.textContent = 'Archivo';
badge.className = 'badge badge-mode-static';
}
if (createInput) {
createInput.value = '';
createInput.placeholder = 'ejemplo.php';
}
if (row) row.style.display = 'block';
createInput?.focus();
});
}
if (btnNewFolder) {
btnNewFolder.addEventListener('click', () => {
fmCreateType = 'dir';
const row = document.getElementById('fm-new-item-row');
const badge = document.getElementById('fm-create-type-label');
if (badge) {
badge.textContent = 'Directorio';
badge.className = 'badge badge-mode-proxy';
}
if (createInput) {
createInput.value = '';
createInput.placeholder = 'nombre-carpeta';
}
if (row) row.style.display = 'block';
createInput?.focus();
});
}
if (btnCancelCreate) {
btnCancelCreate.addEventListener('click', () => {
const row = document.getElementById('fm-new-item-row');
if (row) row.style.display = 'none';
});
}
if (btnConfirmCreate) {
btnConfirmCreate.addEventListener('click', async () => {
const name = createInput?.value?.trim();
if (!name) {
toast.warning('Campo requerido', 'Ingresa un nombre para el nuevo elemento.');
return;
}
try {
await api.createFolderItem(fmCurrentFolder, fmCurrentPath, name, fmCreateType);
toast.success(
fmCreateType === 'dir' ? 'Directorio Creado' : 'Archivo Creado',
`'${name}' creado exitosamente.`
);
const row = document.getElementById('fm-new-item-row');
if (row) row.style.display = 'none';
loadFileManagerFiles(fmCurrentFolder, fmCurrentPath);
} catch (err) {
toast.error('Error al crear elemento', err.detail || err.message);
}
});
if (createInput) {
createInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
btnConfirmCreate.click();
} else if (e.key === 'Escape') {
const row = document.getElementById('fm-new-item-row');
if (row) row.style.display = 'none';
}
});
}
}
if (btnUpDir) {
btnUpDir.addEventListener('click', () => {
if (!fmCurrentPath) return;
const parts = fmCurrentPath.split('/').filter(Boolean);
parts.pop();
const parentPath = parts.join('/');
loadFileManagerFiles(fmCurrentFolder, parentPath);
});
}
if (btnRefresh) {
btnRefresh.addEventListener('click', () => {
loadFileManagerFiles(fmCurrentFolder, fmCurrentPath);
toast.info('Actualizando', 'Contenido de carpeta actualizado.');
});
}
}
async function openFileManager(folderName, subPath = '') {
fmCurrentFolder = folderName;
fmCurrentPath = subPath;
const row = document.getElementById('fm-new-item-row');
if (row) row.style.display = 'none';
openModal('modal-file-manager');
await loadFileManagerFiles(folderName, subPath);
}
async function loadFileManagerFiles(folderName, subPath = '') {
fmCurrentFolder = folderName;
fmCurrentPath = subPath;
const modalTitle = document.getElementById('fm-modal-title');
const pathDisplay = document.getElementById('fm-current-path-display');
const tableBody = document.getElementById('fm-files-table-body');
const itemsCountText = document.getElementById('fm-items-count-text');
const btnUpDir = document.getElementById('fm-btn-up-dir');
if (modalTitle) modalTitle.textContent = `Gestor de Archivos: ${folderName}`;
const fullDisplayPath = `/var/www/${folderName}${subPath ? `/${subPath}` : ''}`;
if (pathDisplay) pathDisplay.textContent = fullDisplayPath;
if (btnUpDir) {
btnUpDir.disabled = !subPath;
}
// Renderizar Breadcrumbs
renderBreadcrumbs(folderName, subPath);
if (tableBody) {
tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">Cargando archivos...</td></tr>`;
}
try {
const res = await api.getFolderFiles(folderName, subPath);
const data = res.data || res;
fmFiles = data.files || [];
if (itemsCountText) {
itemsCountText.textContent = `${fmFiles.length} elemento${fmFiles.length === 1 ? '' : 's'}`;
}
renderFileManagerTable(fmFiles);
} catch (err) {
if (tableBody) {
tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: var(--color-danger); padding: 2rem;">Error al leer carpeta: ${escapeHtml(err.detail || err.message)}</td></tr>`;
}
}
}
function renderBreadcrumbs(folderName, subPath) {
const container = document.getElementById('fm-breadcrumbs');
if (!container) return;
const parts = subPath ? subPath.split('/').filter(Boolean) : [];
let html = `
<button type="button" class="fm-breadcrumb-item ${parts.length === 0 ? 'fm-breadcrumb-active' : ''}" data-path="">
<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M2 3h4l2 2h6v8H2z"></path>
</svg>
<span>Raíz (/var/www/${escapeHtml(folderName)})</span>
</button>
`;
let accumulated = '';
parts.forEach((p, index) => {
accumulated = accumulated ? `${accumulated}/${p}` : p;
const isLast = index === parts.length - 1;
html += `
<span class="fm-breadcrumb-separator">/</span>
<button type="button" class="fm-breadcrumb-item ${isLast ? 'fm-breadcrumb-active' : ''}" data-path="${escapeHtml(accumulated)}">
<span>${escapeHtml(p)}</span>
</button>
`;
});
container.innerHTML = html;
container.querySelectorAll('.fm-breadcrumb-item:not(.fm-breadcrumb-active)').forEach(btn => {
btn.addEventListener('click', () => {
const targetPath = btn.getAttribute('data-path') || '';
loadFileManagerFiles(fmCurrentFolder, targetPath);
});
});
}
function getFileIconSvg(file) {
if (file.type === 'directory') {
return `<svg class="fm-icon-folder" viewBox="0 0 16 16" width="18" height="18" fill="currentColor">
<path d="M2 3a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H7L5.5 3.5A1 1 0 0 0 4.8 3H2z"/>
</svg>`;
}
const ext = (file.name.includes('.') ? file.name.split('.').pop() : '').toLowerCase();
if (ext === 'php') {
return `<svg class="fm-icon-php" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<path stroke-linecap="round" d="M6 8h2a1.5 1.5 0 0 1 0 3H6v2M12 8h2a1.5 1.5 0 0 1 0 3h-2v2"></path>
</svg>`;
}
if (ext === 'js' || ext === 'mjs' || ext === 'ts') {
return `<svg class="fm-icon-js" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<path stroke-linecap="round" d="M8 14V9M12 9v4a1 1 0 0 1-2 0"></path>
</svg>`;
}
if (ext === 'html' || ext === 'htm') {
return `<svg class="fm-icon-html" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<path stroke-linecap="round" d="M7 8l-3 2 3 2M13 8l3 2-3 2M11 7l-2 6"></path>
</svg>`;
}
if (ext === 'css' || ext === 'scss' || ext === 'less') {
return `<svg class="fm-icon-css" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<path stroke-linecap="round" d="M7 7h6M7 10h6M7 13h4"></path>
</svg>`;
}
if (ext === 'json') {
return `<svg class="fm-icon-json" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<circle cx="7" cy="8" r="1" fill="currentColor"></circle>
<circle cx="13" cy="8" r="1" fill="currentColor"></circle>
<path stroke-linecap="round" d="M7 13s1.5-2 3-2 3 2 3 2"></path>
</svg>`;
}
if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'].includes(ext)) {
return `<svg class="fm-icon-img" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<rect x="2" y="3" width="16" height="14" rx="2"></rect>
<circle cx="7" cy="7" r="1.5"></circle>
<path stroke-linecap="round" d="M18 13l-5-5-7 7"></path>
</svg>`;
}
return `<svg class="fm-icon-default" viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 2h8l5 5v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"></path>
</svg>`;
}
function renderFileManagerTable(files) {
const tableBody = document.getElementById('fm-files-table-body');
if (!tableBody) return;
if (files.length === 0) {
tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2.5rem;">Esta carpeta está vacía. Sube archivos o crea uno nuevo usando la barra superior.</td></tr>`;
return;
}
tableBody.innerHTML = files.map(file => {
const isDir = file.type === 'directory';
const icon = getFileIconSvg(file);
const dateFormatted = file.lastModified ? new Date(file.lastModified).toLocaleString() : '—';
return `
<tr class="${isDir ? 'fm-dir-row' : ''}">
<td>
<div class="fm-file-name-cell">
${icon}
${isDir
? `<a href="#" class="fm-folder-link" data-path="${escapeHtml(file.path)}">${escapeHtml(file.name)}/</a>`
: `<span style="font-weight: 500; color: var(--text-primary);">${escapeHtml(file.name)}</span>`
}
</div>
</td>
<td>
<span class="badge ${isDir ? 'badge-mode-proxy' : 'badge-status-active'}" style="font-size: 0.72rem;">
${isDir ? 'Directorio' : 'Archivo'}
</span>
</td>
<td><span class="tabular-nums" style="font-size: 0.8rem;">${isDir ? '—' : (file.sizeFormatted || '—')}</span></td>
<td><code style="font-size: 0.76rem;">${escapeHtml(file.permissions || '—')}</code></td>
<td style="font-size: 0.76rem; color: var(--text-muted);">${dateFormatted}</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.4rem;">
${file.isEditable
? `<button
type="button"
class="btn btn-secondary btn-fm-edit"
data-name="${escapeHtml(file.name)}"
data-path="${escapeHtml(file.path)}"
style="min-height: 30px; padding: 0.25rem 0.65rem; font-size: 0.76rem;"
title="Editar en el Editor de Código"
>
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path>
</svg>
<span>Editar</span>
</button>`
: ''
}
<button
type="button"
class="btn-icon btn-icon-danger btn-fm-delete"
data-name="${escapeHtml(file.name)}"
data-path="${escapeHtml(file.path)}"
data-type="${file.type}"
title="Eliminar elemento"
>
<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</div>
</td>
</tr>
`;
}).join('');
// Eventos en filas
tableBody.querySelectorAll('.fm-folder-link').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const targetPath = link.getAttribute('data-path');
loadFileManagerFiles(fmCurrentFolder, targetPath);
});
});
tableBody.querySelectorAll('.btn-fm-edit').forEach(btn => {
btn.addEventListener('click', () => {
const fileName = btn.getAttribute('data-name');
const filePath = btn.getAttribute('data-path');
openCodeEditor(fmCurrentFolder, filePath, fileName);
});
});
tableBody.querySelectorAll('.btn-fm-delete').forEach(btn => {
btn.addEventListener('click', async () => {
const fileName = btn.getAttribute('data-name');
const filePath = btn.getAttribute('data-path');
const type = btn.getAttribute('data-type');
const isDir = type === 'directory';
const promptText = `¿Estás seguro de que deseas eliminar ${isDir ? 'el directorio' : 'el archivo'} '${fileName}'?`;
if (!confirm(promptText)) return;
try {
await api.deleteFolderItem(fmCurrentFolder, filePath);
toast.success(
isDir ? 'Directorio Eliminado' : 'Archivo Eliminado',
`'${fileName}' fue eliminado correctamente.`
);
loadFileManagerFiles(fmCurrentFolder, fmCurrentPath);
} catch (err) {
toast.error('Error al eliminar', err.detail || err.message);
}
});
});
}
/* ==========================================================================
Editor de Código para Archivos Web (.php, .html, .css, .js, etc.)
========================================================================== */
let currentEditorFolder = '';
let currentEditorPath = '';
let currentEditorFileName = '';
let editorOriginalContent = '';
function setupCodeEditor() {
const textarea = document.getElementById('code-editor-textarea');
const btnSaveTop = document.getElementById('code-editor-btn-save');
const btnSaveBottom = document.getElementById('code-editor-btn-save-bottom');
const btnClose = document.getElementById('code-editor-btn-close');
if (textarea) {
textarea.addEventListener('input', () => {
updateCodeEditorLineNumbers();
updateCodeEditorStatus();
updateCodeEditorCursorPos();
});
textarea.addEventListener('scroll', () => {
const lineGutter = document.getElementById('code-editor-linenumbers');
if (lineGutter) {
lineGutter.scrollTop = textarea.scrollTop;
}
});
textarea.addEventListener('click', updateCodeEditorCursorPos);
textarea.addEventListener('keyup', updateCodeEditorCursorPos);
// Tecla Tab e interceptación de Ctrl+S / Cmd+S
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
textarea.value = textarea.value.substring(0, start) + ' ' + textarea.value.substring(end);
textarea.selectionStart = textarea.selectionEnd = start + 2;
updateCodeEditorLineNumbers();
updateCodeEditorStatus();
} else if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
saveCodeEditorFile();
}
});
}
if (btnSaveTop) btnSaveTop.addEventListener('click', saveCodeEditorFile);
if (btnSaveBottom) btnSaveBottom.addEventListener('click', saveCodeEditorFile);
if (btnClose) {
btnClose.addEventListener('click', () => {
const modal = document.getElementById('modal-code-editor');
if (modal) modal.classList.remove('active');
});
}
}
async function openCodeEditor(folderName, filePath, fileName) {
currentEditorFolder = folderName;
currentEditorPath = filePath;
currentEditorFileName = fileName;
const modal = document.getElementById('modal-code-editor');
const titleEl = document.getElementById('code-editor-file-title');
const pathEl = document.getElementById('code-editor-file-path');
const statusEl = document.getElementById('code-editor-save-status');
const textarea = document.getElementById('code-editor-textarea');
if (titleEl) titleEl.textContent = fileName;
if (pathEl) pathEl.textContent = `/var/www/${folderName}/${filePath}`;
if (statusEl) {
statusEl.textContent = 'Cargando...';
statusEl.className = 'code-editor-status-tag status-clean';
}
if (textarea) {
textarea.value = '';
textarea.disabled = true;
}
openModal('modal-code-editor');
try {
const res = await api.getFileContent(folderName, filePath);
const data = res.data || res;
const content = typeof data.content === 'string' ? data.content : '';
if (textarea) {
textarea.value = content;
textarea.disabled = false;
editorOriginalContent = content;
}
updateCodeEditorLineNumbers();
updateCodeEditorStatus();
updateCodeEditorCursorPos();
textarea?.focus();
} catch (err) {
if (statusEl) {
statusEl.textContent = 'Error al cargar';
statusEl.className = 'code-editor-status-tag status-dirty';
}
toast.error('Error al abrir archivo', err.detail || err.message);
}
}
function updateCodeEditorLineNumbers() {
const textarea = document.getElementById('code-editor-textarea');
const lineGutter = document.getElementById('code-editor-linenumbers');
if (!textarea || !lineGutter) return;
const linesCount = (textarea.value.match(/\n/g) || []).length + 1;
let numbersStr = '';
for (let i = 1; i <= linesCount; i++) {
numbersStr += i + '\n';
}
lineGutter.textContent = numbersStr;
lineGutter.scrollTop = textarea.scrollTop;
}
function updateCodeEditorStatus() {
const textarea = document.getElementById('code-editor-textarea');
const statusEl = document.getElementById('code-editor-save-status');
const charCountEl = document.getElementById('code-editor-char-count');
if (!textarea || !statusEl) return;
const isDirty = textarea.value !== editorOriginalContent;
if (isDirty) {
statusEl.textContent = 'Modificado*';
statusEl.className = 'code-editor-status-tag status-dirty';
} else {
statusEl.textContent = 'Sin cambios';
statusEl.className = 'code-editor-status-tag status-clean';
}
if (charCountEl) {
charCountEl.textContent = `${textarea.value.length} caracteres`;
}
}
function updateCodeEditorCursorPos() {
const textarea = document.getElementById('code-editor-textarea');
const posEl = document.getElementById('code-editor-cursor-pos');
if (!textarea || !posEl) return;
const textToCursor = textarea.value.substring(0, textarea.selectionStart);
const lines = textToCursor.split('\n');
const currentLine = lines.length;
const currentCol = lines[lines.length - 1].length + 1;
posEl.textContent = `Línea ${currentLine}, Col ${currentCol}`;
}
async function saveCodeEditorFile() {
const textarea = document.getElementById('code-editor-textarea');
const statusEl = document.getElementById('code-editor-save-status');
const btnTop = document.getElementById('code-editor-btn-save');
const btnBottom = document.getElementById('code-editor-btn-save-bottom');
if (!textarea || !currentEditorFolder || !currentEditorPath) return;
if (statusEl) {
statusEl.textContent = 'Guardando...';
statusEl.className = 'code-editor-status-tag status-saving';
}
if (btnTop) btnTop.disabled = true;
if (btnBottom) btnBottom.disabled = true;
try {
await api.saveFileContent(currentEditorFolder, currentEditorPath, textarea.value);
editorOriginalContent = textarea.value;
if (statusEl) {
statusEl.textContent = 'Guardado exitosamente';
statusEl.className = 'code-editor-status-tag status-saved';
}
toast.success('Archivo Guardado', `'${currentEditorFileName}' se guardó en el servidor.`);
updateCodeEditorStatus();
// Si el file manager está abierto en la misma carpeta, actualizar lista
if (fmCurrentFolder === currentEditorFolder) {
loadFileManagerFiles(fmCurrentFolder, fmCurrentPath);
}
} catch (err) {
if (statusEl) {
statusEl.textContent = 'Error al guardar';
statusEl.className = 'code-editor-status-tag status-dirty';
}
toast.error('Error al guardar archivo', err.detail || err.message);
} finally {
if (btnTop) btnTop.disabled = false;
if (btnBottom) btnBottom.disabled = false;
}
}
/* ==========================================================================
🖥️ Pestaña 3: Terminal Remota del Sistema (Bash)
========================================================================== */
let terminalCommandHistory = [];
let terminalHistoryIndex = -1;
let currentTerminalCwd = '/var/www';
let terminalUser = 'root';
let terminalHost = 'vps-jose';
function setupTerminal() {
const form = document.getElementById('terminal-command-form');
const input = document.getElementById('terminal-input');
const btnClear = document.getElementById('terminal-btn-clear');
const loginForm = document.getElementById('form-terminal-login');
const btnLogout = document.getElementById('btn-terminal-logout');
const userEl = document.getElementById('terminal-vps-user-input');
const errEl = document.getElementById('terminal-login-error');
// Validación inmediata al teclear en el campo de usuario
if (userEl) {
userEl.addEventListener('input', () => {
const val = userEl.value.trim().toLowerCase();
if (val === 'ggc') {
if (errEl) {
errEl.textContent = "El usuario 'ggc' está reservado para desarrollo. Ingrese con 'root' u otro usuario del VPS.";
errEl.style.display = 'block';
}
} else if (errEl && errEl.textContent.includes('ggc')) {
errEl.style.display = 'none';
errEl.textContent = '';
}
});
}
// Formulario de autenticación del sistema VPS
if (loginForm) {
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const passEl = document.getElementById('terminal-vps-pass-input');
const vpsUser = userEl?.value.trim();
const vpsPassword = passEl?.value;
if (!vpsUser || !vpsPassword) {
if (errEl) {
errEl.textContent = 'Ingrese usuario y contraseña del VPS.';
errEl.style.display = 'block';
}
return;
}
// Validación estricta anti-ggc
if (vpsUser.toLowerCase() === 'ggc') {
if (errEl) {
errEl.textContent = "El usuario 'ggc' está reservado para desarrollo. Ingrese con 'root' u otro usuario del VPS.";
errEl.style.display = 'block';
}
return;
}
const btnSubmit = document.getElementById('btn-terminal-login');
if (btnSubmit) btnSubmit.disabled = true;
try {
const res = await api.vpsTerminalLogin(vpsUser, vpsPassword);
if (errEl) errEl.style.display = 'none';
if (passEl) passEl.value = '';
toast.success('Sesión iniciada', `Autenticado en el VPS como ${vpsUser}`);
await initTerminalTab();
} catch (err) {
if (errEl) {
errEl.textContent = err.detail || err.message || 'Credenciales de usuario del VPS inválidas.';
errEl.style.display = 'block';
}
} finally {
if (btnSubmit) btnSubmit.disabled = false;
}
});
}
// Botón de Cerrar Sesión del VPS
if (btnLogout) {
btnLogout.addEventListener('click', async () => {
try {
await api.vpsTerminalLogout();
toast.info('Sesión de terminal cerrada');
} catch (err) {
console.warn('[Terminal] Error en logout:', err);
} finally {
const authCard = document.getElementById('terminal-auth-card');
const activeView = document.getElementById('terminal-active-view');
if (authCard) authCard.style.display = 'flex';
if (activeView) activeView.style.display = 'none';
}
});
}
if (form && input) {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const cmd = input.value.trim();
if (!cmd) return;
terminalCommandHistory.push(cmd);
terminalHistoryIndex = -1;
input.value = '';
await executeTerminalCommand(cmd);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (terminalCommandHistory.length === 0) return;
if (terminalHistoryIndex === -1) {
terminalHistoryIndex = terminalCommandHistory.length - 1;
} else if (terminalHistoryIndex > 0) {
terminalHistoryIndex--;
}
input.value = terminalCommandHistory[terminalHistoryIndex] || '';
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (terminalHistoryIndex !== -1) {
if (terminalHistoryIndex < terminalCommandHistory.length - 1) {
terminalHistoryIndex++;
input.value = terminalCommandHistory[terminalHistoryIndex] || '';
} else {
terminalHistoryIndex = -1;
input.value = '';
}
}
}
});
}
// Quick command buttons
document.querySelectorAll('.btn-quick-cmd').forEach(btn => {
btn.addEventListener('click', () => {
const cmd = btn.getAttribute('data-cmd');
if (cmd && input) {
input.value = cmd;
if (form) {
form.dispatchEvent(new Event('submit', { cancelable: true }));
}
}
});
});
if (btnClear) {
btnClear.addEventListener('click', () => {
const screen = document.getElementById('terminal-screen');
if (screen) {
screen.innerHTML = `
<div class="terminal-banner">
<span class="terminal-banner-brand">a2host Remote Web Terminal v1.0 [Linux 6.x / VPS elingejose.com]</span>
<span class="terminal-banner-sub">Escribe un comando o selecciona una acción rápida superior. Usa las flechas ↑/↓ para navegar en el historial.</span>
</div>
`;
}
});
}
}
async function initTerminalTab() {
const activeView = document.getElementById('terminal-active-view');
const badgeEl = document.getElementById('terminal-env-badge');
const promptLabel = document.getElementById('terminal-prompt-label');
const topbarTitle = document.getElementById('terminal-topbar-title');
const input = document.getElementById('terminal-input');
if (activeView) activeView.style.display = 'block';
try {
const res = await api.getTerminalInfo();
const info = res.data || res;
terminalUser = info.user || 'root';
terminalHost = info.hostname || 'vps-jose';
currentTerminalCwd = info.cwd || '/var/www';
if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`;
if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:# `;
if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`;
input?.focus();
} catch {
terminalUser = 'root';
terminalHost = 'vps-jose';
currentTerminalCwd = '/var/www';
if (badgeEl) badgeEl.textContent = 'root@vps-jose (/var/www)';
if (promptLabel) promptLabel.textContent = 'root@vps:# ';
input?.focus();
}
}
async function executeTerminalCommand(cmd) {
const screen = document.getElementById('terminal-screen');
const input = document.getElementById('terminal-input');
if (!screen) return;
const entryId = 'cmd-' + Date.now();
const promptText = `${terminalUser}@${terminalHost}:~${currentTerminalCwd}$`;
const entryEl = document.createElement('div');
entryEl.className = 'terminal-entry';
entryEl.id = entryId;
entryEl.innerHTML = `
<div class="terminal-cmd-row">
<span class="terminal-prompt-sym">${escapeHtml(promptText)}</span>
<span>${escapeHtml(cmd)}</span>
</div>
<div class="terminal-output-block" id="output-${entryId}">
<span style="color: var(--text-muted); font-style: italic;">Ejecutando proceso...</span>
</div>
`;
screen.appendChild(entryEl);
screen.scrollTop = screen.scrollHeight;
if (input) input.disabled = true;
try {
const response = await api.executeCommand(cmd, currentTerminalCwd);
const result = response.data || response;
const outBlock = document.getElementById(`output-${entryId}`);
if (outBlock) {
const stdout = result.stdout || '';
const stderr = result.stderr || '';
const exitCode = result.exitCode ?? 0;
const ms = result.executionTimeMs ?? 0;
let outHtml = '';
if (stdout) {
outHtml += `<div>${escapeHtml(stdout)}</div>`;
}
if (stderr) {
outHtml += `<div class="terminal-stderr-text">${escapeHtml(stderr)}</div>`;
}
if (!stdout && !stderr) {
outHtml += `<span style="color: var(--text-muted); font-style: italic;">(Sin salida)</span>`;
}
outBlock.innerHTML = outHtml;
if (exitCode !== 0) {
outBlock.classList.add('has-error');
}
// Añadir footer
const footerEl = document.createElement('div');
footerEl.className = 'terminal-entry-footer';
footerEl.innerHTML = `
<span>⏱️ ${ms}ms</span>
<span class="${exitCode === 0 ? 'terminal-badge-ok' : 'terminal-badge-err'}">
exit ${exitCode}
</span>
`;
entryEl.appendChild(footerEl);
if (result.cwd && result.cwd !== currentTerminalCwd) {
currentTerminalCwd = result.cwd;
const promptLabel = document.getElementById('terminal-prompt-label');
const badgeEl = document.getElementById('terminal-env-badge');
const topbarTitle = document.getElementById('terminal-topbar-title');
if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`;
if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:~$`;
if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`;
}
}
} catch (err) {
const outBlock = document.getElementById(`output-${entryId}`);
if (outBlock) {
outBlock.classList.add('has-error');
outBlock.innerHTML = `<div class="terminal-stderr-text">Error de ejecución: ${escapeHtml(err.detail || err.message)}</div>`;
}
} finally {
if (input) {
input.disabled = false;
input.focus();
}
screen.scrollTop = screen.scrollHeight;
}
}
/* ==========================================================================
📊 Pestaña 4: Monitor del Servidor VPS
========================================================================== */
let monitorAutoRefreshTimer = null;
let currentTopProcesses = [];
let pendingKillPid = null;
let pendingKillCommand = null;
let pendingRestartService = null;
function getServiceNameForProcess(cmd) {
const lower = (cmd || '').toLowerCase();
if (lower.includes('apache') || lower.includes('httpd')) return 'apache2';
if (lower.includes('gitea')) return 'gitea';
if (lower.includes('mysql') || lower.includes('mariadb')) return 'mysql';
if (lower.includes('node') || lower.includes('pm2') || lower.includes('a2host')) return 'a2host';
return null;
}
function setupMonitor() {
const btnRefresh = document.getElementById('btn-refresh-monitor');
const selectInterval = document.getElementById('monitor-interval-select');
const searchInput = document.getElementById('search-processes-input');
if (btnRefresh) {
btnRefresh.addEventListener('click', () => {
loadMonitorMetrics();
toast.info('Monitor Actualizado', 'Métricas refrescadas.');
});
}
if (selectInterval) {
selectInterval.addEventListener('change', () => {
restartMonitorAutoRefresh();
});
}
if (searchInput) {
searchInput.addEventListener('input', () => {
renderProcessesTable(currentTopProcesses);
});
}
// --- Herramientas de Mantenimiento ---
// 1. Liberar Caché de RAM
const btnCleanRam = document.getElementById('btn-clean-ram');
const txtCleanRam = document.getElementById('btn-clean-ram-text');
if (btnCleanRam) {
btnCleanRam.addEventListener('click', async () => {
btnCleanRam.disabled = true;
const originalText = txtCleanRam ? txtCleanRam.textContent : 'Liberar Caché de RAM (Drop Caches)';
if (txtCleanRam) txtCleanRam.textContent = 'Liberando caché de RAM...';
try {
const res = await api.cleanRam();
const data = res.data || res;
const freed = data.freedFormatted || '0 B';
toast.success('Memoria RAM Liberada', `Se recuperaron ${freed} de caché en el VPS.`);
await loadMonitorMetrics();
} catch (err) {
toast.error('Error al liberar RAM', err.detail || err.message);
} finally {
btnCleanRam.disabled = false;
if (txtCleanRam) txtCleanRam.textContent = originalText;
}
});
}
// 2. Limpiar Disco y Temporales
const btnCleanDisk = document.getElementById('btn-clean-disk');
const txtCleanDisk = document.getElementById('btn-clean-disk-text');
if (btnCleanDisk) {
btnCleanDisk.addEventListener('click', async () => {
btnCleanDisk.disabled = true;
const originalText = txtCleanDisk ? txtCleanDisk.textContent : 'Depurar Disco y Temporales';
if (txtCleanDisk) txtCleanDisk.textContent = 'Depurando temporales...';
try {
const res = await api.cleanDisk();
const data = res.data || res;
const freed = data.freedFormatted || '0 B';
toast.success('Disco Optimizado', `Se liberaron ${freed} de espacio en el sistema.`);
await loadMonitorMetrics();
} catch (err) {
toast.error('Error al depurar disco', err.detail || err.message);
} finally {
btnCleanDisk.disabled = false;
if (txtCleanDisk) txtCleanDisk.textContent = originalText;
}
});
}
// 3. Ver Desglose de Espacio en Disco
const btnViewBreakdown = document.getElementById('btn-view-disk-breakdown');
if (btnViewBreakdown) {
btnViewBreakdown.addEventListener('click', async () => {
const tbody = document.getElementById('disk-breakdown-table-body');
if (tbody) {
tbody.innerHTML = `<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Analizando almacenamiento del VPS...</td></tr>`;
}
openModal('modal-disk-breakdown');
try {
const res = await api.getDiskBreakdown();
const breakdown = Array.isArray(res) ? res : (res.data || []);
renderDiskBreakdownTable(breakdown);
} catch (err) {
if (tbody) {
tbody.innerHTML = `<tr><td colspan="3" style="text-align: center; color: var(--color-danger); padding: 1.5rem;">Error al leer desglose: ${escapeHtml(err.detail || err.message)}</td></tr>`;
}
}
});
}
// 4. Auditar Firewall (UFW) y Puertos
const btnAuditFirewall = document.getElementById('btn-audit-firewall');
if (btnAuditFirewall) {
btnAuditFirewall.addEventListener('click', async () => {
openModal('modal-firewall-status');
const statusTextEl = document.getElementById('firewall-status-text');
const statusBadgeEl = document.getElementById('firewall-status-badge');
const tbody = document.getElementById('firewall-ports-table-body');
const codeBlock = document.getElementById('firewall-commands-code');
if (statusTextEl) statusTextEl.textContent = 'Consultando estado de UFW...';
if (tbody) tbody.innerHTML = `<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Cargando puertos...</td></tr>`;
try {
const res = await api.getFirewallStatus();
const fw = res.data || res;
if (statusTextEl) statusTextEl.textContent = fw.statusText || (fw.ufwActive ? 'Activo (Protegido por UFW)' : 'Inactivo (Sin restricciones de firewall en el sistema)');
if (statusBadgeEl) {
statusBadgeEl.textContent = fw.ufwActive ? 'Activo' : 'Inactivo';
statusBadgeEl.className = `badge ${fw.ufwActive ? 'badge-status-active' : 'badge-status-disabled'}`;
}
if (tbody && Array.isArray(fw.requiredPorts)) {
tbody.innerHTML = fw.requiredPorts.map(p => `
<tr>
<td><span class="badge badge-port">${escapeHtml(p.port)}</span></td>
<td><code style="font-size: 0.78rem;">${escapeHtml(p.protocol)}</code></td>
<td><strong style="color: var(--text-primary);">${escapeHtml(p.service)}</strong></td>
<td style="font-size: 0.82rem; color: var(--text-secondary);">${escapeHtml(p.description)}</td>
</tr>
`).join('');
}
if (codeBlock && Array.isArray(fw.commandsToEnable)) {
codeBlock.textContent = fw.commandsToEnable.join('\n');
}
} catch (err) {
if (statusTextEl) statusTextEl.textContent = `Error al consultar: ${err.message}`;
}
});
}
// Copiar Comandos UFW
const btnCopyUfw = document.getElementById('btn-copy-ufw-commands');
if (btnCopyUfw) {
btnCopyUfw.addEventListener('click', () => {
const codeBlock = document.getElementById('firewall-commands-code');
if (codeBlock && codeBlock.textContent) {
navigator.clipboard.writeText(codeBlock.textContent).then(() => {
toast.info('Comandos Copiados', 'Reglas UFW copiadas al portapapeles.');
}).catch(() => {
toast.error('No se pudo copiar', 'Copia manualmente el texto de la caja.');
});
}
});
}
// Ver Versiones del Stack Tecnológico
const btnViewStack = document.getElementById('btn-view-stack-versions');
if (btnViewStack) {
btnViewStack.addEventListener('click', async () => {
openModal('modal-stack-versions');
const tbody = document.getElementById('stack-versions-table-body');
if (tbody) tbody.innerHTML = `<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Detectando versiones del software en el servidor...</td></tr>`;
try {
const res = await api.getSoftwareStack();
const items = res.data || res;
if (tbody && Array.isArray(items)) {
tbody.innerHTML = items.map(item => `
<tr>
<td><strong style="color: var(--text-primary);">${escapeHtml(item.name)}</strong></td>
<td><span class="text-xs text-muted">${escapeHtml(item.category)}</span></td>
<td><code class="credential-value" style="font-size: 0.82rem; color: var(--accent-lime);">${escapeHtml(item.version)}</code></td>
<td style="text-align: right;"><span class="badge ${item.installed ? 'badge-status-active' : 'badge-status-disabled'}">${item.installed ? 'Instalado &middot; Listo' : 'No detectado'}</span></td>
</tr>
`).join('');
}
} catch (err) {
if (tbody) tbody.innerHTML = `<tr><td colspan="4" style="text-align: center; color: var(--status-danger); padding: 1.5rem;">Error al detectar versiones: ${escapeHtml(err.message)}</td></tr>`;
}
});
}
// --- Confirmaciones de Modales de Procesos ---
// Confirmar Kill Proceso
const btnConfirmKill = document.getElementById('btn-confirm-kill-process');
if (btnConfirmKill) {
btnConfirmKill.addEventListener('click', async () => {
if (!pendingKillPid) return;
const signal = document.getElementById('kill-proc-signal-select')?.value || 'SIGTERM';
btnConfirmKill.disabled = true;
try {
const res = await api.killProcess(pendingKillPid, signal);
closeAllModals();
toast.success('Proceso Finalizado', res.message || `Proceso PID ${pendingKillPid} terminado (${signal}).`);
await loadMonitorMetrics();
} catch (err) {
toast.error('Error al finalizar proceso', err.detail || err.message);
} finally {
btnConfirmKill.disabled = false;
}
});
}
// Confirmar Reinicio de Servicio
const btnConfirmRestart = document.getElementById('btn-confirm-restart-service');
if (btnConfirmRestart) {
btnConfirmRestart.addEventListener('click', async () => {
if (!pendingRestartService) return;
btnConfirmRestart.disabled = true;
try {
const res = await api.restartSystemService(pendingRestartService);
closeAllModals();
toast.success('Servicio Reiniciado', res.message || `Servicio '${pendingRestartService}' reiniciado exitosamente.`);
await loadMonitorMetrics();
} catch (err) {
toast.error('Error al reiniciar servicio', err.detail || err.message);
} finally {
btnConfirmRestart.disabled = false;
}
});
}
}
function renderDiskBreakdownTable(items) {
const tbody = document.getElementById('disk-breakdown-table-body');
if (!tbody) return;
if (!items || items.length === 0) {
tbody.innerHTML = `<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron datos de almacenamiento.</td></tr>`;
return;
}
tbody.innerHTML = items.map(item => `
<tr>
<td><code style="font-weight: 700; color: var(--accent-lime);">${escapeHtml(item.path)}</code></td>
<td><strong class="tabular-nums" style="color: var(--text-primary);">${escapeHtml(item.sizeFormatted)}</strong></td>
<td style="font-size: 0.82rem; color: var(--text-secondary);">${escapeHtml(item.description || 'Directorio del sistema')}</td>
</tr>
`).join('');
}
function initMonitorTab() {
loadMonitorMetrics();
restartMonitorAutoRefresh();
}
function stopMonitorAutoRefresh() {
if (monitorAutoRefreshTimer) {
clearInterval(monitorAutoRefreshTimer);
monitorAutoRefreshTimer = null;
}
}
function restartMonitorAutoRefresh() {
stopMonitorAutoRefresh();
const selectInterval = document.getElementById('monitor-interval-select');
const intervalMs = Number(selectInterval?.value || 0);
if (intervalMs > 0) {
monitorAutoRefreshTimer = setInterval(() => {
if (store.getState('activeTab') === 'monitor') {
loadMonitorMetrics();
} else {
stopMonitorAutoRefresh();
}
}, intervalMs);
}
}
async function loadMonitorMetrics() {
const lastUpdatedEl = document.getElementById('monitor-last-updated-text');
try {
const [statsRes, procsRes] = await Promise.all([
api.getSystemStats(),
api.getSystemProcesses().catch(() => [])
]);
const stats = statsRes.data || statsRes;
const procs = Array.isArray(procsRes) ? procsRes : (procsRes.data || []);
currentTopProcesses = procs;
updateMonitorUI(stats);
renderProcessesTable(procs);
if (lastUpdatedEl) {
lastUpdatedEl.textContent = `Actualizado: ${new Date().toLocaleTimeString()}`;
}
} catch (err) {
console.warn('[Monitor] Error al cargar telemetría:', err.message);
}
}
function updateMonitorUI(stats) {
if (!stats) return;
// 1. CPU & Load Average
const cpuPercent = stats.cpu?.usagePercent ?? 0;
const cpuPercentEl = document.getElementById('monitor-cpu-percent');
const cpuBarEl = document.getElementById('monitor-cpu-bar');
const cpuModelEl = document.getElementById('monitor-cpu-model-text');
const load1mEl = document.getElementById('monitor-load-1m');
const load5mEl = document.getElementById('monitor-load-5m');
const load15mEl = document.getElementById('monitor-load-15m');
if (cpuPercentEl) cpuPercentEl.textContent = `${cpuPercent}%`;
if (cpuBarEl) {
cpuBarEl.style.width = `${Math.min(100, cpuPercent)}%`;
cpuBarEl.className = 'metric-progress-fill';
if (cpuPercent > 80) cpuBarEl.classList.add('fill-danger');
else if (cpuPercent > 60) cpuBarEl.classList.add('fill-warning');
}
if (cpuModelEl && stats.cpu) {
cpuModelEl.textContent = `${stats.cpu.cores} Cores &middot; ${stats.server?.arch || 'x64'}`;
}
if (load1mEl) load1mEl.textContent = stats.cpu?.loadavg?.[0]?.toFixed(2) ?? '0.00';
if (load5mEl) load5mEl.textContent = stats.cpu?.loadavg?.[1]?.toFixed(2) ?? '0.00';
if (load15mEl) load15mEl.textContent = stats.cpu?.loadavg?.[2]?.toFixed(2) ?? '0.00';
// 2. RAM del VPS
const ramUsedEl = document.getElementById('monitor-ram-used-text');
const ramPercentEl = document.getElementById('monitor-ram-percent');
const ramBarEl = document.getElementById('monitor-ram-bar');
const ramFreeEl = document.getElementById('monitor-ram-free');
const ramCacheEl = document.getElementById('monitor-ram-cache');
if (stats.memory) {
const mem = stats.memory;
const usedText = mem.hostUsedFormatted || mem.usedFormatted || '0 B';
const totalText = mem.hostTotalFormatted || mem.totalFormatted || '1 GB';
const percent = mem.hostUsedPercent ?? mem.usedPercent ?? 0;
const freeText = mem.hostAvailableFormatted || mem.hostFreeFormatted || mem.freeFormatted || '0 B';
const cacheText = mem.buffersCacheFormatted || mem.cachedFormatted || '—';
if (ramUsedEl) ramUsedEl.textContent = `${usedText} / ${totalText}`;
if (ramPercentEl) ramPercentEl.textContent = `${percent}%`;
if (ramBarEl) {
ramBarEl.style.width = `${Math.min(100, Math.max(0, percent))}%`;
ramBarEl.className = 'metric-progress-fill fill-lime';
if (percent > 85) ramBarEl.classList.add('fill-danger');
else if (percent > 65) ramBarEl.classList.add('fill-warning');
}
if (ramFreeEl) ramFreeEl.textContent = freeText;
if (ramCacheEl) ramCacheEl.textContent = cacheText;
}
// 3. Swap
const swapUsedEl = document.getElementById('monitor-swap-used-text');
const swapPercentEl = document.getElementById('monitor-swap-percent');
const swapBarEl = document.getElementById('monitor-swap-bar');
const swapFreeEl = document.getElementById('monitor-swap-free');
const swapTotalEl = document.getElementById('monitor-swap-total');
const swapObj = stats.swap || stats.memory?.swap || {};
const swapUsedText = swapObj.usedFormatted || stats.memory?.swapUsedFormatted || '0 B';
const swapTotalText = swapObj.totalFormatted || stats.memory?.swapTotalFormatted || '0 B';
const swapPercent = swapObj.usedPercent ?? stats.memory?.swapUsedPercent ?? 0;
const swapFreeText = swapObj.freeFormatted || stats.memory?.swapFreeFormatted || '—';
if (swapUsedEl) swapUsedEl.textContent = `${swapUsedText} / ${swapTotalText}`;
if (swapPercentEl) swapPercentEl.textContent = `${swapPercent}%`;
if (swapBarEl) {
swapBarEl.style.width = `${Math.min(100, Math.max(0, swapPercent))}%`;
swapBarEl.className = 'metric-progress-fill fill-purple';
if (swapPercent > 80) swapBarEl.classList.add('fill-danger');
}
if (swapFreeEl) swapFreeEl.textContent = swapFreeText;
if (swapTotalEl) swapTotalEl.textContent = swapTotalText;
// 4. Disco /
const diskUsedEl = document.getElementById('monitor-disk-used-text');
const diskPercentEl = document.getElementById('monitor-disk-percent');
const diskBarEl = document.getElementById('monitor-disk-bar');
const diskFreeEl = document.getElementById('monitor-disk-free');
const diskTotalEl = document.getElementById('monitor-disk-total');
if (stats.disk) {
const d = stats.disk;
if (diskUsedEl) diskUsedEl.textContent = `${d.usedFormatted || '0 B'} / ${d.totalFormatted || '0 B'}`;
if (diskPercentEl) diskPercentEl.textContent = `${d.usedPercent || 0}%`;
if (diskBarEl) diskBarEl.style.width = `${Math.min(100, d.usedPercent || 0)}%`;
if (diskFreeEl) diskFreeEl.textContent = d.freeFormatted || '0 B';
if (diskTotalEl) diskTotalEl.textContent = d.totalFormatted || '0 B';
}
// 5. Proceso a2host (PM2 vs 120M)
const pm2UsedEl = document.getElementById('monitor-pm2-used-text');
const pm2PercentEl = document.getElementById('monitor-pm2-percent');
const pm2BarEl = document.getElementById('monitor-pm2-bar');
const pm2HeapEl = document.getElementById('monitor-pm2-heap');
if (stats.memory) {
const mem = stats.memory;
const rssBytes = mem.processRssBytes || 0;
const pm2Limit = 120 * 1024 * 1024;
const pm2Percent = Math.min(100, Math.round((rssBytes / pm2Limit) * 100));
if (pm2UsedEl) pm2UsedEl.textContent = `${mem.processRssFormatted || '0 MB'} / 120 MB`;
if (pm2PercentEl) pm2PercentEl.textContent = `${pm2Percent}%`;
if (pm2BarEl) {
pm2BarEl.style.width = `${pm2Percent}%`;
pm2BarEl.className = 'metric-progress-fill fill-lime';
if (pm2Percent > 85) pm2BarEl.classList.add('fill-danger');
else if (pm2Percent > 65) pm2BarEl.classList.add('fill-warning');
}
if (pm2HeapEl) pm2HeapEl.textContent = `${mem.heapUsedFormatted || '—'} / ${mem.heapTotalFormatted || '—'}`;
}
}
function getProcessBadgeClass(cmd) {
const lower = (cmd || '').toLowerCase();
if (lower.includes('apache') || lower.includes('httpd')) return 'proc-apache';
if (lower.includes('node') || lower.includes('pm2')) return 'proc-node';
if (lower.includes('git')) return 'proc-gitea';
if (lower.includes('mysql') || lower.includes('mariadb')) return 'proc-mysql';
return 'proc-system';
}
function renderProcessesTable(processes) {
const tableBody = document.getElementById('processes-table-body');
const mobileContainer = document.getElementById('processes-mobile-list');
const searchInput = document.getElementById('search-processes-input');
const query = searchInput?.value?.trim().toLowerCase() || '';
const filtered = processes.filter(p => {
if (!query) return true;
return String(p.pid).includes(query) ||
(p.command || '').toLowerCase().includes(query) ||
(p.user || '').toLowerCase().includes(query);
});
if (tableBody) {
if (filtered.length === 0) {
tableBody.innerHTML = `<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron procesos coincidentes.</td></tr>`;
} else {
tableBody.innerHTML = filtered.map(p => {
const badgeCls = getProcessBadgeClass(p.command);
const serviceName = getServiceNameForProcess(p.command);
return `
<tr>
<td><code style="font-weight: 700; color: var(--text-secondary);">${p.pid}</code></td>
<td><span style="font-size: 0.8rem;">${escapeHtml(p.user || 'root')}</span></td>
<td><span class="tabular-nums" style="font-weight: 600;">${p.cpuPercent}%</span></td>
<td><span class="tabular-nums" style="font-weight: 600;">${p.memPercent}%</span></td>
<td><span class="tabular-nums">${escapeHtml(p.rssFormatted || '—')}</span></td>
<td>
<span class="process-cmd-badge ${badgeCls}">
${escapeHtml(p.command || '')}
</span>
</td>
<td style="text-align: right; white-space: nowrap;">
<div style="display: inline-flex; gap: 0.35rem; align-items: center; justify-content: flex-end;">
${serviceName ? `
<button
type="button"
class="btn btn-secondary btn-sm btn-restart-proc"
data-service="${serviceName}"
data-cmd="${escapeHtml(p.command || '')}"
title="Reiniciar servicio ${serviceName}"
style="padding: 0.25rem 0.6rem; font-size: 0.76rem;"
>
🔄 Reiniciar
</button>
` : ''}
<button
type="button"
class="btn btn-danger btn-sm btn-kill-proc"
data-pid="${p.pid}"
data-cmd="${escapeHtml(p.command || '')}"
title="Finalizar proceso PID ${p.pid}"
style="padding: 0.25rem 0.6rem; font-size: 0.76rem;"
>
🛑 Finalizar
</button>
</div>
</td>
</tr>
`;
}).join('');
}
}
if (mobileContainer) {
if (filtered.length === 0) {
mobileContainer.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron procesos coincidentes.</div>`;
} else {
mobileContainer.innerHTML = filtered.map(p => {
const badgeCls = getProcessBadgeClass(p.command);
const serviceName = getServiceNameForProcess(p.command);
return `
<div class="mobile-card">
<div class="mobile-card-header">
<span class="process-cmd-badge ${badgeCls}">${escapeHtml(p.command || '')}</span>
<code>PID: ${p.pid}</code>
</div>
<div class="mobile-card-body">
<div class="mobile-card-row">
<span>Usuario:</span>
<strong>${escapeHtml(p.user || 'root')}</strong>
</div>
<div class="mobile-card-row">
<span>CPU %:</span>
<strong>${p.cpuPercent}%</strong>
</div>
<div class="mobile-card-row">
<span>Memoria %:</span>
<strong>${p.memPercent}% (${p.rssFormatted || '—'})</strong>
</div>
</div>
<div class="mobile-card-actions" style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
${serviceName ? `
<button
type="button"
class="btn btn-secondary btn-sm btn-restart-proc"
data-service="${serviceName}"
data-cmd="${escapeHtml(p.command || '')}"
style="flex: 1; justify-content: center;"
>
🔄 Reiniciar
</button>
` : ''}
<button
type="button"
class="btn btn-danger btn-sm btn-kill-proc"
data-pid="${p.pid}"
data-cmd="${escapeHtml(p.command || '')}"
style="flex: 1; justify-content: center;"
>
🛑 Finalizar
</button>
</div>
</div>
`;
}).join('');
}
}
// Vincular eventos de botones de procesos
document.querySelectorAll('.btn-kill-proc').forEach(btn => {
btn.addEventListener('click', () => {
pendingKillPid = btn.getAttribute('data-pid');
pendingKillCommand = btn.getAttribute('data-cmd');
const pidEl = document.getElementById('kill-proc-pid-text');
const nameEl = document.getElementById('kill-proc-name-text');
if (pidEl) pidEl.textContent = pendingKillPid;
if (nameEl) nameEl.textContent = pendingKillCommand;
openModal('modal-kill-process');
});
});
document.querySelectorAll('.btn-restart-proc').forEach(btn => {
btn.addEventListener('click', () => {
pendingRestartService = btn.getAttribute('data-service');
const targetEl = document.getElementById('restart-service-target-text');
if (targetEl) targetEl.textContent = pendingRestartService;
openModal('modal-restart-service');
});
});
}
/* ==========================================================================
Pestaña 3: Gestión de Usuarios
========================================================================== */
async function loadUsers() {
const currentUser = store.getState('currentUser');
const tableBody = document.getElementById('users-table-body');
const mobileContainer = document.getElementById('users-mobile-list');
const restrictedNotice = document.getElementById('users-restricted-notice');
// Si no es admin, mostrar pantalla amigable de restricción
if (currentUser?.role !== 'admin') {
if (tableBody) tableBody.closest('.table-glass-card').style.display = 'none';
if (mobileContainer) mobileContainer.style.display = 'none';
if (restrictedNotice) restrictedNotice.style.display = 'flex';
return;
}
if (restrictedNotice) restrictedNotice.style.display = 'none';
if (tableBody) tableBody.closest('.table-glass-card').style.display = 'block';
try {
const users = await api.getUsers();
store.setState({ users });
renderUsers();
} catch (err) {
toast.error('Error al listar operadores', err.message);
}
}
function renderUsers() {
const users = store.getState('users') || [];
const currentUser = store.getState('currentUser');
const tableBody = document.getElementById('users-table-body');
const mobileContainer = document.getElementById('users-mobile-list');
if (tableBody) {
tableBody.innerHTML = users.map(u => {
const isSelf = currentUser && currentUser.id === u.id;
const isImmutable = Boolean(u.isImmutable || u.username === 'root');
return `
<tr>
<td>
<div style="font-weight: 600; display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
<span>${escapeHtml(u.fullName || u.username)}</span>
${isImmutable ? `<span class="badge-immutable">🛡️ SUPERADMIN / ROOT</span>` : ''}
</div>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(u.username)}</div>
</td>
<td>
<span class="user-role-tag role-${u.role}">${escapeHtml(u.role)}</span>
</td>
<td>
<span class="badge ${u.active ? 'badge-status-active' : 'badge-status-disabled'}">
${u.active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td style="font-size: 0.78rem; color: var(--text-muted);">
${u.lastLogin ? new Date(u.lastLogin).toLocaleString() : 'Nunca'}
</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.4rem;">
<button
type="button"
class="btn-icon btn-edit-user"
data-id="${escapeHtml(u.id)}"
${isImmutable ? 'disabled title="El superadministrador root es inmutable y no puede modificarse"' : 'title="Editar Usuario"'}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path>
</svg>
</button>
<button
type="button"
class="btn-icon btn-icon-danger btn-delete-user"
data-id="${escapeHtml(u.id)}"
data-username="${escapeHtml(u.username)}"
${isImmutable
? 'disabled title="El superadministrador root es inmutable y no puede eliminarse"'
: (isSelf ? 'disabled title="No puedes eliminar tu propia cuenta activa"' : 'title="Eliminar Usuario"')
}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</div>
</td>
</tr>
`;
}).join('');
}
// Tarjetas Mobile
if (mobileContainer) {
mobileContainer.innerHTML = users.map(u => {
const isSelf = currentUser && currentUser.id === u.id;
const isImmutable = Boolean(u.isImmutable);
return `
<div class="mobile-card">
<div class="mobile-card-header">
<div>
<div style="font-weight: 600; display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap;">
<span>${escapeHtml(u.fullName || u.username)}</span>
${isImmutable ? `<span class="badge-immutable">[SISTEMA / INMUTABLE]</span>` : ''}
</div>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(u.username)}</div>
</div>
<span class="user-role-tag role-${u.role}">${escapeHtml(u.role)}</span>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-edit-user"
data-id="${escapeHtml(u.id)}"
style="padding: 0.4rem 0.85rem;"
${isImmutable ? 'disabled title="Usuario inmutable"' : ''}
>
Editar
</button>
<button
type="button"
class="btn btn-danger btn-delete-user"
data-id="${escapeHtml(u.id)}"
data-username="${escapeHtml(u.username)}"
${isImmutable || isSelf ? 'disabled' : ''}
style="padding: 0.4rem 0.85rem;"
>
Eliminar
</button>
</div>
</div>
`;
}).join('');
}
attachUserEvents();
}
function attachUserEvents() {
const btnOpenCreateUser = document.getElementById('btn-open-create-user');
if (btnOpenCreateUser) {
btnOpenCreateUser.onclick = () => openCreateUserModal();
}
document.querySelectorAll('.btn-edit-user').forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-id');
openEditUserModal(id);
});
});
document.querySelectorAll('.btn-delete-user').forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-id');
const username = btn.getAttribute('data-username');
confirmDeleteUser(id, username);
});
});
}
function openCreateUserModal() {
const form = document.getElementById('form-user');
const title = document.getElementById('modal-user-title');
const usernameInput = document.getElementById('user-username-input');
const passwordInput = document.getElementById('user-password-input');
const fullNameInput = document.getElementById('user-fullname-input');
const roleSelect = document.getElementById('user-role-select');
const userIdInput = document.getElementById('user-id-hidden');
if (title) title.textContent = 'Crear Nuevo Operador';
if (userIdInput) userIdInput.value = '';
if (usernameInput) {
usernameInput.value = '';
usernameInput.disabled = false;
}
if (passwordInput) {
passwordInput.value = '';
passwordInput.required = true;
passwordInput.placeholder = 'Mínimo 8 caracteres';
}
if (fullNameInput) fullNameInput.value = '';
if (roleSelect) roleSelect.value = 'operator';
openModal('modal-user');
}
function openEditUserModal(userId) {
const users = store.getState('users') || [];
const u = users.find(x => x.id === userId);
if (!u) return;
const title = document.getElementById('modal-user-title');
const usernameInput = document.getElementById('user-username-input');
const passwordInput = document.getElementById('user-password-input');
const fullNameInput = document.getElementById('user-fullname-input');
const roleSelect = document.getElementById('user-role-select');
const userIdInput = document.getElementById('user-id-hidden');
if (title) title.textContent = `Editar Usuario: ${u.username}`;
if (userIdInput) userIdInput.value = u.id;
if (usernameInput) {
usernameInput.value = u.username;
usernameInput.disabled = true; // No modificar username
}
if (passwordInput) {
passwordInput.value = '';
passwordInput.required = false;
passwordInput.placeholder = 'Dejar en blanco para no cambiarla';
}
if (fullNameInput) fullNameInput.value = u.fullName || '';
if (roleSelect) roleSelect.value = u.role || 'operator';
openModal('modal-user');
}
// Envío del Formulario de Usuario
const formUser = document.getElementById('form-user');
if (formUser) {
formUser.addEventListener('submit', async (e) => {
e.preventDefault();
const userId = document.getElementById('user-id-hidden')?.value;
const username = document.getElementById('user-username-input')?.value.trim();
const fullName = document.getElementById('user-fullname-input')?.value.trim();
const password = document.getElementById('user-password-input')?.value;
const role = document.getElementById('user-role-select')?.value;
const btnSubmit = document.getElementById('btn-submit-user');
btnSubmit.disabled = true;
try {
if (!userId) {
// Crear
const userVal = validateUsername(username);
if (!userVal.valid) throw new Error(userVal.error);
const passVal = validatePassword(password);
if (!passVal.valid) throw new Error(passVal.error);
await api.createUser({ username, password, fullName, role });
toast.success('Usuario Creado', `El operador '${username}' ha sido registrado.`);
} else {
// Editar
const updateData = { fullName, role };
if (password) {
const passVal = validatePassword(password);
if (!passVal.valid) throw new Error(passVal.error);
updateData.password = password;
}
await api.updateUser(userId, updateData);
toast.success('Usuario Actualizado', 'Los datos del usuario han sido actualizados.');
}
closeAllModals();
loadUsers();
} catch (err) {
toast.error('Error al procesar usuario', err.detail || err.message);
} finally {
btnSubmit.disabled = false;
}
});
}
async function confirmDeleteUser(id, username) {
if (!confirm(`¿Está seguro de que desea eliminar la cuenta de usuario '${username}'? Esta acción no se puede deshacer.`)) {
return;
}
try {
await api.deleteUser(id);
toast.success('Usuario Eliminado', `La cuenta '${username}' fue eliminada.`);
loadUsers();
} catch (err) {
toast.error('Error al eliminar usuario', err.detail || err.message);
}
}
/* ==========================================================================
Pestaña 4: Documentación Técnica (/docs)
========================================================================== */
async function loadDocs() {
const sidebarNav = document.getElementById('docs-sidebar-nav');
const contentViewer = document.getElementById('docs-content-viewer');
try {
const docs = await api.getDocs();
store.setState({ docs });
renderDocsSidebar(docs);
// Cargar primer documento por defecto si no hay seleccionado
if (docs.length > 0 && !store.getState('selectedDoc')) {
loadDocContent(docs[0].id);
}
} catch (err) {
console.error('Error al cargar índice de documentos:', err);
}
}
function renderDocsSidebar(docs) {
const sidebarNav = document.getElementById('docs-sidebar-nav');
if (!sidebarNav) return;
// Agrupar por categoría
const grouped = {};
docs.forEach(doc => {
const cat = doc.category || 'general';
if (!grouped[cat]) grouped[cat] = [];
grouped[cat].push(doc);
});
const categoryTitles = {
'01-requirements': '1. Requisitos del Sistema (SRS)',
'02-architecture': '2. Arquitectura & Diseño (SDD)',
'03-api': '3. Especificación API REST',
'04-security': '4. Modelo de Seguridad',
'05-deployment': '5. Guía de Despliegue VPS',
'06-user-guides': '6. Manual de Administración',
'general': 'Documentos Generales'
};
let html = '';
for (const [catKey, items] of Object.entries(grouped)) {
const title = categoryTitles[catKey] || catKey.replace(/^\d+-/, '').toUpperCase();
html += `
<div style="margin-bottom: 0.85rem;">
<div class="docs-category-title">${escapeHtml(title)}</div>
<ul class="docs-nav-list">
${items.map(item => `
<li>
<button
type="button"
class="docs-nav-item-btn"
data-doc-id="${escapeHtml(item.id)}"
>
<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 2.5A1.5 1.5 0 0 1 4.5 1h5l4 4v8.5a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 13.5v-11z"></path>
</svg>
<span class="truncate">${escapeHtml(item.title || item.id)}</span>
</button>
</li>
`).join('')}
</ul>
</div>
`;
}
sidebarNav.innerHTML = html;
// Vincular eventos
sidebarNav.querySelectorAll('.docs-nav-item-btn').forEach(btn => {
btn.addEventListener('click', () => {
const docId = btn.getAttribute('data-doc-id');
loadDocContent(docId);
});
});
}
async function loadDocContent(docId) {
const contentViewer = document.getElementById('docs-content-viewer');
if (!contentViewer) return;
// Actualizar clase activa en sidebar
document.querySelectorAll('.docs-nav-item-btn').forEach(b => {
b.classList.toggle('active', b.getAttribute('data-doc-id') === docId);
});
contentViewer.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 3rem;">Cargando documento...</div>`;
try {
const docData = await api.getDoc(docId);
store.setState({ selectedDoc: docData });
const htmlContent = renderMarkdown(docData.content);
contentViewer.innerHTML = `
<div class="docs-header-bar">
<div>
<span class="badge badge-mode-static" style="margin-bottom: 0.4rem;">Doc ID: ${escapeHtml(docData.id)}</span>
<h2 style="font-size: 1.4rem; font-weight: 700;">${escapeHtml(docData.title)}</h2>
</div>
<div style="font-size: 0.76rem; color: var(--text-muted);">
Actualizado: ${new Date(docData.lastModified).toLocaleDateString()}
</div>
</div>
<div class="docs-rendered-body">
${htmlContent}
</div>
`;
// Vincular botones para copiar código en los bloques renderizados
contentViewer.querySelectorAll('.btn-copy-code').forEach(btn => {
btn.addEventListener('click', () => {
const rawCode = decodeURIComponent(btn.getAttribute('data-code'));
navigator.clipboard.writeText(rawCode).then(() => {
const original = btn.innerHTML;
btn.innerHTML = `<span>¡Copiado!</span>`;
setTimeout(() => {
btn.innerHTML = original;
}, 1500);
});
});
});
} catch (err) {
contentViewer.innerHTML = `<div style="color: var(--color-danger); padding: 2rem;">Error al cargar documento: ${escapeHtml(err.message)}</div>`;
}
}
/* ==========================================================================
Temas e Identidad del Sistema (Carga Temprana & Dinámica)
========================================================================== */
let currentThemesList = [];
let currentActiveTheme = null;
let currentIdentity = null;
async function loadIdentityAndThemes() {
try {
const [identity, themesData] = await Promise.all([
api.getIdentity().catch(err => { console.warn('[Identity]', err); return null; }),
api.getThemes().catch(err => { console.warn('[Themes]', err); return null; })
]);
if (identity) {
currentIdentity = identity;
store.setState({ identity });
applyIdentityUI(identity);
}
if (themesData && themesData.themes) {
currentThemesList = themesData.themes;
currentActiveTheme = themesData.activeTheme;
store.setState({
themes: themesData.themes,
activeThemeId: themesData.activeThemeId,
activeTheme: themesData.activeTheme
});
if (themesData.activeTheme?.colors) {
applyThemeVariables(themesData.activeTheme.colors);
}
}
} catch (err) {
console.warn('[Identity & Themes] Error al cargar configuración visual:', err);
}
}
function applyThemeVariables(colors) {
if (!colors || typeof colors !== 'object') return;
const root = document.documentElement;
for (const [key, value] of Object.entries(colors)) {
root.style.setProperty(key, value);
}
// Sincronizar variables estándar utilizadas por componentes
if (colors['--bg-app']) root.style.setProperty('--bg-base', colors['--bg-app']);
if (colors['--accent-primary']) root.style.setProperty('--accent-emerald', colors['--accent-primary']);
if (colors['--accent-lime']) root.style.setProperty('--accent-lime', colors['--accent-lime']);
}
function applyIdentityUI(identity) {
if (!identity) return;
if (identity.appName && identity.panelTitle) {
document.title = `${identity.appName} — ${identity.panelTitle} | ${identity.baseDomain || BASE_DOMAIN}`;
}
const brandName = document.querySelector('.brand-name');
if (brandName && identity.appName) brandName.textContent = identity.appName;
const brandDomain = document.querySelector('.brand-subdomain');
if (brandDomain && identity.baseDomain) brandDomain.textContent = identity.baseDomain;
const footerText = document.getElementById('footer-text-display');
if (footerText && identity.footerText) footerText.textContent = identity.footerText;
const footerSlogan = document.getElementById('footer-slogan-display');
if (footerSlogan && identity.slogan) footerSlogan.textContent = identity.slogan;
const footerGit = document.getElementById('footer-git-link');
if (footerGit && identity.gitUrl) {
footerGit.href = identity.gitUrl;
footerGit.textContent = `Repositorio Git (${identity.appName || 'a2host'})`;
}
if (identity.primaryColor) {
document.documentElement.style.setProperty('--accent-emerald', identity.primaryColor);
document.documentElement.style.setProperty('--accent-primary', identity.primaryColor);
}
}
/* ==========================================================================
Pestaña Proyectos (/var/www/<proyecto>)
========================================================================== */
let currentEditProjectId = null;
let currentLinkProjectId = null;
let currentDeleteProjectId = null;
function setupProjects() {
const searchInput = document.getElementById('search-projects');
const typeFilter = document.getElementById('filter-project-type');
const btnRefresh = document.getElementById('btn-refresh-projects');
const btnOpenCreate = document.getElementById('btn-open-create-project');
const formProject = document.getElementById('form-project');
const formLinkSubdomain = document.getElementById('form-link-subdomain');
const btnConfirmDeleteProject = document.getElementById('btn-confirm-delete-project');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
const filter = store.getState('projectsFilter') || {};
store.setState({ projectsFilter: { ...filter, search: e.target.value.trim() } });
renderProjects();
});
}
if (typeFilter) {
typeFilter.addEventListener('change', (e) => {
const filter = store.getState('projectsFilter') || {};
store.setState({ projectsFilter: { ...filter, type: e.target.value } });
renderProjects();
});
}
if (btnRefresh) {
btnRefresh.addEventListener('click', loadProjects);
}
if (btnOpenCreate) {
btnOpenCreate.addEventListener('click', openCreateProjectModal);
}
// Radios de selección de tipo de proyecto en modal
document.querySelectorAll('input[name="project-type"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const type = e.target.value;
const portGroup = document.getElementById('form-group-project-port');
if (portGroup) {
portGroup.style.display = (type === 'node' || type === 'python' || type === 'custom') ? 'block' : 'none';
}
updateDocRootPreview();
});
});
const projNameInput = document.getElementById('project-name-input');
const projPublicFolderInput = document.getElementById('project-public-folder-input');
if (projNameInput) {
projNameInput.addEventListener('input', updateDocRootPreview);
}
if (projPublicFolderInput) {
projPublicFolderInput.addEventListener('input', updateDocRootPreview);
}
// Submit Crear / Editar Proyecto
if (formProject) {
formProject.addEventListener('submit', handleSaveProject);
}
// Modal Vincular Subdominio
const linkSubInput = document.getElementById('link-subdomain-name-input');
if (linkSubInput) {
linkSubInput.addEventListener('input', (e) => {
const clean = e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '');
const preview = document.getElementById('link-subdomain-preview-url');
if (preview) {
preview.textContent = clean ? `${clean}.${currentIdentity?.baseDomain || BASE_DOMAIN}` : `subdominio.${currentIdentity?.baseDomain || BASE_DOMAIN}`;
}
});
}
if (formLinkSubdomain) {
formLinkSubdomain.addEventListener('submit', handleSaveLinkSubdomain);
}
if (btnConfirmDeleteProject) {
btnConfirmDeleteProject.addEventListener('click', handleConfirmDeleteProject);
}
}
function updateDocRootPreview() {
const nameInput = document.getElementById('project-name-input');
const folderInput = document.getElementById('project-public-folder-input');
const preview = document.getElementById('preview-project-docroot');
if (!preview) return;
const name = nameInput?.value.trim() || 'mi-super-app';
const folder = folderInput?.value.trim().replace(/^\/+/, '');
preview.textContent = folder ? `/var/www/${name}/${folder}` : `/var/www/${name}`;
}
async function loadProjects() {
store.setState({ projectsLoading: true });
try {
const list = await api.getProjects();
store.setState({ projects: list, projectsLoading: false });
const badge = document.getElementById('projects-count-badge');
if (badge) badge.textContent = list.length;
renderProjects();
updateProjectSelects(list);
} catch (err) {
store.setState({ projectsLoading: false });
toast.error('Error al cargar proyectos', err.message);
}
}
function updateProjectSelects(projects) {
const bulkSelect = document.getElementById('ftp-bulk-project-select');
const ftpAccSelect = document.getElementById('ftp-project-select');
if (bulkSelect) {
const curVal = bulkSelect.value;
bulkSelect.innerHTML = `<option value="">-- Selecciona un Proyecto --</option>` +
projects.map(p => `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)} (${escapeHtml(p.type)})</option>`).join('');
if (curVal) bulkSelect.value = curVal;
}
if (ftpAccSelect) {
const curVal = ftpAccSelect.value;
ftpAccSelect.innerHTML = `<option value="">Todos los Proyectos (/var/www)</option>` +
projects.map(p => `<option value="${escapeHtml(p.name)}">/var/www/${escapeHtml(p.name)}</option>`).join('');
if (curVal) ftpAccSelect.value = curVal;
}
}
function renderProjects() {
const projects = store.getState('projects') || [];
const filter = store.getState('projectsFilter') || {};
const grid = document.getElementById('projects-grid');
const emptyState = document.getElementById('projects-empty-state');
if (!grid) return;
const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN;
const filtered = projects.filter(p => {
if (filter.search) {
const q = filter.search.toLowerCase();
const matchName = p.name.toLowerCase().includes(q);
const matchSubs = (p.subdomains || []).some(s => s.toLowerCase().includes(q));
if (!matchName && !matchSubs) return false;
}
if (filter.type && filter.type !== 'all') {
if (p.type !== filter.type) return false;
}
return true;
});
if (filtered.length === 0) {
grid.innerHTML = '';
if (emptyState) emptyState.style.display = 'flex';
return;
}
if (emptyState) emptyState.style.display = 'none';
grid.innerHTML = filtered.map(proj => {
const typeLabels = {
static: 'Estático / PHP',
node: 'Node.js',
python: 'Python',
custom: 'Proxy Inverso'
};
const typeLabel = typeLabels[proj.type] || proj.type;
const typeTagClass = `type-tag-${proj.type || 'static'}`;
const subdomainsList = proj.subdomains || [];
const publicFolderDisplay = proj.publicFolder ? `/${proj.publicFolder.replace(/^\/+/, '')}` : 'Raíz (/)';
return `
<div class="project-card" data-project-id="${escapeHtml(proj.id)}">
<div>
<div class="project-card-header">
<div class="project-title-group">
<div class="project-icon-badge" aria-hidden="true">
${proj.type === 'node'
? `<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2 3 14h6l-2 6 10-12h-6l2-6z"></path></svg>`
: proj.type === 'python'
? `<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="m5 7 5-5 5 5M5 13l5 5 5-5"></path></svg>`
: `<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7l7-4 7 4-7 4-7-4zM3 13l7 4 7-4M3 10l7 4 7-4"></path></svg>`
}
</div>
<div>
<h4 class="project-name">${escapeHtml(proj.name)}</h4>
<span style="font-size: 0.72rem; color: var(--text-muted); font-family: ui-monospace, monospace;">
/var/www/${escapeHtml(proj.name)}
</span>
</div>
</div>
<span class="project-type-tag ${typeTagClass}">${escapeHtml(typeLabel)}</span>
</div>
<div class="project-meta-box" style="margin-top: 0.85rem;">
<div class="project-meta-row">
<span class="project-meta-label">Carpeta Pública:</span>
<strong class="project-meta-value">${escapeHtml(publicFolderDisplay)}</strong>
</div>
${proj.port ? `
<div class="project-meta-row">
<span class="project-meta-label">Puerto Proxy:</span>
<span class="badge badge-port">127.0.0.1:${escapeHtml(proj.port)}</span>
</div>
` : ''}
<div class="project-meta-row">
<span class="project-meta-label">Estado en Disco:</span>
<span class="badge ${proj.existsOnDisk ? 'badge-status-active' : 'badge-status-disabled'}">
${proj.existsOnDisk ? 'Directorio OK' : 'No Encontrado'}
</span>
</div>
</div>
<div class="project-subdomains-section" style="margin-top: 1rem;">
<span class="project-subdomains-title">Subdominios Vinculados (${subdomainsList.length})</span>
<div class="project-subdomains-list">
${subdomainsList.length > 0 ? subdomainsList.map(sub => `
<span class="subdomain-chip">
<a class="subdomain-chip-link" href="https://${escapeHtml(sub)}.${escapeHtml(baseDom)}" target="_blank" rel="noopener noreferrer" title="Abrir https://${escapeHtml(sub)}.${escapeHtml(baseDom)}">
<span>🌐 ${escapeHtml(sub)}.${escapeHtml(baseDom)}</span>
<svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 3h7v7M13 3 7 9"></path></svg>
</a>
<button type="button" class="subdomain-chip-remove btn-remove-proj-sub" data-project-id="${escapeHtml(proj.id)}" data-subdomain="${escapeHtml(sub)}" title="Desvincular subdominio">&times;</button>
</span>
`).join('') : `<span class="text-xs text-muted" style="font-style: italic;">Sin subdominios vinculados aún</span>`}
</div>
</div>
</div>
<div class="project-actions-bar">
<div class="project-actions-left">
<button type="button" class="btn btn-secondary btn-sm btn-project-add-sub" data-project-id="${escapeHtml(proj.id)}" data-project-name="${escapeHtml(proj.name)}">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 3v10M3 8h10"></path></svg>
<span>+ Subdominio</span>
</button>
<button type="button" class="btn btn-secondary btn-sm btn-project-files" data-project-name="${escapeHtml(proj.name)}" title="Abrir Gestor de Archivos">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 4a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-6l-2-2H3z"></path></svg>
<span>Archivos</span>
</button>
</div>
<div class="project-actions-right">
<button type="button" class="btn btn-secondary btn-sm btn-project-edit" data-project-id="${escapeHtml(proj.id)}" title="Editar Configuración">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path></svg>
<span>Editar</span>
</button>
<button type="button" class="btn btn-danger btn-sm btn-project-delete" data-project-id="${escapeHtml(proj.id)}" data-project-name="${escapeHtml(proj.name)}" title="Eliminar Proyecto">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path></svg>
<span>Eliminar</span>
</button>
</div>
</div>
</div>
`;
}).join('');
// Vincular eventos delegados en tarjetas
grid.querySelectorAll('.btn-project-add-sub').forEach(b => {
b.addEventListener('click', () => {
const id = b.getAttribute('data-project-id');
const name = b.getAttribute('data-project-name');
openLinkSubdomainModal({ id, name });
});
});
grid.querySelectorAll('.btn-project-edit').forEach(b => {
b.addEventListener('click', () => {
const id = b.getAttribute('data-project-id');
const proj = projects.find(p => p.id === id);
if (proj) openEditProjectModal(proj);
});
});
grid.querySelectorAll('.btn-project-files').forEach(b => {
b.addEventListener('click', () => {
const name = b.getAttribute('data-project-name');
if (name) openFileManager(name);
});
});
grid.querySelectorAll('.btn-project-delete').forEach(b => {
b.addEventListener('click', () => {
const id = b.getAttribute('data-project-id');
const name = b.getAttribute('data-project-name');
openDeleteProjectModal({ id, name });
});
});
grid.querySelectorAll('.btn-remove-proj-sub').forEach(b => {
b.addEventListener('click', () => {
const id = b.getAttribute('data-project-id');
const sub = b.getAttribute('data-subdomain');
handleRemoveProjectSubdomain(id, sub);
});
});
}
function openCreateProjectModal() {
currentEditProjectId = null;
const modal = document.getElementById('modal-project');
const title = document.getElementById('modal-project-title');
const idInput = document.getElementById('project-id-hidden');
const nameInput = document.getElementById('project-name-input');
const folderInput = document.getElementById('project-public-folder-input');
const portInput = document.getElementById('project-port-input');
const subInput = document.getElementById('project-subdomains-input');
const subGroup = document.getElementById('form-group-project-subdomains');
const portGroup = document.getElementById('form-group-project-port');
if (title) title.textContent = 'Crear Nuevo Proyecto';
if (idInput) idInput.value = '';
if (nameInput) {
nameInput.value = '';
nameInput.disabled = false;
}
if (folderInput) folderInput.value = '';
if (portInput) portInput.value = '';
if (subInput) subInput.value = '';
if (subGroup) subGroup.style.display = 'block';
if (portGroup) portGroup.style.display = 'none';
const defaultRadio = document.querySelector('input[name="project-type"][value="static"]');
if (defaultRadio) defaultRadio.checked = true;
updateDocRootPreview();
openModal('modal-project');
}
function openEditProjectModal(proj) {
currentEditProjectId = proj.id;
const modal = document.getElementById('modal-project');
const title = document.getElementById('modal-project-title');
const idInput = document.getElementById('project-id-hidden');
const nameInput = document.getElementById('project-name-input');
const folderInput = document.getElementById('project-public-folder-input');
const portInput = document.getElementById('project-port-input');
const subGroup = document.getElementById('form-group-project-subdomains');
const portGroup = document.getElementById('form-group-project-port');
if (title) title.textContent = `Editar Proyecto: ${proj.name}`;
if (idInput) idInput.value = proj.id;
if (nameInput) {
nameInput.value = proj.name;
nameInput.disabled = true; // El nombre del directorio raíz es inmutable en edición
}
if (folderInput) folderInput.value = proj.publicFolder || '';
if (portInput) portInput.value = proj.port || '';
if (subGroup) subGroup.style.display = 'none';
const targetRadio = document.querySelector(`input[name="project-type"][value="${proj.type || 'static'}"]`);
if (targetRadio) targetRadio.checked = true;
if (portGroup) {
portGroup.style.display = (proj.type === 'node' || proj.type === 'python' || proj.type === 'custom') ? 'block' : 'none';
}
updateDocRootPreview();
openModal('modal-project');
}
async function handleSaveProject(e) {
e.preventDefault();
const id = document.getElementById('project-id-hidden')?.value;
const typeRadio = document.querySelector('input[name="project-type"]:checked');
const type = typeRadio ? typeRadio.value : 'static';
const publicFolder = document.getElementById('project-public-folder-input')?.value.trim();
const portVal = document.getElementById('project-port-input')?.value;
const port = portVal ? Number(portVal) : undefined;
const btnSubmit = document.getElementById('btn-submit-project');
if (btnSubmit) btnSubmit.disabled = true;
try {
if (id) {
// Edición
await api.updateProject(id, { type, publicFolder, port });
toast.success('Proyecto actualizado', 'Configuración guardada exitosamente.');
} else {
// Creación
const name = document.getElementById('project-name-input')?.value.trim();
if (!name) {
toast.error('Nombre requerido', 'Ingresa el nombre del proyecto.');
return;
}
const subVal = document.getElementById('project-subdomains-input')?.value.trim();
const subdomains = subVal ? [subVal] : [];
await api.createProject({ name, type, publicFolder, port, subdomains });
toast.success('Proyecto creado', `El proyecto '${name}' fue inicializado exitosamente.`);
}
closeAllModals();
await loadProjects();
await loadSubdomains();
await loadFolders();
} catch (err) {
toast.error('Error al guardar proyecto', err.detail || err.message);
} finally {
if (btnSubmit) btnSubmit.disabled = false;
}
}
function openLinkSubdomainModal(proj) {
currentLinkProjectId = proj.id;
const modal = document.getElementById('modal-link-subdomain');
const title = document.getElementById('modal-link-subdomain-title');
const idInput = document.getElementById('link-project-id-hidden');
const nameInput = document.getElementById('link-subdomain-name-input');
const preview = document.getElementById('link-subdomain-preview-url');
const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN;
if (title) title.textContent = `Vincular Subdominio a: ${proj.name}`;
if (idInput) idInput.value = proj.id;
if (nameInput) nameInput.value = '';
if (preview) preview.textContent = `subdominio.${baseDom}`;
openModal('modal-link-subdomain');
}
async function handleSaveLinkSubdomain(e) {
e.preventDefault();
const projectId = document.getElementById('link-project-id-hidden')?.value;
const subdomain = document.getElementById('link-subdomain-name-input')?.value.trim().toLowerCase();
if (!projectId || !subdomain) {
toast.error('Subdominio requerido', 'Ingresa el nombre del subdominio.');
return;
}
const btnSubmit = document.getElementById('btn-submit-link-subdomain');
if (btnSubmit) btnSubmit.disabled = true;
try {
await api.addProjectSubdomain(projectId, subdomain);
const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN;
toast.success('Subdominio vinculado', `https://${subdomain}.${baseDom} activo en Apache.`);
closeAllModals();
await loadProjects();
await loadSubdomains();
} catch (err) {
toast.error('Error al vincular subdominio', err.detail || err.message);
} finally {
if (btnSubmit) btnSubmit.disabled = false;
}
}
async function handleRemoveProjectSubdomain(projectId, subdomain) {
if (!confirm(`¿Desvincular el subdominio '${subdomain}' de este proyecto? Se eliminará su VirtualHost de Apache.`)) {
return;
}
try {
await api.removeProjectSubdomain(projectId, subdomain);
toast.info('Subdominio desvinculado', subdomain);
await loadProjects();
await loadSubdomains();
} catch (err) {
toast.error('Error al desvincular subdominio', err.detail || err.message);
}
}
function openDeleteProjectModal(proj) {
currentDeleteProjectId = proj.id;
const nameDisplay = document.getElementById('delete-project-name-display');
const chk = document.getElementById('chk-delete-project-files');
if (nameDisplay) nameDisplay.textContent = proj.name;
if (chk) chk.checked = false;
openModal('modal-delete-project');
}
async function handleConfirmDeleteProject() {
if (!currentDeleteProjectId) return;
const chk = document.getElementById('chk-delete-project-files');
const deleteFiles = Boolean(chk?.checked);
const btn = document.getElementById('btn-confirm-delete-project');
if (btn) btn.disabled = true;
try {
const res = await api.deleteProject(currentDeleteProjectId, deleteFiles);
toast.success('Proyecto eliminado', res?.message || 'VirtualHosts eliminados.');
closeAllModals();
await loadProjects();
await loadSubdomains();
await loadFolders();
} catch (err) {
toast.error('Error al eliminar proyecto', err.detail || err.message);
} finally {
if (btn) btn.disabled = false;
}
}
/* ==========================================================================
Pestaña Gestión FTP & Carga Masiva (Bulk Upload)
========================================================================== */
let selectedZipFile = null;
function setupFtp() {
const btnOpenCreateAcc = document.getElementById('btn-open-create-ftp-account');
const formFtpAcc = document.getElementById('form-ftp-account');
const dropZone = document.getElementById('ftp-drop-zone');
const zipInput = document.getElementById('ftp-zip-input');
const btnRemoveFile = document.getElementById('ftp-btn-remove-file');
const formBulk = document.getElementById('form-bulk-upload');
if (btnOpenCreateAcc) {
btnOpenCreateAcc.addEventListener('click', openCreateFtpAccountModal);
}
if (formFtpAcc) {
formFtpAcc.addEventListener('submit', handleSaveFtpAccount);
}
// Copiado de credenciales
document.querySelectorAll('.btn-copy-mini').forEach(b => {
b.addEventListener('click', () => {
const text = b.getAttribute('data-copy');
if (text) {
navigator.clipboard.writeText(text).then(() => {
toast.success('Copiado', text);
});
}
});
});
// Drag & Drop para archivo .zip
if (dropZone && zipInput) {
dropZone.addEventListener('click', () => zipInput.click());
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
handleZipFileSelected(e.dataTransfer.files[0]);
}
});
zipInput.addEventListener('change', (e) => {
if (e.target.files && e.target.files.length > 0) {
handleZipFileSelected(e.target.files[0]);
}
});
}
if (btnRemoveFile) {
btnRemoveFile.addEventListener('click', () => {
selectedZipFile = null;
if (zipInput) zipInput.value = '';
const wrap = document.getElementById('ftp-selected-file-wrap');
const btnExtract = document.getElementById('btn-extract-zip');
if (wrap) wrap.style.display = 'none';
if (btnExtract) btnExtract.disabled = true;
});
}
if (formBulk) {
formBulk.addEventListener('submit', handleExtractBulkZip);
}
}
function handleZipFileSelected(file) {
if (!file.name.toLowerCase().endsWith('.zip')) {
toast.error('Formato inválido', 'Por favor selecciona un archivo comprimido .zip');
return;
}
selectedZipFile = file;
const wrap = document.getElementById('ftp-selected-file-wrap');
const nameEl = document.getElementById('ftp-selected-file-name');
const sizeEl = document.getElementById('ftp-selected-file-size');
const btnExtract = document.getElementById('btn-extract-zip');
if (nameEl) nameEl.textContent = file.name;
if (sizeEl) sizeEl.textContent = `${Math.round(file.size / 1024)} KB`;
if (wrap) wrap.style.display = 'flex';
if (btnExtract) btnExtract.disabled = false;
}
async function handleExtractBulkZip(e) {
e.preventDefault();
const project = document.getElementById('ftp-bulk-project-select')?.value;
const subpath = document.getElementById('ftp-bulk-subpath-input')?.value.trim();
const statusEl = document.getElementById('ftp-extract-status');
if (!project) {
toast.error('Proyecto requerido', 'Selecciona el proyecto de destino para extraer el ZIP.');
return;
}
if (!selectedZipFile) {
toast.error('Archivo ZIP requerido', 'Selecciona o arrastra un archivo .zip.');
return;
}
const btnExtract = document.getElementById('btn-extract-zip');
if (btnExtract) {
btnExtract.disabled = true;
btnExtract.innerHTML = `<span>Descomprimiendo y configurando permisos...</span>`;
}
try {
const reader = new FileReader();
reader.readAsDataURL(selectedZipFile);
reader.onload = async () => {
try {
const base64Data = String(reader.result).replace(/^data:.*?;base64,/, '');
const res = await api.extractZipToProject(project, subpath, base64Data);
if (statusEl) {
statusEl.className = 'extract-status-banner success';
statusEl.textContent = `✅ Éxito: Archivo ZIP extraído en ${res.extractedTo || `/var/www/${project}`}. Acceso Web Óptimo configurado para todo el contenido.`;
statusEl.style.display = 'block';
}
toast.success('Descompresión Exitosa', `Archivos extraídos en /var/www/${project}`);
await loadFolders();
} catch (extractErr) {
if (statusEl) {
statusEl.className = 'extract-status-banner error';
statusEl.textContent = `❌ Error: ${extractErr.detail || extractErr.message}`;
statusEl.style.display = 'block';
}
toast.error('Fallo de extracción', extractErr.message);
} finally {
if (btnExtract) {
btnExtract.disabled = false;
btnExtract.innerHTML = `
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 2v10M3 7l5 5 5-5M2 14h12"></path>
</svg>
<span>Subir y Descomprimir (Acceso Web Óptimo)</span>
`;
}
}
};
} catch (err) {
toast.error('Error al leer archivo', err.message);
if (btnExtract) btnExtract.disabled = false;
}
}
async function loadFtpData() {
try {
const [info, accounts] = await Promise.all([
api.getFtpInfo().catch(() => null),
api.getFtpAccounts().catch(() => [])
]);
if (info) {
store.setState({ ftpInfo: info });
const hostEl = document.getElementById('ftp-info-host');
const ipEl = document.getElementById('ftp-info-ip');
const userEl = document.getElementById('ftp-info-user');
if (hostEl) hostEl.textContent = info.host;
if (ipEl) ipEl.textContent = info.ip;
const displayUser = (info.systemUser && info.systemUser.toLowerCase() !== 'ggc') ? info.systemUser : 'ftp';
if (userEl) userEl.textContent = displayUser;
}
store.setState({ ftpAccounts: accounts || [] });
renderFtpAccounts(accounts || []);
} catch (err) {
console.warn('[FTP] Error al cargar datos FTP:', err);
}
}
function renderFtpAccounts(accounts) {
const tbody = document.getElementById('ftp-accounts-table-body');
const mobileList = document.getElementById('ftp-accounts-mobile-list');
const emptyState = document.getElementById('ftp-accounts-empty-state');
if (!tbody) return;
if (!accounts || accounts.length === 0) {
tbody.innerHTML = '';
if (mobileList) mobileList.innerHTML = '';
if (emptyState) emptyState.style.display = 'flex';
return;
}
if (emptyState) emptyState.style.display = 'none';
tbody.innerHTML = accounts.map(acc => `
<tr>
<td>
<strong style="color: var(--text-primary); font-family: ui-monospace, monospace;">${escapeHtml(acc.username)}</strong>
</td>
<td>
<span style="font-size: 0.82rem; color: var(--accent-lime); font-family: ui-monospace, monospace;">
${escapeHtml(acc.project || 'Todos')}
</span>
</td>
<td>
<span class="badge ${acc.permission === 'rw' ? 'badge-mode-static' : 'badge-mode-proxy'}">
${acc.permission === 'rw' ? 'Lectura y Escritura (rw)' : 'Solo Lectura (ro)'}
</span>
</td>
<td>
<span class="badge ${acc.active ? 'badge-status-active' : 'badge-status-disabled'}">
${acc.active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td style="font-size: 0.78rem; color: var(--text-muted);">
${new Date(acc.createdAt).toLocaleDateString()}
</td>
<td style="text-align: right;">
<button type="button" class="btn-icon btn-icon-danger btn-delete-ftp-acc" data-id="${escapeHtml(acc.id)}" data-username="${escapeHtml(acc.username)}" title="Eliminar Cuenta FTP">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</td>
</tr>
`).join('');
// Mobile
if (mobileList) {
mobileList.innerHTML = accounts.map(acc => `
<div class="mobile-subdomain-card">
<div style="display: flex; justify-content: space-between; align-items: center;">
<strong style="font-family: ui-monospace, monospace;">${escapeHtml(acc.username)}</strong>
<span class="badge ${acc.active ? 'badge-status-active' : 'badge-status-disabled'}">
${acc.active ? 'Activo' : 'Inactivo'}
</span>
</div>
<div class="mobile-card-row" style="margin-top: 0.4rem;">
<span class="mobile-card-label">Ruta:</span>
<span>${escapeHtml(acc.project || '/var/www')}</span>
</div>
<div class="mobile-card-row">
<span class="mobile-card-label">Permisos:</span>
<span>${acc.permission === 'rw' ? 'rw (Lectura/Escritura)' : 'ro (Solo lectura)'}</span>
</div>
<div class="mobile-card-actions" style="margin-top: 0.6rem;">
<button type="button" class="btn btn-danger btn-sm btn-delete-ftp-acc" data-id="${escapeHtml(acc.id)}" data-username="${escapeHtml(acc.username)}">
Eliminar Cuenta
</button>
</div>
</div>
`).join('');
}
// Delegación de eliminar cuenta FTP
document.querySelectorAll('.btn-delete-ftp-acc').forEach(b => {
b.addEventListener('click', () => {
const id = b.getAttribute('data-id');
const username = b.getAttribute('data-username');
handleDeleteFtpAccount(id, username);
});
});
}
function openCreateFtpAccountModal() {
const form = document.getElementById('form-ftp-account');
if (form) form.reset();
const idInput = document.getElementById('ftp-account-id-hidden');
if (idInput) idInput.value = '';
openModal('modal-ftp-account');
}
async function handleSaveFtpAccount(e) {
e.preventDefault();
const username = document.getElementById('ftp-username-input')?.value.trim();
const password = document.getElementById('ftp-password-input')?.value;
const project = document.getElementById('ftp-project-select')?.value;
const permission = document.getElementById('ftp-permission-select')?.value;
if (!username || !password) {
toast.error('Campos obligatorios', 'Ingresa usuario y contraseña.');
return;
}
const btnSubmit = document.getElementById('btn-submit-ftp-account');
if (btnSubmit) btnSubmit.disabled = true;
try {
await api.createFtpAccount({ username, password, project, permission });
toast.success('Cuenta FTP Creada', `Usuario '${username}' registrado.`);
closeAllModals();
await loadFtpData();
} catch (err) {
toast.error('Error al crear cuenta FTP', err.detail || err.message);
} finally {
if (btnSubmit) btnSubmit.disabled = false;
}
}
async function handleDeleteFtpAccount(id, username) {
if (!confirm(`¿Eliminar la cuenta FTP '${username}'? Ya no podrá autenticarse.`)) return;
try {
await api.deleteFtpAccount(id);
toast.success('Cuenta eliminada', username);
await loadFtpData();
} catch (err) {
toast.error('Error al eliminar cuenta', err.detail || err.message);
}
}
/* ==========================================================================
Pestaña 8: Configuraciones (Usuarios, Temas, Identidad)
========================================================================== */
function setupSettings() {
// Botones de Subnavegación
const subnavBtns = document.querySelectorAll('.settings-subnav-btn');
subnavBtns.forEach(btn => {
btn.addEventListener('click', () => {
const target = btn.getAttribute('data-subtab');
switchSettingsSubtab(target);
});
});
// Editor JSON de Temas
const btnExport = document.getElementById('btn-export-theme-json');
const btnImport = document.getElementById('btn-import-theme-json');
const fileInput = document.getElementById('theme-file-input');
const btnReset = document.getElementById('btn-reset-theme');
const btnSaveCustom = document.getElementById('btn-save-custom-theme');
if (btnExport) {
btnExport.addEventListener('click', handleExportThemeJson);
}
if (btnImport && fileInput) {
btnImport.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleImportThemeFile);
}
if (btnReset) {
btnReset.addEventListener('click', handleResetTheme);
}
if (btnSaveCustom) {
btnSaveCustom.addEventListener('click', handleSaveCustomTheme);
}
// Formulario de Identidad
const colorPicker = document.getElementById('identity-primary-color');
const hexInput = document.getElementById('identity-primary-hex');
if (colorPicker && hexInput) {
colorPicker.addEventListener('input', (e) => {
hexInput.value = e.target.value;
});
hexInput.addEventListener('input', (e) => {
if (/^#[0-9a-f]{6}$/i.test(e.target.value)) {
colorPicker.value = e.target.value;
}
});
}
const formIdentity = document.getElementById('form-identity');
if (formIdentity) {
formIdentity.addEventListener('submit', handleSaveIdentity);
}
}
function switchSettingsSubtab(subtabName) {
store.setState({ settingsSubtab: subtabName });
document.querySelectorAll('.settings-subnav-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-subtab') === subtabName);
});
const panels = {
users: document.getElementById('settings-panel-users'),
themes: document.getElementById('settings-panel-themes'),
identity: document.getElementById('settings-panel-identity')
};
for (const [key, el] of Object.entries(panels)) {
if (el) el.style.display = (key === subtabName) ? 'block' : 'none';
}
if (subtabName === 'users') loadUsers();
if (subtabName === 'themes') loadThemes();
if (subtabName === 'identity') loadIdentity();
}
function loadSettingsTab() {
const sub = store.getState('settingsSubtab') || 'users';
switchSettingsSubtab(sub);
}
async function loadThemes() {
try {
const data = await api.getThemes();
currentThemesList = data.themes || [];
currentActiveTheme = data.activeTheme;
renderThemesGallery(currentThemesList, data.activeThemeId);
const textarea = document.getElementById('theme-json-textarea');
if (textarea && currentActiveTheme) {
textarea.value = JSON.stringify(currentActiveTheme, null, 2);
}
} catch (err) {
toast.error('Error al cargar temas', err.message);
}
}
function renderThemesGallery(themes, activeThemeId) {
const grid = document.getElementById('themes-gallery-grid');
if (!grid) return;
grid.innerHTML = themes.map(t => {
const isActive = t.id === activeThemeId;
const colors = t.colors || {};
const cBgApp = colors['--bg-app'] || '#080c08';
const cBgSurface = colors['--bg-surface'] || '#0f141f';
const cPrimary = colors['--accent-primary'] || '#10b981';
const cLime = colors['--accent-lime'] || '#a3e635';
return `
<div class="theme-card ${isActive ? 'active' : ''}">
<div>
<div class="theme-card-top">
<h4 class="theme-name">${escapeHtml(t.name)}</h4>
${isActive ? `<span class="badge badge-status-active">Activo</span>` : ''}
</div>
<p class="theme-card-desc" style="margin-top: 0.35rem;">${escapeHtml(t.description || '')}</p>
<div class="theme-swatches-row">
<span class="theme-swatch" style="background: ${escapeHtml(cBgApp)};" title="Fondo App (${escapeHtml(cBgApp)})"></span>
<span class="theme-swatch" style="background: ${escapeHtml(cBgSurface)};" title="Superficie (${escapeHtml(cBgSurface)})"></span>
<span class="theme-swatch" style="background: ${escapeHtml(cPrimary)};" title="Primario (${escapeHtml(cPrimary)})"></span>
<span class="theme-swatch" style="background: ${escapeHtml(cLime)};" title="Acento (${escapeHtml(cLime)})"></span>
</div>
</div>
<div class="theme-card-footer">
<span style="font-size: 0.72rem; color: var(--text-muted); font-family: ui-monospace, monospace;">${escapeHtml(t.id)}</span>
<button type="button" class="btn ${isActive ? 'btn-secondary' : 'btn-primary'} btn-sm btn-apply-theme" data-theme-id="${escapeHtml(t.id)}" ${isActive ? 'disabled' : ''}>
${isActive ? '✓ Seleccionado' : 'Activar Tema'}
</button>
</div>
</div>
`;
}).join('');
grid.querySelectorAll('.btn-apply-theme').forEach(b => {
b.addEventListener('click', async () => {
const themeId = b.getAttribute('data-theme-id');
try {
const res = await api.setActiveTheme(themeId);
const active = res.activeTheme || res.data?.activeTheme;
if (active) {
currentActiveTheme = active;
applyThemeVariables(active.colors);
toast.success('Tema aplicado', active.name);
await loadThemes();
}
} catch (err) {
toast.error('Error al aplicar tema', err.message);
}
});
});
}
function handleExportThemeJson() {
if (!currentActiveTheme) return;
const jsonStr = JSON.stringify(currentActiveTheme, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${currentActiveTheme.id || 'theme'}.json`;
a.click();
URL.revokeObjectURL(url);
toast.success('Archivo exportado', `${currentActiveTheme.id}.json`);
}
function handleImportThemeFile(e) {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
try {
const parsed = JSON.parse(reader.result);
const res = await api.importThemeJson(parsed);
const imported = res.theme || res.data?.theme || parsed;
currentActiveTheme = imported;
applyThemeVariables(imported.colors);
toast.success('Tema importado', imported.name || 'Personalizado');
await loadThemes();
} catch (err) {
toast.error('Error al importar tema', err.message);
}
};
reader.readAsText(file);
}
async function handleResetTheme() {
if (!confirm('¿Restaurar el tema visual a los valores por defecto (Obsidian Emerald)?')) return;
try {
const res = await api.resetTheme();
const active = res.activeTheme || res.data?.activeTheme;
if (active) {
currentActiveTheme = active;
applyThemeVariables(active.colors);
toast.success('Tema restaurado', 'Obsidian Emerald por defecto');
await loadThemes();
}
} catch (err) {
toast.error('Error al restaurar tema', err.message);
}
}
async function handleSaveCustomTheme() {
const textarea = document.getElementById('theme-json-textarea');
if (!textarea) return;
try {
const parsed = JSON.parse(textarea.value);
const res = await api.saveCustomTheme(parsed);
const saved = res.theme || res.data?.theme || parsed;
currentActiveTheme = saved;
applyThemeVariables(saved.colors);
toast.success('Tema guardado', saved.name);
await loadThemes();
} catch (err) {
toast.error('JSON inválido o error', err.message);
}
}
async function loadIdentity() {
try {
const identity = await api.getIdentity();
currentIdentity = identity;
const appNameEl = document.getElementById('identity-app-name');
const panelTitleEl = document.getElementById('identity-panel-title');
const sloganEl = document.getElementById('identity-slogan');
const baseDomainEl = document.getElementById('identity-base-domain');
const gitUrlEl = document.getElementById('identity-git-url');
const footerTextEl = document.getElementById('identity-footer-text');
const logoIconEl = document.getElementById('identity-logo-icon');
const primaryColorEl = document.getElementById('identity-primary-color');
const primaryHexEl = document.getElementById('identity-primary-hex');
if (appNameEl) appNameEl.value = identity.appName || 'a2host';
if (panelTitleEl) panelTitleEl.value = identity.panelTitle || '';
if (sloganEl) sloganEl.value = identity.slogan || '';
if (baseDomainEl) baseDomainEl.value = identity.baseDomain || BASE_DOMAIN;
if (gitUrlEl) gitUrlEl.value = identity.gitUrl || '';
if (footerTextEl) footerTextEl.value = identity.footerText || '';
if (logoIconEl) logoIconEl.value = identity.logoIcon || 'server';
if (primaryColorEl) primaryColorEl.value = identity.primaryColor || '#10b981';
if (primaryHexEl) primaryHexEl.value = identity.primaryColor || '#10b981';
} catch (err) {
toast.error('Error al cargar identidad', err.message);
}
}
async function handleSaveIdentity(e) {
e.preventDefault();
const payload = {
appName: document.getElementById('identity-app-name')?.value.trim(),
panelTitle: document.getElementById('identity-panel-title')?.value.trim(),
slogan: document.getElementById('identity-slogan')?.value.trim(),
baseDomain: document.getElementById('identity-base-domain')?.value.trim(),
gitUrl: document.getElementById('identity-git-url')?.value.trim(),
footerText: document.getElementById('identity-footer-text')?.value.trim(),
logoIcon: document.getElementById('identity-logo-icon')?.value,
primaryColor: document.getElementById('identity-primary-color')?.value
};
const btn = document.getElementById('btn-save-identity');
if (btn) btn.disabled = true;
try {
const res = await api.updateIdentity(payload);
const updated = res.identity || res.data?.identity || payload;
currentIdentity = updated;
applyIdentityUI(updated);
toast.success('Identidad guardada', 'Los cambios se han aplicado al panel.');
} catch (err) {
toast.error('Error al guardar identidad', err.detail || err.message);
} finally {
if (btn) btn.disabled = false;
}
}
/* ==========================================================================
Utilidades Globales de Modales y Helpers
========================================================================== */
function openModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.classList.add('active');
document.body.style.overflow = 'hidden';
}
}
function closeAllModals() {
document.querySelectorAll('.modal-backdrop').forEach(m => {
m.classList.remove('active');
});
document.body.style.overflow = '';
}
function escapeHtml(text) {
if (text === null || text === undefined) return '';
const div = document.createElement('div');
div.textContent = String(text);
return div.innerHTML;
}