feat: collina forms platform v1
This commit is contained in:
commit
6763f20b73
16 files changed
+2156
No files matched your search
@@ -0,0 +1,9 @@
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
.env
|
||||
.venv
|
||||
__pycache__/
|
||||
*.pyc
|
||||
data/
|
||||
*.db
|
||||
@@ -0,0 +1,24 @@
|
||||
# JWT
|
||||
JWT_SECRET=cambia_esto_por_un_string_muy_largo_y_aleatorio
|
||||
|
||||
# Primer usuario admin (se crea solo al primer arranque si la tabla users está vacía)
|
||||
FIRST_ADMIN_USER=admin
|
||||
FIRST_ADMIN_PASSWORD=cambia_esto
|
||||
|
||||
# Email de notificaciones (SMTP Hostinger)
|
||||
SMTP_HOST=smtp.hostinger.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=tu@collinasystems.com.mx
|
||||
SMTP_PASS=tu_password_de_correo
|
||||
NOTIFY_TO=tu@collinasystems.com.mx
|
||||
|
||||
# Base de datos
|
||||
DB_PATH=/data/formularios.db
|
||||
|
||||
# Opcionales
|
||||
# Directorio donde se guardan los HTML de los formularios
|
||||
FORMS_DIR=/data/forms
|
||||
# Dominio público usado para construir los links mostrados en el dashboard
|
||||
PUBLIC_BASE=forms.collinasystems.com.mx
|
||||
# Link del dashboard incluido en el footer de los emails
|
||||
DASHBOARD_URL=https://forms.collinasystems.com.mx/dashboard
|
||||
@@ -0,0 +1,7 @@
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.db
|
||||
data/
|
||||
.venv/
|
||||
.DS_Store
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Instalar nginx
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends nginx \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Backend
|
||||
WORKDIR /app
|
||||
COPY backend/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY backend/ .
|
||||
|
||||
# Frontend (servido por nginx)
|
||||
COPY frontend/ /usr/share/nginx/html/
|
||||
|
||||
# nginx config
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
RUN rm -f /etc/nginx/sites-enabled/default
|
||||
|
||||
# Script de arranque
|
||||
COPY start.sh /start.sh
|
||||
RUN chmod +x /start.sh
|
||||
|
||||
EXPOSE 80
|
||||
CMD ["/start.sh"]
|
||||
@@ -0,0 +1,135 @@
|
||||
# Collina Forms
|
||||
|
||||
Plataforma ligera de gestión de formularios para **Collina Systems**. Permite subir
|
||||
formularios HTML, servirlos en una URL pública, recolectar respuestas, notificarlas por
|
||||
email y administrarlas desde un dashboard con estética glassmorphism.
|
||||
|
||||
Vive en `forms.collinasystems.com.mx` y está pensada para desplegarse con Docker / Coolify.
|
||||
|
||||
---
|
||||
|
||||
## Stack
|
||||
|
||||
- **Backend:** Python 3.11 · FastAPI · Uvicorn · Pydantic v2 · SQLAlchemy 2.0
|
||||
- **DB:** SQLite (archivo en volumen persistente `/data/formularios.db`)
|
||||
- **Auth:** JWT (`python-jose`) + `passlib[bcrypt]`, expiración 8 h
|
||||
- **Email:** `smtplib` nativo (SMTP Hostinger)
|
||||
- **Frontend:** HTML + CSS + JS vanilla (sin build)
|
||||
- **Proxy:** nginx · **Contenedor:** Docker + docker-compose
|
||||
|
||||
---
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
collina-forms/
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
├── nginx.conf
|
||||
├── start.sh
|
||||
├── .env.example
|
||||
├── backend/
|
||||
│ ├── main.py # API + endpoints + inyección de script + CSV
|
||||
│ ├── models.py # users, forms, responses
|
||||
│ ├── auth.py # hashing + JWT + dependencias
|
||||
│ ├── database.py # engine SQLite + sesión
|
||||
│ ├── email_service.py # notificación SMTP
|
||||
│ └── requirements.txt
|
||||
└── frontend/
|
||||
├── login.html
|
||||
└── dashboard.html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cómo funciona
|
||||
|
||||
1. Un usuario autenticado sube un archivo HTML desde el dashboard (slug + nombre + descripción).
|
||||
2. Antes de guardarlo, el backend **inyecta automáticamente** un `<script>` antes de
|
||||
`</body>` que intercepta el `submit` del formulario (`#discovery-form`) y lo envía como
|
||||
JSON a `POST /api/submit/{slug}`.
|
||||
3. El HTML se guarda en `/data/forms/{slug}/index.html` y nginx lo sirve en
|
||||
`forms.collinasystems.com.mx/{slug}`.
|
||||
4. Cada respuesta se guarda en SQLite y dispara un email de notificación (los errores SMTP
|
||||
se loggean pero **no rompen** el flujo).
|
||||
5. Las respuestas se ven, borran y exportan a CSV desde el dashboard.
|
||||
|
||||
> El formulario subido debe tener `id="discovery-form"` para que la captura funcione.
|
||||
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Método | Ruta | Auth | Descripción |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/api/auth/login` | — | Login, devuelve JWT |
|
||||
| POST | `/api/auth/users` | admin | Crear usuario |
|
||||
| GET | `/api/auth/users` | admin | Listar usuarios |
|
||||
| DELETE | `/api/auth/users/{id}` | admin | Borrar usuario (no a sí mismo) |
|
||||
| POST | `/api/forms/upload` | JWT | Subir HTML (multipart) |
|
||||
| GET | `/api/forms` | JWT | Listar formularios + conteo |
|
||||
| DELETE | `/api/forms/{slug}` | JWT | Borrar formulario y respuestas |
|
||||
| POST | `/api/submit/{slug}` | **público** | Recibir una respuesta |
|
||||
| GET | `/api/forms/{slug}/responses` | JWT | Listar respuestas |
|
||||
| DELETE | `/api/responses/{id}` | JWT | Borrar una respuesta |
|
||||
| GET | `/api/forms/{slug}/export` | JWT | Descargar CSV |
|
||||
| GET | `/api/health` | — | Healthcheck |
|
||||
|
||||
> "admin" = el usuario cuyo `username` coincide con `FIRST_ADMIN_USER`.
|
||||
|
||||
---
|
||||
|
||||
## Despliegue (Docker)
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# edita .env: JWT_SECRET, FIRST_ADMIN_*, credenciales SMTP
|
||||
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
La app queda en el puerto **80**. En Coolify, apunta el dominio
|
||||
`forms.collinasystems.com.mx` al servicio y deja que gestione el TLS.
|
||||
|
||||
El primer arranque crea el usuario admin (`FIRST_ADMIN_USER` / `FIRST_ADMIN_PASSWORD`)
|
||||
**solo si la tabla `users` está vacía**.
|
||||
|
||||
### Rutas servidas por nginx
|
||||
|
||||
- `/api/*` → FastAPI (`127.0.0.1:8000`)
|
||||
- `/login` → `login.html`
|
||||
- `/dashboard` → `dashboard.html`
|
||||
- `/{slug}` → `/data/forms/{slug}/index.html`
|
||||
- `/` → redirige a `/dashboard`
|
||||
|
||||
---
|
||||
|
||||
## Desarrollo local (sin Docker)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
export DB_PATH=./formularios.db
|
||||
export FORMS_DIR=./forms
|
||||
export JWT_SECRET=dev-secret
|
||||
export FIRST_ADMIN_USER=admin
|
||||
export FIRST_ADMIN_PASSWORD=admin
|
||||
|
||||
uvicorn main:app --reload --port 8000
|
||||
```
|
||||
|
||||
Luego sirve `frontend/` con cualquier servidor estático y haz que `/api` apunte al
|
||||
backend (o usa el contenedor completo). Docs interactivas en `http://localhost:8000/docs`.
|
||||
|
||||
---
|
||||
|
||||
## Notas
|
||||
|
||||
- El slug solo admite `[a-z0-9-]`; el dashboard lo auto-genera desde el nombre.
|
||||
- El CSV aplana el array `automations` a una columna legible (`valor (prioridad: X); …`)
|
||||
y serializa cualquier otro valor compuesto como JSON.
|
||||
- El JWT se guarda en `localStorage` y se envía como `Authorization: Bearer {token}`;
|
||||
si expira o es inválido, el dashboard redirige a `/login`.
|
||||
- Variables opcionales: `FORMS_DIR`, `PUBLIC_BASE`, `DASHBOARD_URL` (ver `.env.example`).
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Autenticación: hashing de passwords y emisión/verificación de JWT."""
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from database import get_db
|
||||
from models import User
|
||||
|
||||
JWT_SECRET = os.environ.get("JWT_SECRET", "dev-insecure-secret-change-me")
|
||||
JWT_ALGORITHM = "HS256"
|
||||
JWT_EXPIRE_HOURS = 8
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
# tokenUrl es solo informativo para el flujo OpenAPI; el login real es JSON.
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(user: User) -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {
|
||||
"sub": str(user.id),
|
||||
"username": user.username,
|
||||
"iat": now,
|
||||
"exp": now + timedelta(hours=JWT_EXPIRE_HOURS),
|
||||
}
|
||||
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
||||
|
||||
|
||||
def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if not user or not user.is_active:
|
||||
return None
|
||||
if not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(
|
||||
token: Optional[str] = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
credentials_exc = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="No autenticado",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
if not token:
|
||||
raise credentials_exc
|
||||
try:
|
||||
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
||||
user_id = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise credentials_exc
|
||||
except JWTError:
|
||||
raise credentials_exc
|
||||
|
||||
user = db.query(User).filter(User.id == int(user_id)).first()
|
||||
if not user or not user.is_active:
|
||||
raise credentials_exc
|
||||
return user
|
||||
|
||||
|
||||
ADMIN_USERNAME = os.environ.get("FIRST_ADMIN_USER", "admin")
|
||||
|
||||
|
||||
def is_admin(user: User) -> bool:
|
||||
return user.username == ADMIN_USERNAME
|
||||
|
||||
|
||||
def require_admin(user: User = Depends(get_current_user)) -> User:
|
||||
if not is_admin(user):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Se requieren privilegios de administrador",
|
||||
)
|
||||
return user
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Configuración de SQLAlchemy 2.0 sobre SQLite."""
|
||||
import os
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||||
|
||||
DB_PATH = os.environ.get("DB_PATH", "/data/formularios.db")
|
||||
|
||||
# Asegurar que el directorio del archivo exista (volumen persistente)
|
||||
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
|
||||
|
||||
DATABASE_URL = f"sqlite:///{DB_PATH}"
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Dependency de FastAPI que entrega una sesión por request."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Crea todas las tablas declaradas."""
|
||||
# Importar modelos para que queden registrados en la metadata
|
||||
import models # noqa: F401
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Envío de notificaciones por email usando smtplib nativo."""
|
||||
import os
|
||||
import smtplib
|
||||
import logging
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from email.utils import formatdate
|
||||
|
||||
logger = logging.getLogger("collina.email")
|
||||
|
||||
SMTP_HOST = os.environ.get("SMTP_HOST", "")
|
||||
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
|
||||
SMTP_USER = os.environ.get("SMTP_USER", "")
|
||||
SMTP_PASS = os.environ.get("SMTP_PASS", "")
|
||||
NOTIFY_TO = os.environ.get("NOTIFY_TO", "")
|
||||
DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "https://forms.collinasystems.com.mx/dashboard")
|
||||
|
||||
|
||||
def _render_value(value) -> str:
|
||||
"""Convierte un valor del JSON de respuesta a HTML legible."""
|
||||
if isinstance(value, list):
|
||||
rows = []
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
parts = [f"{k}: {v}" for k, v in item.items()]
|
||||
rows.append(" — ".join(parts))
|
||||
else:
|
||||
rows.append(str(item))
|
||||
return "<br>".join(rows) if rows else "<em>(vacío)</em>"
|
||||
if isinstance(value, dict):
|
||||
return "<br>".join(f"{k}: {v}" for k, v in value.items())
|
||||
if value in (None, ""):
|
||||
return "<em>(vacío)</em>"
|
||||
return str(value)
|
||||
|
||||
|
||||
def _build_html(label: str, data: dict) -> str:
|
||||
rows = ""
|
||||
for key, value in data.items():
|
||||
rows += f"""
|
||||
<tr>
|
||||
<td style="padding:10px 14px;border-bottom:1px solid #eee;font-weight:600;color:#1c1c1e;vertical-align:top;white-space:nowrap;">{key}</td>
|
||||
<td style="padding:10px 14px;border-bottom:1px solid #eee;color:#3a3a3c;">{_render_value(value)}</td>
|
||||
</tr>"""
|
||||
|
||||
return f"""<!DOCTYPE html>
|
||||
<html>
|
||||
<body style="margin:0;padding:24px;background:#f2f2f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">
|
||||
<div style="max-width:600px;margin:0 auto;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08);">
|
||||
<div style="background:linear-gradient(135deg,#0A84FF,#409CFF);padding:24px 28px;">
|
||||
<div style="color:#fff;font-size:13px;letter-spacing:2px;opacity:0.85;">COLLINA FORMS</div>
|
||||
<div style="color:#fff;font-size:20px;font-weight:700;margin-top:4px;">Nueva respuesta recibida</div>
|
||||
<div style="color:#fff;font-size:15px;opacity:0.9;margin-top:2px;">{label}</div>
|
||||
</div>
|
||||
<table style="width:100%;border-collapse:collapse;font-size:14px;">
|
||||
{rows}
|
||||
</table>
|
||||
<div style="padding:20px 28px;background:#fafafa;text-align:center;">
|
||||
<a href="{DASHBOARD_URL}" style="display:inline-block;background:#0A84FF;color:#fff;text-decoration:none;padding:10px 22px;border-radius:10px;font-weight:600;font-size:14px;">Ver en el dashboard</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def send_new_response_email(label: str, data: dict) -> None:
|
||||
"""Envía el email de notificación. Nunca propaga errores SMTP."""
|
||||
if not (SMTP_HOST and SMTP_USER and NOTIFY_TO):
|
||||
logger.info("SMTP no configurado; se omite el envío de email.")
|
||||
return
|
||||
|
||||
try:
|
||||
msg = MIMEMultipart("alternative")
|
||||
msg["Subject"] = f"[Collina Forms] Nueva respuesta — {label}"
|
||||
msg["From"] = SMTP_USER
|
||||
msg["To"] = NOTIFY_TO
|
||||
msg["Date"] = formatdate(localtime=True)
|
||||
msg.attach(MIMEText(_build_html(label, data), "html", "utf-8"))
|
||||
|
||||
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=15) as server:
|
||||
server.ehlo()
|
||||
server.starttls()
|
||||
server.login(SMTP_USER, SMTP_PASS)
|
||||
server.sendmail(SMTP_USER, [NOTIFY_TO], msg.as_string())
|
||||
logger.info("Email de notificación enviado a %s", NOTIFY_TO)
|
||||
except Exception as exc: # noqa: BLE001 — nunca romper el flujo
|
||||
logger.error("Fallo al enviar email de notificación: %s", exc)
|
||||
+488
@@ -0,0 +1,488 @@
|
||||
"""Collina Forms — API FastAPI."""
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import (
|
||||
Depends,
|
||||
FastAPI,
|
||||
File,
|
||||
Form as FormField,
|
||||
HTTPException,
|
||||
Request,
|
||||
UploadFile,
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
import auth
|
||||
from auth import get_current_user, require_admin
|
||||
from database import get_db, init_db, SessionLocal
|
||||
from email_service import send_new_response_email
|
||||
from models import Form, Response, User
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("collina.main")
|
||||
|
||||
FORMS_DIR = os.environ.get("FORMS_DIR", "/data/forms")
|
||||
SLUG_RE = re.compile(r"^[a-z0-9-]+$")
|
||||
PUBLIC_BASE = os.environ.get("PUBLIC_BASE", "forms.collinasystems.com.mx")
|
||||
|
||||
app = FastAPI(title="Collina Forms", version="1.0.0")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Startup: crear tablas + primer admin
|
||||
# --------------------------------------------------------------------------- #
|
||||
@app.on_event("startup")
|
||||
def on_startup() -> None:
|
||||
os.makedirs(FORMS_DIR, exist_ok=True)
|
||||
init_db()
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if db.query(User).count() == 0:
|
||||
admin_user = os.environ.get("FIRST_ADMIN_USER", "admin")
|
||||
admin_pass = os.environ.get("FIRST_ADMIN_PASSWORD", "admin")
|
||||
admin_email = os.environ.get("NOTIFY_TO", "admin@collinasystems.com.mx")
|
||||
user = User(
|
||||
username=admin_user,
|
||||
email=admin_email,
|
||||
hashed_password=auth.hash_password(admin_pass),
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
logger.info("Primer admin creado: %s", admin_user)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Schemas
|
||||
# --------------------------------------------------------------------------- #
|
||||
class LoginIn(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
username: str
|
||||
is_admin: bool
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=80)
|
||||
email: EmailStr
|
||||
password: str = Field(min_length=4)
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class FormOut(BaseModel):
|
||||
id: int
|
||||
slug: str
|
||||
label: str
|
||||
description: str
|
||||
created_at: datetime
|
||||
is_active: bool
|
||||
response_count: int
|
||||
url: str
|
||||
|
||||
|
||||
class ResponseOut(BaseModel):
|
||||
id: int
|
||||
form_id: int
|
||||
submitted_at: datetime
|
||||
ip: str
|
||||
data: dict
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
SUBMIT_SCRIPT_TEMPLATE = """<script>
|
||||
(function() {{
|
||||
const SUBMIT_URL = '/api/submit/{slug}';
|
||||
const form = document.getElementById('discovery-form');
|
||||
if (!form) return;
|
||||
form.addEventListener('submit', async function(e) {{
|
||||
e.preventDefault();
|
||||
const data = {{}};
|
||||
new FormData(this).forEach((v, k) => {{
|
||||
if (data[k]) {{
|
||||
data[k] = Array.isArray(data[k]) ? [...data[k], v] : [data[k], v];
|
||||
}} else {{
|
||||
data[k] = v;
|
||||
}}
|
||||
}});
|
||||
const selected = [];
|
||||
document.querySelectorAll('.check-item.selected').forEach(item => {{
|
||||
const cb = item.querySelector('input[type="checkbox"]');
|
||||
const prio = item.querySelector('.priority-select select');
|
||||
selected.push({{ value: cb.value, priority: prio ? prio.value : '' }});
|
||||
}});
|
||||
data.automations = selected;
|
||||
try {{
|
||||
const res = await fetch(SUBMIT_URL, {{
|
||||
method: 'POST',
|
||||
headers: {{ 'Content-Type': 'application/json' }},
|
||||
body: JSON.stringify(data)
|
||||
}});
|
||||
if (res.ok) {{
|
||||
this.style.display = 'none';
|
||||
document.getElementById('success').classList.add('visible');
|
||||
window.scrollTo({{ top: 0, behavior: 'smooth' }});
|
||||
}}
|
||||
}} catch(err) {{
|
||||
console.error('Submit error:', err);
|
||||
}}
|
||||
}});
|
||||
}})();
|
||||
</script>"""
|
||||
|
||||
|
||||
def inject_submit_script(html: str, slug: str) -> str:
|
||||
"""Inserta el script de submit antes de </body> (o al final si no existe)."""
|
||||
script = SUBMIT_SCRIPT_TEMPLATE.format(slug=slug)
|
||||
lower = html.lower()
|
||||
idx = lower.rfind("</body>")
|
||||
if idx != -1:
|
||||
return html[:idx] + script + "\n" + html[idx:]
|
||||
return html + "\n" + script
|
||||
|
||||
|
||||
def form_to_out(f: Form) -> FormOut:
|
||||
return FormOut(
|
||||
id=f.id,
|
||||
slug=f.slug,
|
||||
label=f.label,
|
||||
description=f.description,
|
||||
created_at=f.created_at,
|
||||
is_active=f.is_active,
|
||||
response_count=f.response_count,
|
||||
url=f"{PUBLIC_BASE}/{f.slug}",
|
||||
)
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str:
|
||||
fwd = request.headers.get("x-forwarded-for")
|
||||
if fwd:
|
||||
return fwd.split(",")[0].strip()
|
||||
fwd = request.headers.get("x-real-ip")
|
||||
if fwd:
|
||||
return fwd.strip()
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Sistema
|
||||
# --------------------------------------------------------------------------- #
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Auth
|
||||
# --------------------------------------------------------------------------- #
|
||||
@app.post("/api/auth/login", response_model=TokenOut)
|
||||
def login(payload: LoginIn, db: Session = Depends(get_db)):
|
||||
user = auth.authenticate_user(db, payload.username, payload.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Usuario o contraseña incorrectos",
|
||||
)
|
||||
token = auth.create_access_token(user)
|
||||
return TokenOut(access_token=token, username=user.username, is_admin=auth.is_admin(user))
|
||||
|
||||
|
||||
@app.post("/api/auth/users", response_model=UserOut, status_code=201)
|
||||
def create_user(
|
||||
payload: UserCreate,
|
||||
_admin: User = Depends(require_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if db.query(User).filter(User.username == payload.username).first():
|
||||
raise HTTPException(status_code=409, detail="El usuario ya existe")
|
||||
user = User(
|
||||
username=payload.username,
|
||||
email=payload.email,
|
||||
hashed_password=auth.hash_password(payload.password),
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/api/auth/users", response_model=list[UserOut])
|
||||
def list_users(_admin: User = Depends(require_admin), db: Session = Depends(get_db)):
|
||||
return db.query(User).order_by(User.created_at.asc()).all()
|
||||
|
||||
|
||||
@app.delete("/api/auth/users/{user_id}", status_code=204)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
admin: User = Depends(require_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if user_id == admin.id:
|
||||
raise HTTPException(status_code=400, detail="No puedes eliminar tu propio usuario")
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Formularios
|
||||
# --------------------------------------------------------------------------- #
|
||||
@app.post("/api/forms/upload")
|
||||
async def upload_form(
|
||||
slug: str = FormField(...),
|
||||
label: str = FormField(...),
|
||||
description: str = FormField(""),
|
||||
file: UploadFile = File(...),
|
||||
user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
slug = slug.strip().lower()
|
||||
if not SLUG_RE.match(slug):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="El slug solo puede contener minúsculas, números y guiones",
|
||||
)
|
||||
if db.query(Form).filter(Form.slug == slug).first():
|
||||
raise HTTPException(status_code=409, detail="Ya existe un formulario con ese slug")
|
||||
|
||||
raw = await file.read()
|
||||
try:
|
||||
html = raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
html = raw.decode("latin-1")
|
||||
|
||||
html = inject_submit_script(html, slug)
|
||||
|
||||
form_dir = os.path.join(FORMS_DIR, slug)
|
||||
os.makedirs(form_dir, exist_ok=True)
|
||||
html_path = os.path.join(form_dir, "index.html")
|
||||
with open(html_path, "w", encoding="utf-8") as fh:
|
||||
fh.write(html)
|
||||
|
||||
form = Form(
|
||||
slug=slug,
|
||||
label=label,
|
||||
description=description or "",
|
||||
created_by=user.id,
|
||||
html_path=html_path,
|
||||
is_active=True,
|
||||
response_count=0,
|
||||
)
|
||||
db.add(form)
|
||||
db.commit()
|
||||
db.refresh(form)
|
||||
|
||||
return {
|
||||
"slug": form.slug,
|
||||
"url": f"{PUBLIC_BASE}/{form.slug}",
|
||||
"created_at": form.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/forms", response_model=list[FormOut])
|
||||
def list_forms(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
forms = db.query(Form).order_by(Form.created_at.desc()).all()
|
||||
return [form_to_out(f) for f in forms]
|
||||
|
||||
|
||||
@app.delete("/api/forms/{slug}", status_code=204)
|
||||
def delete_form(slug: str, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
form = db.query(Form).filter(Form.slug == slug).first()
|
||||
if not form:
|
||||
raise HTTPException(status_code=404, detail="Formulario no encontrado")
|
||||
|
||||
# Borra respuestas (cascade) y registro
|
||||
db.delete(form)
|
||||
db.commit()
|
||||
|
||||
# Borra los archivos del formulario
|
||||
form_dir = os.path.join(FORMS_DIR, slug)
|
||||
if os.path.isdir(form_dir):
|
||||
shutil.rmtree(form_dir, ignore_errors=True)
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Respuestas
|
||||
# --------------------------------------------------------------------------- #
|
||||
@app.post("/api/submit/{slug}")
|
||||
async def submit_response(slug: str, request: Request, db: Session = Depends(get_db)):
|
||||
form = db.query(Form).filter(Form.slug == slug, Form.is_active == True).first() # noqa: E712
|
||||
if not form:
|
||||
raise HTTPException(status_code=404, detail="Formulario no encontrado")
|
||||
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="JSON inválido")
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(status_code=400, detail="Se esperaba un objeto JSON")
|
||||
|
||||
resp = Response(
|
||||
form_id=form.id,
|
||||
ip=client_ip(request),
|
||||
data=json.dumps(data, ensure_ascii=False),
|
||||
)
|
||||
db.add(resp)
|
||||
form.response_count = (form.response_count or 0) + 1
|
||||
db.commit()
|
||||
|
||||
# Email — no debe romper el flujo
|
||||
try:
|
||||
send_new_response_email(form.label, data)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error inesperado enviando email: %s", exc)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/api/forms/{slug}/responses", response_model=list[ResponseOut])
|
||||
def list_responses(slug: str, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
form = db.query(Form).filter(Form.slug == slug).first()
|
||||
if not form:
|
||||
raise HTTPException(status_code=404, detail="Formulario no encontrado")
|
||||
responses = (
|
||||
db.query(Response)
|
||||
.filter(Response.form_id == form.id)
|
||||
.order_by(Response.submitted_at.desc())
|
||||
.all()
|
||||
)
|
||||
out = []
|
||||
for r in responses:
|
||||
try:
|
||||
parsed = json.loads(r.data)
|
||||
except Exception:
|
||||
parsed = {"_raw": r.data}
|
||||
out.append(
|
||||
ResponseOut(
|
||||
id=r.id,
|
||||
form_id=r.form_id,
|
||||
submitted_at=r.submitted_at,
|
||||
ip=r.ip,
|
||||
data=parsed,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@app.delete("/api/responses/{response_id}", status_code=204)
|
||||
def delete_response(
|
||||
response_id: int, user: User = Depends(get_current_user), db: Session = Depends(get_db)
|
||||
):
|
||||
resp = db.query(Response).filter(Response.id == response_id).first()
|
||||
if not resp:
|
||||
raise HTTPException(status_code=404, detail="Respuesta no encontrada")
|
||||
form = db.query(Form).filter(Form.id == resp.form_id).first()
|
||||
db.delete(resp)
|
||||
if form and form.response_count > 0:
|
||||
form.response_count -= 1
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
|
||||
def _flatten_automations(value) -> str:
|
||||
"""Aplana el array de automations a texto legible."""
|
||||
if not isinstance(value, list):
|
||||
return str(value)
|
||||
parts = []
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
v = item.get("value", "")
|
||||
p = item.get("priority", "")
|
||||
parts.append(f"{v} (prioridad: {p})" if p else f"{v}")
|
||||
else:
|
||||
parts.append(str(item))
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
@app.get("/api/forms/{slug}/export")
|
||||
def export_csv(slug: str, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
form = db.query(Form).filter(Form.slug == slug).first()
|
||||
if not form:
|
||||
raise HTTPException(status_code=404, detail="Formulario no encontrado")
|
||||
|
||||
responses = (
|
||||
db.query(Response)
|
||||
.filter(Response.form_id == form.id)
|
||||
.order_by(Response.submitted_at.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
parsed_rows = []
|
||||
data_keys: list[str] = []
|
||||
for r in responses:
|
||||
try:
|
||||
data = json.loads(r.data)
|
||||
except Exception:
|
||||
data = {}
|
||||
if not isinstance(data, dict):
|
||||
data = {"_raw": data}
|
||||
parsed_rows.append((r, data))
|
||||
for k in data.keys():
|
||||
if k not in data_keys:
|
||||
data_keys.append(k)
|
||||
|
||||
fieldnames = ["id", "submitted_at", "ip"] + data_keys
|
||||
|
||||
buffer = io.StringIO()
|
||||
writer = csv.DictWriter(buffer, fieldnames=fieldnames, extrasaction="ignore")
|
||||
writer.writeheader()
|
||||
for r, data in parsed_rows:
|
||||
row = {
|
||||
"id": r.id,
|
||||
"submitted_at": r.submitted_at.isoformat() if r.submitted_at else "",
|
||||
"ip": r.ip,
|
||||
}
|
||||
for k in data_keys:
|
||||
value = data.get(k, "")
|
||||
if k == "automations":
|
||||
row[k] = _flatten_automations(value)
|
||||
elif isinstance(value, (list, dict)):
|
||||
row[k] = json.dumps(value, ensure_ascii=False)
|
||||
else:
|
||||
row[k] = value
|
||||
writer.writerow(row)
|
||||
|
||||
buffer.seek(0)
|
||||
filename = f"{slug}-respuestas.csv"
|
||||
# BOM para que Excel abra UTF-8 correctamente
|
||||
content = "" + buffer.getvalue()
|
||||
return StreamingResponse(
|
||||
iter([content]),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Modelos ORM: users, forms, responses."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from database import Base
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(80), unique=True, nullable=False, index=True)
|
||||
email: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow, nullable=False)
|
||||
|
||||
forms: Mapped[list["Form"]] = relationship(back_populates="creator")
|
||||
|
||||
|
||||
class Form(Base):
|
||||
__tablename__ = "forms"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
slug: Mapped[str] = mapped_column(String(120), unique=True, nullable=False, index=True)
|
||||
label: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
description: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow, nullable=False)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
html_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
response_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
|
||||
creator: Mapped["User"] = relationship(back_populates="forms")
|
||||
responses: Mapped[list["Response"]] = relationship(
|
||||
back_populates="form", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class Response(Base):
|
||||
__tablename__ = "responses"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
form_id: Mapped[int] = mapped_column(ForeignKey("forms.id"), nullable=False, index=True)
|
||||
submitted_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow, nullable=False)
|
||||
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
data: Mapped[str] = mapped_column(Text, default="{}", nullable=False) # JSON serializado
|
||||
|
||||
form: Mapped["Form"] = relationship(back_populates="responses")
|
||||
@@ -0,0 +1,9 @@
|
||||
fastapi==0.111.0
|
||||
uvicorn[standard]==0.30.1
|
||||
pydantic==2.7.4
|
||||
email-validator==2.2.0
|
||||
SQLAlchemy==2.0.30
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib==1.7.4
|
||||
bcrypt==4.0.1
|
||||
python-multipart==0.0.9
|
||||
@@ -0,0 +1,15 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- forms_data:/data
|
||||
env_file:
|
||||
- .env
|
||||
ports:
|
||||
- "80:80"
|
||||
|
||||
volumes:
|
||||
forms_data:
|
||||
@@ -0,0 +1,915 @@
|
||||
<!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 => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||
}[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> › ${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> › ${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>
|
||||
@@ -0,0 +1,198 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Collina Forms — Acceso</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);
|
||||
--danger: #FF453A;
|
||||
--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;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-primary);
|
||||
padding: 24px;
|
||||
}
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
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: 20px;
|
||||
box-shadow: var(--glass-shadow);
|
||||
padding: 40px 36px;
|
||||
}
|
||||
.wordmark {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 5px;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.subtitle {
|
||||
text-align: center;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 32px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.field { margin-bottom: 18px; }
|
||||
.field label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.input-wrap { position: relative; }
|
||||
.input-wrap svg {
|
||||
position: absolute;
|
||||
left: 14px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
stroke: var(--text-tertiary);
|
||||
pointer-events: none;
|
||||
}
|
||||
input {
|
||||
width: 100%;
|
||||
padding: 13px 14px 13px 44px;
|
||||
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;
|
||||
transition: all 0.2s ease;
|
||||
outline: none;
|
||||
}
|
||||
input::placeholder { color: var(--text-tertiary); }
|
||||
input:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
margin-top: 8px;
|
||||
background: var(--accent);
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
box-shadow: 0 0 20px var(--accent-glow);
|
||||
}
|
||||
.btn-primary:disabled { opacity: 0.6; cursor: default; }
|
||||
.error {
|
||||
display: none;
|
||||
margin-top: 16px;
|
||||
padding: 12px 14px;
|
||||
background: rgba(255, 69, 58, 0.12);
|
||||
border: 1px solid rgba(255, 69, 58, 0.3);
|
||||
border-radius: 10px;
|
||||
color: var(--danger);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
.error.visible { display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-card">
|
||||
<div class="wordmark">COLLINA SYSTEMS</div>
|
||||
<div class="subtitle">Collina Forms</div>
|
||||
<form id="login-form">
|
||||
<div class="field">
|
||||
<label for="username">Usuario</label>
|
||||
<div class="input-wrap">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
|
||||
<input id="username" name="username" type="text" placeholder="admin" autocomplete="username" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="password">Contraseña</label>
|
||||
<div class="input-wrap">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
|
||||
<input id="password" name="password" type="password" placeholder="••••••••" autocomplete="current-password" required>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-primary" type="submit" id="submit-btn">Entrar</button>
|
||||
<div class="error" id="error"></div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Si ya hay token válido, ir al dashboard
|
||||
if (localStorage.getItem('collina_token')) {
|
||||
window.location.href = '/dashboard';
|
||||
}
|
||||
|
||||
const form = document.getElementById('login-form');
|
||||
const errorBox = document.getElementById('error');
|
||||
const btn = document.getElementById('submit-btn');
|
||||
|
||||
function showError(msg) {
|
||||
errorBox.textContent = msg;
|
||||
errorBox.classList.add('visible');
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
errorBox.classList.remove('visible');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Entrando…';
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
if (!res.ok) {
|
||||
showError('Usuario o contraseña incorrectos');
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
localStorage.setItem('collina_token', data.access_token);
|
||||
localStorage.setItem('collina_username', data.username);
|
||||
localStorage.setItem('collina_is_admin', data.is_admin ? '1' : '0');
|
||||
window.location.href = '/dashboard';
|
||||
} catch (err) {
|
||||
showError('No se pudo conectar con el servidor');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Entrar';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name forms.collinasystems.com.mx;
|
||||
charset utf-8;
|
||||
client_max_body_size 10M;
|
||||
|
||||
# API -> FastAPI
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Panel admin
|
||||
location = /login {
|
||||
root /usr/share/nginx/html;
|
||||
try_files /login.html =404;
|
||||
}
|
||||
|
||||
location = /dashboard {
|
||||
root /usr/share/nginx/html;
|
||||
try_files /dashboard.html =404;
|
||||
}
|
||||
|
||||
# Formularios públicos subidos por el usuario
|
||||
location / {
|
||||
root /data/forms;
|
||||
try_files $uri $uri/ $uri/index.html @fallback;
|
||||
}
|
||||
|
||||
location @fallback {
|
||||
return 302 /dashboard;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Asegurar directorios del volumen persistente
|
||||
mkdir -p /data/forms
|
||||
|
||||
# Arrancar FastAPI en background (solo accesible localmente; nginx hace de proxy)
|
||||
uvicorn main:app --host 127.0.0.1 --port 8000 &
|
||||
|
||||
# Arrancar nginx en foreground
|
||||
nginx -g 'daemon off;'
|
||||
Reference in new issue
Block a user