/** * 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(); // 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 === 'subdomains') loadSubdomains(); if (tabName === 'folders') loadFolders(); 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 => ` ${escapeHtml(item.name)}
${escapeHtml(item.fullDomain || `${item.name}.${BASE_DOMAIN}`)}
${item.type === 'proxy' ? `Modo B • Proxy` : `Modo A • Estático` } ${item.type === 'proxy' ? `:${item.port || '—'} ${escapeHtml(item.target || '')}` : `${escapeHtml(item.target || `/var/www/${item.name}`)}` } ${item.protected ? `Protegido` : `Normal` }
`).join(''); } // Renderizar Tarjetas Mobile if (mobileContainer) { mobileContainer.innerHTML = filtered.map(item => `
${escapeHtml(item.name)}
Tipo / Modo: ${item.type === 'proxy' ? `Modo B • Proxy :${item.port}` : `Modo A • Estático` }
Destino: ${escapeHtml(item.target || '')}
Seguridad: ${item.protected ? `Protegido` : `Normal` }
`).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 ========================================================================== */ let currentSubdomainModalMode = 'create'; // 'create' | 'edit' let selectedSubdomainType = 'static'; // 'static' | 'proxy' 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(); }); modeBtnProxy.addEventListener('click', () => { selectedSubdomainType = 'proxy'; modeBtnProxy.classList.add('active'); modeBtnStatic.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'flex'; validateSubdomainFormLive(); }); } // Validación en vivo del nombre y preview de URL const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); if (inputName) { inputName.addEventListener('input', () => { validateSubdomainFormLive(); }); } if (inputPort) { inputPort.addEventListener('input', () => { 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'; 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'); if (title) title.textContent = 'Crear Nuevo 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'; // Ocultar terminal de rollback previo if (terminal) terminal.classList.remove('active'); validateSubdomainFormLive(); openModal('modal-subdomain'); inputName?.focus(); } function openEditSubdomainModal(name) { const subdomains = store.getState('subdomains') || []; const item = subdomains.find(s => s.name === name); if (!item) return; currentSubdomainModalMode = 'edit'; selectedSubdomainType = item.type || 'static'; 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'); if (title) title.textContent = `Editar Subdominio: ${name}`; 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 (terminal) terminal.classList.remove('active'); validateSubdomainFormLive(); openModal('modal-subdomain'); } 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 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'); } if (btnSubmit) { btnSubmit.disabled = !(isNameValid && isPortValid); } return isNameValid && isPortValid; } 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 }); 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 = `No se encontraron carpetas en /var/www`; if (mobileContainer) mobileContainer.innerHTML = `
No se encontraron carpetas en /var/www
`; return; } // Renderizar Desktop if (tableBody) { tableBody.innerHTML = folders.map(f => { const isSGID = f.isSGID || f.permissions === '2775'; return `
${escapeHtml(f.folderName)}
${escapeHtml(f.path)}
${f.sizeFormatted || '—'} ${f.fileCount ?? 0} ficheros ${escapeHtml(f.owner)}:${escapeHtml(f.group)} ${escapeHtml(f.permissions)} ${isSGID ? `SGID 2775 OK` : `Sin SGID 2775` } `; }).join(''); } // Renderizar Mobile if (mobileContainer) { mobileContainer.innerHTML = folders.map(f => { const isSGID = f.isSGID || f.permissions === '2775'; return `
${escapeHtml(f.folderName)}
${escapeHtml(f.path)}
${isSGID ? `SGID 2775` : `Sin SGID` }
Tamaño: ${f.sizeFormatted || '—'}
Archivos: ${f.fileCount ?? 0} elementos
Permisos: ${escapeHtml(f.owner)}:${escapeHtml(f.group)} (${f.permissions})
`; }).join(''); } // Eventos de inspección de archivos document.querySelectorAll('.btn-inspect-folder').forEach(btn => { btn.addEventListener('click', () => { const folderName = btn.getAttribute('data-name'); openFolderFilesModal(folderName); }); }); const btnRefresh = document.getElementById('btn-refresh-folders'); if (btnRefresh) { btnRefresh.onclick = () => { loadFolders(); toast.info('Actualizando carpetas', 'Escaneando /var/www...'); }; } } async function openFolderFilesModal(folderName) { const modal = document.getElementById('modal-folder-files'); const title = document.getElementById('folder-files-modal-title'); const container = document.getElementById('folder-files-list-container'); if (title) title.textContent = `/var/www/${folderName}`; if (container) { container.innerHTML = `
Cargando lista de archivos...
`; } openModal('modal-folder-files'); try { const res = await api.getFolderFiles(folderName); const files = res.files || []; if (files.length === 0) { container.innerHTML = `
La carpeta está vacía.
`; return; } container.innerHTML = ` ${files.map(file => ` `).join('')}
Nombre Tipo Tamaño Permisos
${escapeHtml(file.name)} ${escapeHtml(file.type || 'file')} ${file.sizeFormatted || '—'} ${escapeHtml(file.permissions || '—')}
`; } catch (err) { if (container) { container.innerHTML = `
Error al leer carpeta: ${escapeHtml(err.message)}
`; } } } /* ========================================================================== 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; return `
${escapeHtml(u.fullName || u.username)}
${escapeHtml(u.username)}
${escapeHtml(u.role)} ${u.active ? 'Activo' : 'Inactivo'} ${u.lastLogin ? new Date(u.lastLogin).toLocaleString() : 'Nunca'}
`; }).join(''); } // Tarjetas Mobile if (mobileContainer) { mobileContainer.innerHTML = users.map(u => { const isSelf = currentUser && currentUser.id === u.id; return `
${escapeHtml(u.fullName || u.username)}
${escapeHtml(u.username)}
${escapeHtml(u.role)}
`; }).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 += `
${escapeHtml(title)}
`; } 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 = `
Cargando documento...
`; try { const docData = await api.getDoc(docId); store.setState({ selectedDoc: docData }); const htmlContent = renderMarkdown(docData.content); contentViewer.innerHTML = `
Doc ID: ${escapeHtml(docData.id)}

${escapeHtml(docData.title)}

Actualizado: ${new Date(docData.lastModified).toLocaleDateString()}
${htmlContent}
`; // 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 = `¡Copiado!`; setTimeout(() => { btn.innerHTML = original; }, 1500); }); }); }); } catch (err) { contentViewer.innerHTML = `
Error al cargar documento: ${escapeHtml(err.message)}
`; } } /* ========================================================================== 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; }