commit 6763f20b73b06c9cf2389438dd195774a3af1ad8 Author: Jorem Juárez Date: Mon Jun 8 19:43:05 2026 -0600 feat: collina forms platform v1 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..38e191f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.git +.gitignore +*.md +.env +.venv +__pycache__/ +*.pyc +data/ +*.db diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ffe6c9f --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a5942f6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +__pycache__/ +*.pyc +*.db +data/ +.venv/ +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5c6717f --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..4fb2acb --- /dev/null +++ b/README.md @@ -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 `""" + + +def inject_submit_script(html: str, slug: str) -> str: + """Inserta el script de submit antes de (o al final si no existe).""" + script = SUBMIT_SCRIPT_TEMPLATE.format(slug=slug) + lower = html.lower() + idx = lower.rfind("") + 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}"'}, + ) diff --git a/backend/models.py b/backend/models.py new file mode 100644 index 0000000..b0317b5 --- /dev/null +++ b/backend/models.py @@ -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") diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..6c206c5 --- /dev/null +++ b/backend/requirements.txt @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..315502d --- /dev/null +++ b/docker-compose.yml @@ -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: diff --git a/frontend/dashboard.html b/frontend/dashboard.html new file mode 100644 index 0000000..3795005 --- /dev/null +++ b/frontend/dashboard.html @@ -0,0 +1,915 @@ + + + + + + Collina Forms — Dashboard + + + + + + +
+ +
+ + + + + + + +
+ + + + diff --git a/frontend/login.html b/frontend/login.html new file mode 100644 index 0000000..b79d5e1 --- /dev/null +++ b/frontend/login.html @@ -0,0 +1,198 @@ + + + + + + Collina Forms — Acceso + + + +
+
COLLINA SYSTEMS
+
Collina Forms
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+ +
+
+
+ + + + diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 0000000..3bdaacd --- /dev/null +++ b/nginx.conf @@ -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; + } +} diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..e12878b --- /dev/null +++ b/start.sh @@ -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;'