Files

916 lines
37 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collina Forms — Dashboard</title>
<style>
:root {
--bg-gradient: linear-gradient(135deg, #1C1C1E 0%, #2C2C2E 50%, #1C1C1E 100%);
--glass-bg: rgba(255, 255, 255, 0.08);
--glass-bg-hover: rgba(255, 255, 255, 0.12);
--glass-border: rgba(255, 255, 255, 0.15);
--glass-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
--accent: #0A84FF;
--accent-hover: #409CFF;
--accent-glow: rgba(10, 132, 255, 0.3);
--success: #30D158;
--warning: #FF9F0A;
--danger: #FF453A;
--purple: #BF5AF2;
--text-primary: rgba(255, 255, 255, 0.95);
--text-secondary: rgba(255, 255, 255, 0.55);
--text-tertiary: rgba(255, 255, 255, 0.30);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', sans-serif;
background: var(--bg-gradient);
background-attachment: fixed;
min-height: 100vh;
color: var(--text-primary);
display: flex;
}
a { color: var(--accent); }
.glass-card {
background: var(--glass-bg);
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border: 1px solid var(--glass-border);
border-radius: 16px;
box-shadow: var(--glass-shadow);
}
/* ---------- Sidebar ---------- */
.sidebar {
width: 240px;
flex-shrink: 0;
height: 100vh;
position: sticky;
top: 0;
padding: 28px 20px;
display: flex;
flex-direction: column;
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border-right: 1px solid var(--glass-border);
}
.sidebar .logo {
font-size: 18px;
font-weight: 700;
letter-spacing: 4px;
margin-bottom: 36px;
padding-left: 12px;
}
.nav-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
border-radius: 12px;
color: var(--text-secondary);
cursor: pointer;
font-size: 15px;
font-weight: 500;
transition: all 0.2s ease;
margin-bottom: 4px;
}
.nav-item svg { width: 19px; height: 19px; stroke: currentColor; fill: none; stroke-width: 2; }
.nav-item:hover { background: var(--glass-bg); color: var(--text-primary); }
.nav-item.active { background: var(--accent); color: #fff; }
.nav-item.hidden { display: none; }
.sidebar-footer {
margin-top: auto;
padding-top: 20px;
border-top: 1px solid var(--glass-border);
}
.user-chip {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
font-size: 14px;
color: var(--text-secondary);
}
.user-avatar {
width: 32px; height: 32px; border-radius: 50%;
background: var(--accent);
color: #fff;
display: flex; align-items: center; justify-content: center;
font-weight: 600; font-size: 14px;
}
/* ---------- Main ---------- */
.main {
flex: 1;
height: 100vh;
overflow-y: auto;
padding: 36px 44px;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 28px;
flex-wrap: wrap;
gap: 16px;
}
.page-header h1 { font-size: 28px; font-weight: 700; }
.breadcrumb {
font-size: 14px;
color: var(--text-secondary);
margin-bottom: 8px;
}
.breadcrumb a { cursor: pointer; text-decoration: none; }
.btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 11px 18px;
border-radius: 12px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s ease;
background: transparent;
color: var(--text-primary);
font-family: inherit;
}
.btn-primary { background: var(--accent); color: #fff; }
.btn-primary:hover { background: var(--accent-hover); box-shadow: 0 0 20px var(--accent-glow); }
.btn-ghost { background: var(--glass-bg); border-color: var(--glass-border); }
.btn-ghost:hover { background: var(--glass-bg-hover); }
.btn-danger { color: var(--danger); background: rgba(255,69,58,0.1); }
.btn-danger:hover { background: rgba(255,69,58,0.2); }
.btn-sm { padding: 7px 12px; font-size: 13px; }
/* ---------- Forms grid ---------- */
.forms-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 18px;
}
.form-card { padding: 22px; transition: all 0.2s ease; }
.form-card:hover { background: var(--glass-bg-hover); }
.form-card h3 { font-size: 18px; font-weight: 600; margin-bottom: 10px; }
.slug-badge {
display: inline-block;
font-size: 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
color: var(--accent-hover);
background: rgba(10,132,255,0.12);
border: 1px solid rgba(10,132,255,0.2);
padding: 4px 10px;
border-radius: 8px;
margin-bottom: 14px;
word-break: break-all;
}
.form-meta {
display: flex;
gap: 18px;
font-size: 13px;
color: var(--text-secondary);
margin-bottom: 18px;
}
.form-meta span { display: inline-flex; align-items: center; gap: 6px; }
.form-meta svg { width: 15px; height: 15px; stroke: currentColor; fill: none; stroke-width: 2; }
.card-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.desc { color: var(--text-secondary); font-size: 13px; margin-bottom: 14px; }
/* ---------- Empty state ---------- */
.empty-state {
text-align: center;
padding: 80px 20px;
color: var(--text-secondary);
}
.empty-state .icon {
width: 64px; height: 64px; margin: 0 auto 20px;
opacity: 0.4;
}
.empty-state h3 { font-size: 20px; color: var(--text-primary); margin-bottom: 8px; }
/* ---------- Table ---------- */
.table-wrap { overflow-x: auto; padding: 4px; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 14px 16px; font-size: 14px; }
th { color: var(--text-secondary); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 1px solid var(--glass-border); }
tbody tr { border-bottom: 1px solid rgba(255,255,255,0.05); cursor: pointer; transition: background 0.15s ease; }
tbody tr:nth-child(odd) { background: rgba(255,255,255,0.03); }
tbody tr:hover { background: rgba(255,255,255,0.07); }
.detail-row td { background: rgba(0,0,0,0.25); cursor: default; }
.json-view {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 13px;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
}
.json-key { color: var(--accent-hover); }
.json-val { color: var(--text-primary); }
.icon-btn {
background: transparent; border: none; cursor: pointer;
color: var(--text-secondary); padding: 6px; border-radius: 8px;
transition: all 0.2s ease; display: inline-flex;
}
.icon-btn:hover { color: var(--danger); background: rgba(255,69,58,0.1); }
.icon-btn svg { width: 17px; height: 17px; stroke: currentColor; fill: none; stroke-width: 2; }
/* ---------- Pagination ---------- */
.pagination { display: flex; gap: 8px; justify-content: center; margin-top: 20px; align-items: center; }
.pagination .page-info { color: var(--text-secondary); font-size: 14px; }
/* ---------- Modal ---------- */
.modal-overlay {
display: none;
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
backdrop-filter: blur(8px);
z-index: 100;
align-items: center; justify-content: center;
padding: 24px;
}
.modal-overlay.visible { display: flex; }
.modal {
width: 100%;
max-width: 460px;
border-radius: 20px;
padding: 28px;
max-height: 90vh;
overflow-y: auto;
}
.modal h2 { font-size: 20px; margin-bottom: 20px; }
.field { margin-bottom: 16px; }
.field label { display: block; font-size: 13px; color: var(--text-secondary); margin-bottom: 7px; }
.field input, .field textarea {
width: 100%;
padding: 12px 14px;
background: rgba(255,255,255,0.07);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 12px;
color: var(--text-primary);
font-size: 15px;
font-family: inherit;
transition: all 0.2s ease;
outline: none;
}
.field textarea { resize: vertical; min-height: 70px; }
.field input:focus, .field textarea:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.url-preview {
font-size: 12px;
font-family: ui-monospace, monospace;
color: var(--text-tertiary);
margin-top: 6px;
word-break: break-all;
}
.url-preview b { color: var(--accent-hover); }
.dropzone {
border: 2px dashed rgba(255,255,255,0.2);
border-radius: 14px;
padding: 28px 20px;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
color: var(--text-secondary);
}
.dropzone:hover, .dropzone.dragover {
border-color: var(--accent);
background: rgba(10,132,255,0.08);
color: var(--text-primary);
}
.dropzone svg { width: 32px; height: 32px; stroke: currentColor; fill: none; stroke-width: 1.6; margin-bottom: 10px; }
.dropzone .filename { color: var(--success); font-weight: 600; margin-top: 8px; }
.modal-actions { display: flex; gap: 12px; justify-content: flex-end; margin-top: 24px; }
.field-error { color: var(--danger); font-size: 12px; margin-top: 6px; display: none; }
.field-error.visible { display: block; }
/* ---------- Skeleton ---------- */
.skeleton {
background: linear-gradient(90deg, rgba(255,255,255,0.05) 25%, rgba(255,255,255,0.1) 50%, rgba(255,255,255,0.05) 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
border-radius: 8px;
}
@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
.skeleton-card { padding: 22px; }
.skeleton-line { height: 14px; margin-bottom: 12px; }
/* ---------- Toasts ---------- */
.toast-container {
position: fixed; bottom: 24px; right: 24px; z-index: 200;
display: flex; flex-direction: column; gap: 10px;
}
.toast {
min-width: 240px; max-width: 360px;
padding: 14px 18px;
border-radius: 12px;
font-size: 14px;
color: #fff;
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
animation: slideIn 0.25s ease;
display: flex; align-items: center; gap: 10px;
}
.toast.success { background: rgba(48,209,88,0.92); }
.toast.error { background: rgba(255,69,58,0.92); }
.toast.info { background: rgba(10,132,255,0.92); }
@keyframes slideIn { from { transform: translateX(120%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
.count-pill {
display: inline-flex; align-items: center; gap: 6px;
background: var(--glass-bg); border: 1px solid var(--glass-border);
padding: 6px 12px; border-radius: 10px; font-size: 14px; color: var(--text-secondary);
}
/* ---------- Hamburger / responsive ---------- */
.hamburger { display: none; background: none; border: none; cursor: pointer; }
.hamburger svg { width: 26px; height: 26px; stroke: var(--text-primary); fill: none; stroke-width: 2; }
.sidebar-backdrop { display: none; }
@media (max-width: 820px) {
.forms-grid { grid-template-columns: 1fr; }
.sidebar {
position: fixed; left: 0; top: 0; z-index: 150;
transform: translateX(-100%); transition: transform 0.25s ease;
}
.sidebar.open { transform: translateX(0); }
.sidebar-backdrop.visible { display: block; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 140; }
.main { padding: 20px; height: auto; min-height: 100vh; }
.hamburger { display: inline-flex; }
}
</style>
</head>
<body>
<aside class="sidebar" id="sidebar">
<div class="logo">COLLINA</div>
<nav>
<div class="nav-item active" data-view="forms" id="nav-forms">
<svg viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h8"/></svg>
Formularios
</div>
<div class="nav-item hidden" data-view="users" id="nav-users">
<svg viewBox="0 0 24 24"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>
Usuarios
</div>
<div class="nav-item" id="nav-logout">
<svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></svg>
Cerrar sesión
</div>
</nav>
<div class="sidebar-footer">
<div class="user-chip">
<div class="user-avatar" id="user-avatar">?</div>
<div id="user-name">—</div>
</div>
</div>
</aside>
<div class="sidebar-backdrop" id="sidebar-backdrop"></div>
<main class="main" id="main">
<!-- Las vistas se inyectan aquí -->
</main>
<!-- Modal: subir formulario -->
<div class="modal-overlay" id="upload-modal">
<div class="modal glass-card">
<h2>Subir formulario</h2>
<div class="field">
<label for="form-label">Nombre del formulario</label>
<input id="form-label" type="text" placeholder="Discovery — Cliente X">
<div class="field-error" id="err-label">Ingresa un nombre</div>
</div>
<div class="field">
<label for="form-slug">Slug</label>
<input id="form-slug" type="text" placeholder="discovery-cliente-x">
<div class="url-preview">forms.collinasystems.com.mx/<b id="slug-preview">slug</b></div>
<div class="field-error" id="err-slug">Solo minúsculas, números y guiones</div>
</div>
<div class="field">
<label for="form-desc">Descripción (opcional)</label>
<textarea id="form-desc" placeholder="Notas internas…"></textarea>
</div>
<div class="field">
<label>Archivo HTML</label>
<div class="dropzone" id="dropzone">
<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8l-5-5-5 5M12 3v12"/></svg>
<div>Arrastra o haz click para seleccionar</div>
<div class="filename" id="filename"></div>
</div>
<input id="file-input" type="file" accept=".html,text/html" style="display:none">
<div class="field-error" id="err-file">Selecciona un archivo HTML</div>
</div>
<div class="modal-actions">
<button class="btn btn-ghost" id="upload-cancel">Cancelar</button>
<button class="btn btn-primary" id="upload-submit">Subir formulario</button>
</div>
</div>
</div>
<!-- Modal: nuevo usuario -->
<div class="modal-overlay" id="user-modal">
<div class="modal glass-card">
<h2>Nuevo usuario</h2>
<div class="field">
<label for="u-username">Usuario</label>
<input id="u-username" type="text" placeholder="jdoe">
</div>
<div class="field">
<label for="u-email">Email</label>
<input id="u-email" type="email" placeholder="jdoe@collinasystems.com.mx">
</div>
<div class="field">
<label for="u-password">Contraseña</label>
<input id="u-password" type="password" placeholder="••••••••">
</div>
<div class="field-error" id="err-user">Completa todos los campos</div>
<div class="modal-actions">
<button class="btn btn-ghost" id="user-cancel">Cancelar</button>
<button class="btn btn-primary" id="user-submit">Crear usuario</button>
</div>
</div>
</div>
<div class="toast-container" id="toasts"></div>
<script>
// ===================================================================== //
// Auth & helpers
// ===================================================================== //
const TOKEN = localStorage.getItem('collina_token');
const USERNAME = localStorage.getItem('collina_username') || '';
const IS_ADMIN = localStorage.getItem('collina_is_admin') === '1';
if (!TOKEN) { window.location.href = '/login'; }
function logout() {
localStorage.removeItem('collina_token');
localStorage.removeItem('collina_username');
localStorage.removeItem('collina_is_admin');
window.location.href = '/login';
}
async function api(path, opts = {}) {
const headers = opts.headers || {};
headers['Authorization'] = 'Bearer ' + TOKEN;
if (opts.body && !(opts.body instanceof FormData) && !headers['Content-Type']) {
headers['Content-Type'] = 'application/json';
}
const res = await fetch(path, { ...opts, headers });
if (res.status === 401) { logout(); throw new Error('No autorizado'); }
return res;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[c]));
}
function fmtDate(iso) {
if (!iso) return '—';
const d = new Date(iso);
return d.toLocaleString('es-MX', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}
function toast(msg, type = 'info') {
const c = document.getElementById('toasts');
const t = document.createElement('div');
t.className = 'toast ' + type;
t.textContent = msg;
c.appendChild(t);
setTimeout(() => {
t.style.transition = 'opacity 0.3s';
t.style.opacity = '0';
setTimeout(() => t.remove(), 300);
}, 3200);
}
// ===================================================================== //
// Sidebar / nav
// ===================================================================== //
const main = document.getElementById('main');
const sidebar = document.getElementById('sidebar');
const backdrop = document.getElementById('sidebar-backdrop');
document.getElementById('user-name').textContent = USERNAME;
document.getElementById('user-avatar').textContent = (USERNAME[0] || '?').toUpperCase();
if (IS_ADMIN) document.getElementById('nav-users').classList.remove('hidden');
document.getElementById('nav-forms').addEventListener('click', () => { setActiveNav('forms'); renderForms(); closeSidebar(); });
document.getElementById('nav-users').addEventListener('click', () => { setActiveNav('users'); renderUsers(); closeSidebar(); });
document.getElementById('nav-logout').addEventListener('click', logout);
backdrop.addEventListener('click', closeSidebar);
function setActiveNav(view) {
document.querySelectorAll('.nav-item[data-view]').forEach(n => {
n.classList.toggle('active', n.dataset.view === view);
});
}
function openSidebar() { sidebar.classList.add('open'); backdrop.classList.add('visible'); }
function closeSidebar() { sidebar.classList.remove('open'); backdrop.classList.remove('visible'); }
// ===================================================================== //
// Vista: Formularios
// ===================================================================== //
function headerBar(title, btnHtml = '') {
return `<div class="page-header">
<div style="display:flex;align-items:center;gap:14px;">
<button class="hamburger" onclick="openSidebar()"><svg viewBox="0 0 24 24"><path d="M3 12h18M3 6h18M3 18h18"/></svg></button>
<h1>${escapeHtml(title)}</h1>
</div>
<div>${btnHtml}</div>
</div>`;
}
function skeletonGrid() {
let s = '<div class="forms-grid">';
for (let i = 0; i < 4; i++) {
s += `<div class="glass-card skeleton-card">
<div class="skeleton skeleton-line" style="width:60%"></div>
<div class="skeleton skeleton-line" style="width:80%"></div>
<div class="skeleton skeleton-line" style="width:40%"></div>
</div>`;
}
return s + '</div>';
}
async function renderForms() {
main.innerHTML = headerBar('Formularios',
'<button class="btn btn-primary" onclick="openUploadModal()">+ Subir formulario</button>') + skeletonGrid();
try {
const res = await api('/api/forms');
const forms = await res.json();
renderFormsGrid(forms);
} catch (e) {
main.innerHTML = headerBar('Formularios') + '<div class="empty-state">Error al cargar formularios</div>';
}
}
function renderFormsGrid(forms) {
const header = headerBar('Formularios',
'<button class="btn btn-primary" onclick="openUploadModal()">+ Subir formulario</button>');
if (!forms.length) {
main.innerHTML = header + `<div class="glass-card empty-state">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>
<h3>Aún no hay formularios</h3>
<p>Sube tu primer HTML para empezar a recibir respuestas.</p>
</div>`;
return;
}
let cards = '<div class="forms-grid">';
for (const f of forms) {
cards += `<div class="glass-card form-card">
<h3>${escapeHtml(f.label)}</h3>
<span class="slug-badge">${escapeHtml(f.url)}</span>
${f.description ? `<div class="desc">${escapeHtml(f.description)}</div>` : ''}
<div class="form-meta">
<span><svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>${f.response_count} respuestas</span>
<span><svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>${fmtDate(f.created_at)}</span>
</div>
<div class="card-actions">
<button class="btn btn-ghost btn-sm" onclick="renderResponses('${escapeHtml(f.slug)}','${escapeHtml(f.label).replace(/'/g, "\\'")}')">Ver respuestas</button>
<button class="btn btn-ghost btn-sm" onclick="copyLink('${escapeHtml(f.url)}')">Copiar link</button>
<button class="btn btn-danger btn-sm" onclick="deleteForm('${escapeHtml(f.slug)}','${escapeHtml(f.label).replace(/'/g, "\\'")}')">Eliminar</button>
</div>
</div>`;
}
main.innerHTML = header + cards + '</div>';
}
function copyLink(url) {
const full = url.startsWith('http') ? url : 'https://' + url;
navigator.clipboard.writeText(full).then(
() => toast('Link copiado', 'success'),
() => toast('No se pudo copiar', 'error')
);
}
async function deleteForm(slug, label) {
if (!confirm(`¿Eliminar "${label}" y todas sus respuestas?`)) return;
try {
await api('/api/forms/' + encodeURIComponent(slug), { method: 'DELETE' });
toast('Formulario eliminado', 'success');
renderForms();
} catch (e) { toast('Error al eliminar', 'error'); }
}
// ===================================================================== //
// Vista: Respuestas
// ===================================================================== //
const PAGE_SIZE = 20;
let respState = { slug: '', label: '', items: [], page: 1 };
async function renderResponses(slug, label) {
respState = { slug, label, items: [], page: 1 };
main.innerHTML = `<div class="breadcrumb"><a onclick="renderForms()">Formularios</a> &rsaquo; ${escapeHtml(label)}</div>`
+ headerBar(label,
`<button class="btn btn-primary" onclick="exportCsv('${escapeHtml(slug)}')">Exportar CSV</button>`)
+ '<div class="glass-card"><div class="skeleton skeleton-line" style="margin:24px;width:50%"></div><div class="skeleton skeleton-line" style="margin:24px;width:70%"></div></div>';
try {
const res = await api('/api/forms/' + encodeURIComponent(slug) + '/responses');
respState.items = await res.json();
paintResponses();
} catch (e) {
toast('Error al cargar respuestas', 'error');
}
}
function paintResponses() {
const { items, page, slug, label } = respState;
const breadcrumb = `<div class="breadcrumb"><a onclick="renderForms()">Formularios</a> &rsaquo; ${escapeHtml(label)}</div>`;
const header = headerBar(label,
items.length ? `<button class="btn btn-primary" onclick="exportCsv('${escapeHtml(slug)}')">Exportar CSV</button>` : '');
if (!items.length) {
main.innerHTML = breadcrumb + header + `<div class="glass-card empty-state">
<h3>Sin respuestas todavía</h3>
<p>Comparte el link del formulario para empezar a recibir respuestas.</p></div>`;
return;
}
const totalPages = Math.ceil(items.length / PAGE_SIZE);
const start = (page - 1) * PAGE_SIZE;
const pageItems = items.slice(start, start + PAGE_SIZE);
let rows = '';
for (const r of pageItems) {
rows += `<tr onclick="toggleDetail(${r.id}, this)">
<td>#${r.id}</td>
<td>${fmtDate(r.submitted_at)}</td>
<td>${escapeHtml(r.ip || '—')}</td>
<td><button class="icon-btn" onclick="event.stopPropagation(); deleteResponse(${r.id})" title="Eliminar">
<svg viewBox="0 0 24 24"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
</button></td>
</tr>
<tr class="detail-row" id="detail-${r.id}" style="display:none"><td colspan="4">
<div class="json-view">${renderJson(r.data)}</div>
</td></tr>`;
}
let pag = '';
if (totalPages > 1) {
pag = `<div class="pagination">
<button class="btn btn-ghost btn-sm" ${page <= 1 ? 'disabled' : ''} onclick="goPage(${page - 1})">‹</button>
<span class="page-info">Página ${page} de ${totalPages}</span>
<button class="btn btn-ghost btn-sm" ${page >= totalPages ? 'disabled' : ''} onclick="goPage(${page + 1})">›</button>
</div>`;
}
main.innerHTML = breadcrumb + header
+ `<div style="margin-bottom:18px;"><span class="count-pill">${items.length} respuestas</span></div>`
+ `<div class="glass-card table-wrap"><table>
<thead><tr><th>#</th><th>Fecha</th><th>IP</th><th>Acciones</th></tr></thead>
<tbody>${rows}</tbody></table></div>` + pag;
}
function goPage(p) { respState.page = p; paintResponses(); }
function toggleDetail(id, row) {
const d = document.getElementById('detail-' + id);
if (d) d.style.display = d.style.display === 'none' ? 'table-row' : 'none';
}
function renderJson(obj) {
function fmt(val, indent) {
const pad = ' '.repeat(indent);
if (Array.isArray(val)) {
if (!val.length) return '[]';
return '[\n' + val.map(v => pad + ' ' + fmt(v, indent + 1)).join(',\n') + '\n' + pad + ']';
}
if (val && typeof val === 'object') {
const entries = Object.entries(val);
if (!entries.length) return '{}';
return '{\n' + entries.map(([k, v]) =>
pad + ' <span class="json-key">"' + escapeHtml(k) + '"</span>: ' + fmt(v, indent + 1)
).join(',\n') + '\n' + pad + '}';
}
return '<span class="json-val">' + escapeHtml(JSON.stringify(val)) + '</span>';
}
return fmt(obj, 0);
}
async function deleteResponse(id) {
if (!confirm('¿Eliminar esta respuesta?')) return;
try {
await api('/api/responses/' + id, { method: 'DELETE' });
respState.items = respState.items.filter(r => r.id !== id);
const totalPages = Math.max(1, Math.ceil(respState.items.length / PAGE_SIZE));
if (respState.page > totalPages) respState.page = totalPages;
paintResponses();
toast('Respuesta eliminada', 'success');
} catch (e) { toast('Error al eliminar', 'error'); }
}
async function exportCsv(slug) {
try {
const res = await api('/api/forms/' + encodeURIComponent(slug) + '/export');
if (!res.ok) throw new Error();
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = slug + '-respuestas.csv';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
toast('CSV descargado', 'success');
} catch (e) { toast('Error al exportar', 'error'); }
}
// ===================================================================== //
// Vista: Usuarios (admin)
// ===================================================================== //
async function renderUsers() {
main.innerHTML = headerBar('Usuarios',
'<button class="btn btn-primary" onclick="openUserModal()">+ Nuevo usuario</button>')
+ '<div class="glass-card"><div class="skeleton skeleton-line" style="margin:24px;width:50%"></div></div>';
try {
const res = await api('/api/auth/users');
const users = await res.json();
let rows = '';
for (const u of users) {
const selfBadge = u.username === USERNAME;
rows += `<tr style="cursor:default">
<td>${escapeHtml(u.username)}${selfBadge ? ' <span style="color:var(--text-tertiary);font-size:12px">(tú)</span>' : ''}</td>
<td>${escapeHtml(u.email)}</td>
<td>${fmtDate(u.created_at)}</td>
<td>${selfBadge ? '' : `<button class="icon-btn" onclick="deleteUser(${u.id},'${escapeHtml(u.username)}')" title="Eliminar">
<svg viewBox="0 0 24 24"><path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>`}</td>
</tr>`;
}
main.innerHTML = headerBar('Usuarios',
'<button class="btn btn-primary" onclick="openUserModal()">+ Nuevo usuario</button>')
+ `<div class="glass-card table-wrap"><table>
<thead><tr><th>Usuario</th><th>Email</th><th>Creado</th><th></th></tr></thead>
<tbody>${rows}</tbody></table></div>`;
} catch (e) { toast('Error al cargar usuarios', 'error'); }
}
async function deleteUser(id, username) {
if (!confirm(`¿Eliminar al usuario "${username}"?`)) return;
try {
const res = await api('/api/auth/users/' + id, { method: 'DELETE' });
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.detail); }
toast('Usuario eliminado', 'success');
renderUsers();
} catch (e) { toast(e.message || 'Error al eliminar', 'error'); }
}
// ===================================================================== //
// Modal: subir formulario
// ===================================================================== //
const uploadModal = document.getElementById('upload-modal');
const fileInput = document.getElementById('file-input');
const dropzone = document.getElementById('dropzone');
let selectedFile = null;
let slugEditedManually = false;
function slugify(s) {
return s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9\s-]/g, '').trim().replace(/\s+/g, '-').replace(/-+/g, '-');
}
function openUploadModal() {
selectedFile = null; slugEditedManually = false;
document.getElementById('form-label').value = '';
document.getElementById('form-slug').value = '';
document.getElementById('form-desc').value = '';
document.getElementById('slug-preview').textContent = 'slug';
document.getElementById('filename').textContent = '';
['err-label', 'err-slug', 'err-file'].forEach(id => document.getElementById(id).classList.remove('visible'));
uploadModal.classList.add('visible');
}
function closeUploadModal() { uploadModal.classList.remove('visible'); }
document.getElementById('form-label').addEventListener('input', (e) => {
if (!slugEditedManually) {
const s = slugify(e.target.value);
document.getElementById('form-slug').value = s;
document.getElementById('slug-preview').textContent = s || 'slug';
}
});
document.getElementById('form-slug').addEventListener('input', (e) => {
slugEditedManually = true;
const s = slugify(e.target.value);
e.target.value = s;
document.getElementById('slug-preview').textContent = s || 'slug';
});
dropzone.addEventListener('click', () => fileInput.click());
dropzone.addEventListener('dragover', (e) => { e.preventDefault(); dropzone.classList.add('dragover'); });
dropzone.addEventListener('dragleave', () => dropzone.classList.remove('dragover'));
dropzone.addEventListener('drop', (e) => {
e.preventDefault(); dropzone.classList.remove('dragover');
if (e.dataTransfer.files.length) setFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', () => { if (fileInput.files.length) setFile(fileInput.files[0]); });
function setFile(file) {
if (!/\.html?$/i.test(file.name) && file.type !== 'text/html') {
toast('El archivo debe ser HTML', 'error'); return;
}
selectedFile = file;
document.getElementById('filename').textContent = file.name;
document.getElementById('err-file').classList.remove('visible');
}
document.getElementById('upload-cancel').addEventListener('click', closeUploadModal);
document.getElementById('upload-submit').addEventListener('click', submitUpload);
async function submitUpload() {
const label = document.getElementById('form-label').value.trim();
const slug = document.getElementById('form-slug').value.trim();
const desc = document.getElementById('form-desc').value.trim();
let ok = true;
document.getElementById('err-label').classList.toggle('visible', !label); if (!label) ok = false;
const slugValid = /^[a-z0-9-]+$/.test(slug);
document.getElementById('err-slug').classList.toggle('visible', !slugValid); if (!slugValid) ok = false;
document.getElementById('err-file').classList.toggle('visible', !selectedFile); if (!selectedFile) ok = false;
if (!ok) return;
const fd = new FormData();
fd.append('slug', slug);
fd.append('label', label);
fd.append('description', desc);
fd.append('file', selectedFile);
const btn = document.getElementById('upload-submit');
btn.disabled = true; btn.textContent = 'Subiendo…';
try {
const res = await api('/api/forms/upload', { method: 'POST', body: fd });
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e.detail || 'Error al subir');
}
closeUploadModal();
toast('Formulario creado', 'success');
setActiveNav('forms'); renderForms();
} catch (e) {
toast(e.message, 'error');
} finally {
btn.disabled = false; btn.textContent = 'Subir formulario';
}
}
// ===================================================================== //
// Modal: nuevo usuario
// ===================================================================== //
const userModal = document.getElementById('user-modal');
function openUserModal() {
document.getElementById('u-username').value = '';
document.getElementById('u-email').value = '';
document.getElementById('u-password').value = '';
document.getElementById('err-user').classList.remove('visible');
userModal.classList.add('visible');
}
function closeUserModal() { userModal.classList.remove('visible'); }
document.getElementById('user-cancel').addEventListener('click', closeUserModal);
document.getElementById('user-submit').addEventListener('click', async () => {
const username = document.getElementById('u-username').value.trim();
const email = document.getElementById('u-email').value.trim();
const password = document.getElementById('u-password').value;
if (!username || !email || !password) {
document.getElementById('err-user').classList.add('visible'); return;
}
const btn = document.getElementById('user-submit');
btn.disabled = true; btn.textContent = 'Creando…';
try {
const res = await api('/api/auth/users', {
method: 'POST',
body: JSON.stringify({ username, email, password })
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.detail || 'Error'); }
closeUserModal();
toast('Usuario creado', 'success');
renderUsers();
} catch (e) { toast(e.message, 'error'); }
finally { btn.disabled = false; btn.textContent = 'Crear usuario'; }
});
// Cerrar modales al hacer click en overlay
[uploadModal, userModal].forEach(m => {
m.addEventListener('click', (e) => { if (e.target === m) m.classList.remove('visible'); });
});
// Exponer funciones usadas en onclick inline
Object.assign(window, {
renderForms, renderResponses, renderUsers, copyLink, deleteForm,
deleteResponse, exportCsv, goPage, toggleDetail, deleteUser,
openUploadModal, openUserModal, openSidebar
});
// Arranque
renderForms();
</script>
</body>
</html>