a2host/public/js/app.js

2585 lines
94 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;
}
// 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
setupModals();
setupFileManager();
setupCodeEditor();
setupTerminal();
setupMonitor();
// 6. Cargar datos iniciales
loadSubdomains();
loadFolders();
if (store.getState('currentUser')?.role === 'admin') {
loadUsers();
}
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 === 'folders') loadFolders();
if (tabName === 'terminal') initTerminalTab();
if (tabName === 'monitor') initMonitorTab();
if (tabName === 'users') loadUsers();
if (tabName === 'docs') loadDocs();
}
/* ==========================================================================
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="Bit SGID 2775 activo: hereda grupo www-data">SGID 2775 OK</span>`
: `<span class="badge badge-sgid-warn" title="Alerta: se recomienda chmod 2775">Sin SGID 2775</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">SGID 2775</span>`
: `<span class="badge badge-sgid-warn">Sin SGID</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 = 'ggc';
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');
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 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');
try {
const res = await api.getTerminalInfo();
const info = res.data || res;
if (info) {
terminalUser = info.user || 'ggc';
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}`;
}
} catch (err) {
console.warn('[Terminal] Error al obtener info:', err);
}
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 = [];
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);
});
}
}
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;
if (ramUsedEl) ramUsedEl.textContent = `${mem.usedFormatted || '0 B'} / ${mem.totalFormatted || '1 GB'}`;
if (ramPercentEl) ramPercentEl.textContent = `${mem.usedPercent || 0}%`;
if (ramBarEl) {
ramBarEl.style.width = `${Math.min(100, mem.usedPercent || 0)}%`;
ramBarEl.className = 'metric-progress-fill fill-lime';
if (mem.usedPercent > 85) ramBarEl.classList.add('fill-danger');
else if (mem.usedPercent > 65) ramBarEl.classList.add('fill-warning');
}
if (ramFreeEl) ramFreeEl.textContent = mem.freeFormatted || '0 B';
if (ramCacheEl) ramCacheEl.textContent = mem.buffersCacheFormatted || mem.cachedFormatted || '—';
}
// 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');
if (stats.memory) {
const mem = stats.memory;
if (swapUsedEl) swapUsedEl.textContent = `${mem.swapUsedFormatted || '0 B'} / ${mem.swapTotalFormatted || '0 B'}`;
if (swapPercentEl) swapPercentEl.textContent = `${mem.swapUsedPercent || 0}%`;
if (swapBarEl) swapBarEl.style.width = `${Math.min(100, mem.swapUsedPercent || 0)}%`;
if (swapFreeEl) swapFreeEl.textContent = mem.swapFreeFormatted || '—';
if (swapTotalEl) swapTotalEl.textContent = mem.swapTotalFormatted || '—';
}
// 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="6" 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);
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>
</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);
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>
`;
}).join('');
}
}
}
/* ==========================================================================
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);
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">[SISTEMA / INMUTABLE]</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 del sistema 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 del sistema 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>`;
}
}
/* ==========================================================================
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;
}