From 506de5e271482c3e56e916887c28502b84fa7f7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Tue, 26 May 2026 12:21:05 -0600 Subject: [PATCH] =?UTF-8?q?Adaptador=20Reels=20x=20Expedientes=20-=20versi?= =?UTF-8?q?=C3=B3n=20inicial?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Estado tal cual recibido antes de hardening: - backend Express + Postgres + Anthropic SDK - frontend Vite + React + nginx proxy - docker-compose para Coolify --- .env.example | 14 ++ .gitignore | 17 +++ DESPLIEGUE.md | 102 +++++++++++++ backend/.dockerignore | 3 + backend/Dockerfile | 15 ++ backend/package.json | 19 +++ backend/schema.sql | 23 +++ backend/server.js | 166 +++++++++++++++++++++ docker-compose.yml | 25 ++++ frontend/.dockerignore | 4 + frontend/App.jsx | 310 ++++++++++++++++++++++++++++++++++++++++ frontend/Dockerfile | 13 ++ frontend/index.html | 12 ++ frontend/main.jsx | 5 + frontend/nginx.conf | 22 +++ frontend/package.json | 20 +++ frontend/vite.config.js | 7 + 17 files changed, 777 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 DESPLIEGUE.md create mode 100644 backend/.dockerignore create mode 100644 backend/Dockerfile create mode 100644 backend/package.json create mode 100644 backend/schema.sql create mode 100644 backend/server.js create mode 100644 docker-compose.yml create mode 100644 frontend/.dockerignore create mode 100644 frontend/App.jsx create mode 100644 frontend/Dockerfile create mode 100644 frontend/index.html create mode 100644 frontend/main.jsx create mode 100644 frontend/nginx.conf create mode 100644 frontend/package.json create mode 100644 frontend/vite.config.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e4154a0 --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +# Variables de entorno — configúralas en el panel de Coolify (NO subas valores reales a Git) + +# Cadena de conexión del Postgres creado en Coolify. +# Cópiala desde el recurso PostgreSQL de Coolify. Formato: +DATABASE_URL=postgresql://USUARIO:CONTRASENA@HOST:5432/NOMBRE_DB + +# Tu API key de Anthropic (console.anthropic.com → Settings → API Keys) +ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxx + +# Modelo. Opus = máxima calidad (más caro). Para abaratar: claude-sonnet-4-6 +ANTHROPIC_MODEL=claude-opus-4-20250514 + +# Tokens máximos de salida del brief +MAX_TOKENS=4000 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72a5656 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Dependencias +node_modules/ +*/node_modules/ + +# Builds +frontend/dist/ +backend/dist/ + +# Secretos y entorno (NUNCA subir al repo) +.env +.env.local +*/.env + +# Logs y temporales +*.log +npm-debug.log* +.DS_Store diff --git a/DESPLIEGUE.md b/DESPLIEGUE.md new file mode 100644 index 0000000..6f2375d --- /dev/null +++ b/DESPLIEGUE.md @@ -0,0 +1,102 @@ +# Despliegue en Coolify — Adaptador Reels × Expedientes + +Tu servidor `srv1413204` corre **Coolify** (proxy Docker en los puertos 80/443) con n8n ya desplegado. Esta app se despliega **dentro de Coolify**, sin tocar Nginx ni certbot a mano. Coolify se encarga del dominio, HTTPS y reinicios. + +## Arquitectura + +``` +reels.collinasystems.com.mx + │ (proxy de Coolify, HTTPS automático) + ▼ + frontend (nginx) ── /api/* ──► backend (Express :3001) + │ + ├─ PostgreSQL (recurso de Coolify) + └─ API de Anthropic (tu key) +``` + +El frontend sirve la web y reenvía internamente `/api` al backend. El backend guarda en Postgres y llama a Anthropic con tu API key (que vive solo como variable de entorno en Coolify, nunca en el navegador). + +--- + +## Paso 0 · DNS + +En tu gestor de DNS de `collinasystems.com.mx`, crea un registro A: + +``` +Tipo: A Nombre: reels Valor: TTL: 3600 +``` + +Espera a que propague (`ping reels.collinasystems.com.mx` debe devolver tu IP). + +## Paso 1 · Subir el código a Gitea + +### 1.1 · Crea el repositorio en Gitea +En tu Gitea: **+ → New Repository**, nómbralo p. ej. `collina-reels`, privado. NO lo inicialices con README (subirás el tuyo). + +### 1.2 · Sube el código desde tu máquina +Descomprime el ZIP y, dentro de la carpeta `collina-reels/`: + +```bash +git init +git add . +git commit -m "Adaptador Reels x Expedientes - versión inicial" +git branch -M main +git remote add origin https://TU-GITEA/USUARIO/collina-reels.git +git push -u origin main +``` + +Estructura que se sube: +``` +collina-reels/ +├─ docker-compose.yml +├─ .gitignore (evita subir node_modules y .env) +├─ backend/ (Dockerfile, .dockerignore, server.js, schema.sql, package.json) +└─ frontend/ (Dockerfile, .dockerignore, nginx.conf, App.jsx, main.jsx, index.html, package.json, vite.config.js) +``` + +**Importante:** el `.gitignore` ya excluye `.env` y `node_modules`. NO subas ninguna API key ni contraseña al repo. Esos valores van solo en el panel de Coolify (Paso 3). + +### 1.3 · Conecta Gitea con Coolify +Si aún no lo hiciste para otros proyectos: en Coolify → **Sources** → añade tu Gitea (vía GitHub App style o token/SSH deploy key, según cómo tengas Gitea). Una vez conectada, Coolify podrá clonar el repo y, si activas el webhook, redeployar en cada `git push`. + +## Paso 2 · Crear el PostgreSQL en Coolify + +1. En tu proyecto de Coolify → **+ New** → **Database** → **PostgreSQL**. +2. Déjalo en la misma red/servidor que la app. +3. Cuando arranque, copia la **Connection String interna** (la que usa el nombre de host interno de Docker, no `localhost`). La necesitarás en el Paso 3. + +> Esto reemplaza el Postgres que instalaste con `apt`. Aquel puede quedarse parado; si quieres liberarlo luego: `sudo systemctl disable --now postgresql`. + +## Paso 3 · Crear la aplicación (Docker Compose desde Gitea) + +1. **+ New** → **Resource** → **Private Repository (with Source)** → elige tu Gitea y el repo `collina-reels`, rama `main`. +2. Build Pack: **Docker Compose**. Coolify detecta el `docker-compose.yml` de la raíz. +3. En **Environment Variables**, añade (ver `.env.example`): + - `DATABASE_URL` → la connection string interna del Paso 2 + - `ANTHROPIC_API_KEY` → tu key de console.anthropic.com + - `ANTHROPIC_MODEL` → `claude-opus-4-20250514` (o `claude-sonnet-4-6` para abaratar) + - `MAX_TOKENS` → `4000` +4. En el servicio **frontend**, asigna el dominio: `reels.collinasystems.com.mx`. Coolify le pondrá el certificado HTTPS solo. + > El `docker-compose.yml` incluye `SERVICE_FQDN_FRONTEND_80` para ayudar a Coolify a mapear dominio→puerto 80. Si tu versión de Coolify no la usa, ignóralo: lo que cuenta es asignar el dominio al servicio frontend desde la pestaña de dominios del panel. Asegúrate de que el dominio apunte al servicio **frontend** y al puerto **80**, no al backend. +5. El servicio **backend** NO necesita dominio público (se accede por dentro vía `/api`). +6. (Opcional) Activa el **webhook** en Gitea para que cada `git push` a `main` dispare un redeploy automático. + +## Paso 4 · Desplegar + +Pulsa **Deploy**. Coolify construye las dos imágenes (frontend y backend) y las levanta. El backend, al arrancar, crea las tablas automáticamente (lee `schema.sql`). + +## Paso 5 · Verificar + +- `https://reels.collinasystems.com.mx` → carga la interfaz. +- `https://reels.collinasystems.com.mx/api/health` → debe responder `{"ok":true,...}`. +- Crea un análisis y un expediente, y genera un brief de prueba. + +--- + +## Notas + +- **Coste:** cada brief con Opus son centavos. Pon un límite de gasto en console.anthropic.com (Settings → Billing) para empezar, p. ej. 20 USD/mes. +- **Cambiar de modelo:** edita `ANTHROPIC_MODEL` en Coolify y redeploy. No hace falta tocar código. +- **Formatos de archivo:** TXT, MD, DOCX y PDF (con texto). El `.doc` antiguo y los PDF escaneados sin texto no se extraen. +- **El Postgres de apt y el firewall:** el `ufw` que activaste permite 80/443/22, suficiente para Coolify. No lo desactives. +- **Kernel pendiente:** tu servidor avisó de una actualización de kernel. Reinícialo en un momento tranquilo (`sudo reboot`) para cargar el 6.8.0-117; Coolify y sus contenedores levantan solos al arrancar. diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..c81b8d3 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +.env diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..050a696 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,15 @@ +FROM node:20-slim + +WORKDIR /app + +# Dependencias primero (mejor cacheo de capas) +COPY package.json ./ +RUN npm install --omit=dev + +# Código +COPY server.js schema.sql ./ + +ENV PORT=3001 +EXPOSE 3001 + +CMD ["node", "server.js"] diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..9c56e3f --- /dev/null +++ b/backend/package.json @@ -0,0 +1,19 @@ +{ + "name": "collina-reels-backend", + "version": "1.0.0", + "description": "Backend del Adaptador Reels x Expedientes - Collina Systems", + "main": "server.js", + "type": "module", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "@anthropic-ai/sdk": "^0.32.1", + "cors": "^2.8.5", + "express": "^4.21.2", + "mammoth": "^1.8.0", + "multer": "^1.4.5-lts.1", + "pdf-parse": "^1.1.1", + "pg": "^8.13.1" + } +} diff --git a/backend/schema.sql b/backend/schema.sql new file mode 100644 index 0000000..7835bc8 --- /dev/null +++ b/backend/schema.sql @@ -0,0 +1,23 @@ +-- Esquema de la base de datos para el Adaptador Reels × Expedientes +-- Se ejecuta automáticamente al arrancar el backend (idempotente). + +CREATE TABLE IF NOT EXISTS reels ( + id TEXT PRIMARY KEY, + titulo TEXT NOT NULL, + hook TEXT DEFAULT '', + estructura TEXT DEFAULT '', + tono TEXT DEFAULT '', + formato TEXT DEFAULT '', + notas TEXT DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS expedientes ( + id TEXT PRIMARY KEY, + titulo TEXT NOT NULL, + contenido TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_reels_created ON reels (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_exp_created ON expedientes (created_at DESC); diff --git a/backend/server.js b/backend/server.js new file mode 100644 index 0000000..d0d687e --- /dev/null +++ b/backend/server.js @@ -0,0 +1,166 @@ +import express from "express"; +import cors from "cors"; +import multer from "multer"; +import pkg from "pg"; +import { readFileSync } from "fs"; +import { fileURLToPath } from "url"; +import { dirname, join } from "path"; +import mammoth from "mammoth"; +import { createRequire } from "module"; +import Anthropic from "@anthropic-ai/sdk"; + +const require = createRequire(import.meta.url); +const pdfParse = require("pdf-parse"); + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const { Pool } = pkg; + +// ── Config desde variables de entorno ────────────────────────── +const PORT = process.env.PORT || 3001; +const DATABASE_URL = process.env.DATABASE_URL; // la inyecta Coolify +const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +const MODEL = process.env.ANTHROPIC_MODEL || "claude-opus-4-20250514"; +const MAX_TOKENS = parseInt(process.env.MAX_TOKENS || "4000", 10); + +if (!DATABASE_URL) { console.error("FALTA DATABASE_URL"); process.exit(1); } +if (!ANTHROPIC_API_KEY) console.warn("AVISO: falta ANTHROPIC_API_KEY; /api/generar fallará hasta configurarla."); + +const pool = new Pool({ connectionString: DATABASE_URL }); +const anthropic = new Anthropic({ apiKey: ANTHROPIC_API_KEY }); + +// ── Inicialización del esquema ───────────────────────────────── +async function initDB() { + const sql = readFileSync(join(__dirname, "schema.sql"), "utf8"); + await pool.query(sql); + console.log("Esquema verificado."); +} + +// ── App ──────────────────────────────────────────────────────── +const app = express(); +app.use(cors()); +app.use(express.json({ limit: "5mb" })); +const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 15 * 1024 * 1024 } }); + +const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7); + +app.get("/api/health", (_req, res) => res.json({ ok: true, model: MODEL })); + +// ── Extracción de texto de archivos subidos ──────────────────── +app.post("/api/extract", upload.single("file"), async (req, res) => { + try { + if (!req.file) return res.status(400).json({ error: "No se recibió archivo." }); + const name = req.file.originalname.toLowerCase(); + const buf = req.file.buffer; + let text = ""; + if (name.endsWith(".txt") || name.endsWith(".md")) { + text = buf.toString("utf8"); + } else if (name.endsWith(".docx")) { + text = (await mammoth.extractRawText({ buffer: buf })).value; + } else if (name.endsWith(".pdf")) { + text = (await pdfParse(buf)).text; + } else if (name.endsWith(".doc")) { + return res.status(415).json({ error: "El formato .doc antiguo no se soporta. Convierte a .docx o pega el texto." }); + } else { + return res.status(415).json({ error: "Formato no soportado. Usa MD, TXT, DOCX o PDF." }); + } + text = (text || "").trim(); + if (!text) return res.status(422).json({ error: "El archivo no contiene texto legible (¿PDF escaneado?)." }); + res.json({ text, filename: req.file.originalname }); + } catch (e) { + res.status(500).json({ error: "No se pudo procesar el archivo: " + e.message }); + } +}); + +// ── CRUD Reels ───────────────────────────────────────────────── +app.get("/api/reels", async (_req, res) => { + const { rows } = await pool.query("SELECT * FROM reels ORDER BY created_at DESC"); + res.json(rows); +}); +app.post("/api/reels", async (req, res) => { + const { titulo, hook = "", estructura = "", tono = "", formato = "", notas = "" } = req.body; + if (!titulo?.trim()) return res.status(400).json({ error: "El título es obligatorio." }); + const id = uid(); + const { rows } = await pool.query( + `INSERT INTO reels (id,titulo,hook,estructura,tono,formato,notas) + VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`, + [id, titulo, hook, estructura, tono, formato, notas] + ); + res.status(201).json(rows[0]); +}); +app.delete("/api/reels/:id", async (req, res) => { + await pool.query("DELETE FROM reels WHERE id=$1", [req.params.id]); + res.json({ deleted: req.params.id }); +}); + +// ── CRUD Expedientes ─────────────────────────────────────────── +app.get("/api/expedientes", async (_req, res) => { + const { rows } = await pool.query("SELECT * FROM expedientes ORDER BY created_at DESC"); + res.json(rows); +}); +app.post("/api/expedientes", async (req, res) => { + const { titulo, contenido } = req.body; + if (!titulo?.trim() || !contenido?.trim()) + return res.status(400).json({ error: "Título y contenido son obligatorios." }); + const id = uid(); + const { rows } = await pool.query( + "INSERT INTO expedientes (id,titulo,contenido) VALUES ($1,$2,$3) RETURNING *", + [id, titulo, contenido] + ); + res.status(201).json(rows[0]); +}); +app.delete("/api/expedientes/:id", async (req, res) => { + await pool.query("DELETE FROM expedientes WHERE id=$1", [req.params.id]); + res.json({ deleted: req.params.id }); +}); + +// ── Generación del brief (Anthropic) ─────────────────────────── +app.post("/api/generar", async (req, res) => { + try { + const { reelId, expedienteId } = req.body; + const reelR = await pool.query("SELECT * FROM reels WHERE id=$1", [reelId]); + const expR = await pool.query("SELECT * FROM expedientes WHERE id=$1", [expedienteId]); + const reel = reelR.rows[0], exp = expR.rows[0]; + if (!reel || !exp) return res.status(404).json({ error: "Reel o expediente no encontrado." }); + + const prompt = `Eres un director creativo y estratega de contenido para redes sociales, experto en adaptar mensajes comerciales al estilo de creadores concretos. + +=== ANÁLISIS TÉCNICO DEL REEL DEL CREADOR === +Etiqueta: ${reel.titulo} +Hook / primeros 3s: ${reel.hook || "(no especificado)"} +Estructura y ritmo: ${reel.estructura || "(no especificado)"} +Tono y lenguaje: ${reel.tono || "(no especificado)"} +Duración / formato / CTA: ${reel.formato || "(no especificado)"} +Notas adicionales: ${reel.notas || "(ninguna)"} + +=== EXPEDIENTE COMERCIAL DE LA SOLUCIÓN === +Nombre: ${exp.titulo} +Contenido: +${exp.contenido} + +=== TAREA === +Genera UN BRIEF DE PRODUCCIÓN completo y accionable que adapte la solución comercial al estilo del creador analizado. El brief DEBE incluir, en este orden: + +1. RESUMEN DE LA PIEZA: objetivo, plataforma, duración estimada y CTA principal. +2. GUION ADAPTADO: el guion completo dividido por bloques con marcas de segundos (ej. 0-3s, 3-8s…), replicando el hook, estructura, ritmo y tono del creador, pero vendiendo la solución del expediente. Incluye lo que se dice en voz/texto en cada bloque. +3. INDICACIONES DE PRODUCCIÓN para cada bloque: encuadre y movimiento de cámara, lo que aparece en pantalla, texto sobreimpreso, ritmo de edición/cortes y sugerencia de música/sonido. +4. NOTAS FINALES: variantes de hook alternativas y recomendaciones de optimización. + +Escribe en español, directo y listo para rodar. No incluyas preámbulos ni explicaciones meta: entrega solo el brief.`; + + const msg = await anthropic.messages.create({ + model: MODEL, + max_tokens: MAX_TOKENS, + messages: [{ role: "user", content: prompt }], + }); + const brief = msg.content.filter((b) => b.type === "text").map((b) => b.text).join("\n").trim(); + res.json({ brief, model: MODEL }); + } catch (e) { + const status = e?.status || 500; + res.status(status).json({ error: "Error al generar: " + (e?.message || "desconocido") }); + } +}); + +// ── Arranque ─────────────────────────────────────────────────── +initDB() + .then(() => app.listen(PORT, () => console.log(`Backend escuchando en :${PORT} (modelo ${MODEL})`))) + .catch((e) => { console.error("Fallo al iniciar DB:", e); process.exit(1); }); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..96d65b8 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,25 @@ +services: + backend: + build: ./backend + restart: unless-stopped + environment: + # Coolify inyecta estas variables (configúralas en el panel): + - DATABASE_URL=${DATABASE_URL} + - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} + - ANTHROPIC_MODEL=${ANTHROPIC_MODEL:-claude-opus-4-20250514} + - MAX_TOKENS=${MAX_TOKENS:-4000} + - PORT=3001 + expose: + - "3001" + + frontend: + build: ./frontend + restart: unless-stopped + depends_on: + - backend + environment: + # Coolify genera el dominio y el certificado a partir de esta variable. + # Déjala así: en el panel asignas reels.collinasystems.com.mx al servicio. + - SERVICE_FQDN_FRONTEND_80 + expose: + - "80" diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..cd44c15 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,4 @@ +node_modules +dist +npm-debug.log +.env diff --git a/frontend/App.jsx b/frontend/App.jsx new file mode 100644 index 0000000..2f6407e --- /dev/null +++ b/frontend/App.jsx @@ -0,0 +1,310 @@ +import React, { useState, useEffect, useCallback, useRef } from "react"; +import { Film, FileText, Sparkles, Trash2, Plus, Copy, Check, Loader2, Database, ChevronRight, UploadCloud, FileWarning } from "lucide-react"; + +const API = import.meta.env.VITE_API_BASE || "/api"; + +async function api(path, opts = {}) { + const res = await fetch(API + path, { + headers: opts.body && !(opts.body instanceof FormData) ? { "Content-Type": "application/json" } : undefined, + ...opts, + }); + if (!res.ok) { + let msg = "Error " + res.status; + try { msg = (await res.json()).error || msg; } catch {} + throw new Error(msg); + } + return res.json(); +} + +function Field({ label, value, onChange, textarea, rows = 3, placeholder }) { + const Comp = textarea ? "textarea" : "input"; + return ( + + ); +} + +function DropBox({ onText, hint }) { + const [drag, setDrag] = useState(false); + const [status, setStatus] = useState(null); + const inputRef = useRef(); + + const handle = async (file) => { + if (!file) return; + setStatus({ type: "load", msg: `Subiendo ${file.name}…` }); + try { + const fd = new FormData(); + fd.append("file", file); + const { text, filename } = await api("/extract", { method: "POST", body: fd }); + onText(text, filename); + setStatus({ type: "ok", msg: `${filename} cargado (${text.length} caracteres).` }); + } catch (e) { + setStatus({ type: "err", msg: e.message }); + } + }; + + return ( +
+ Soltar archivo (MD, TXT, DOCX, PDF) +
{ e.preventDefault(); setDrag(true); }} + onDragLeave={() => setDrag(false)} + onDrop={(e) => { e.preventDefault(); setDrag(false); handle(e.dataTransfer.files[0]); }} + onClick={() => inputRef.current?.click()} + style={{ + border: `1.5px dashed ${drag ? "var(--accent)" : "rgba(255,255,255,.25)"}`, + background: drag ? "rgba(255,255,255,.10)" : "rgba(255,255,255,.04)", + borderRadius: 14, padding: "20px 16px", textAlign: "center", cursor: "pointer", + transition: "all .15s", color: "var(--muted)", + }}> + +
Arrastra aquí o haz clic para subir
+
{hint}
+ handle(e.target.files[0])} /> +
+ {status && ( +
+ {status.type === "err" ? : status.type === "load" ? : } + {status.msg} +
+ )} +
+ ); +} + +export default function App() { + const [tab, setTab] = useState("generar"); + const [reels, setReels] = useState([]); + const [exps, setExps] = useState([]); + const [loaded, setLoaded] = useState(false); + const [loadErr, setLoadErr] = useState(""); + + const [reelForm, setReelForm] = useState(blankReel()); + const [expForm, setExpForm] = useState(blankExp()); + + const [selReel, setSelReel] = useState(null); + const [selExp, setSelExp] = useState(null); + const [output, setOutput] = useState(""); + const [busy, setBusy] = useState(false); + const [err, setErr] = useState(""); + const [copied, setCopied] = useState(false); + + function blankReel() { return { titulo: "", hook: "", estructura: "", tono: "", formato: "", notas: "" }; } + function blankExp() { return { titulo: "", contenido: "" }; } + + const refresh = useCallback(async () => { + try { + const [r, e] = await Promise.all([api("/reels"), api("/expedientes")]); + setReels(r); setExps(e); setLoaded(true); setLoadErr(""); + } catch (e) { setLoadErr("No se pudo conectar con el backend: " + e.message); setLoaded(true); } + }, []); + + useEffect(() => { refresh(); }, [refresh]); + + const addReel = async () => { + if (!reelForm.titulo.trim()) return; + try { await api("/reels", { method: "POST", body: JSON.stringify(reelForm) }); setReelForm(blankReel()); refresh(); } + catch (e) { alert(e.message); } + }; + const addExp = async () => { + if (!expForm.titulo.trim() || !expForm.contenido.trim()) return; + try { await api("/expedientes", { method: "POST", body: JSON.stringify(expForm) }); setExpForm(blankExp()); refresh(); } + catch (e) { alert(e.message); } + }; + const delReel = async (id) => { await api("/reels/" + id, { method: "DELETE" }); if (selReel === id) setSelReel(null); refresh(); }; + const delExp = async (id) => { await api("/expedientes/" + id, { method: "DELETE" }); if (selExp === id) setSelExp(null); refresh(); }; + + const generar = async () => { + setErr(""); setOutput(""); setCopied(false); + if (!selReel || !selExp) { setErr("Selecciona un análisis técnico y un expediente."); return; } + setBusy(true); + try { + const { brief } = await api("/generar", { method: "POST", body: JSON.stringify({ reelId: selReel, expedienteId: selExp }) }); + setOutput(brief || "(Sin respuesta del modelo)"); + } catch (e) { setErr(e.message); } + finally { setBusy(false); } + }; + + const copy = async () => { + try { await navigator.clipboard.writeText(output); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch {} + }; + + const TABS = [ + { id: "generar", label: "Generar brief", icon: Sparkles }, + { id: "reels", label: "Análisis técnicos", icon: Film, count: reels.length }, + { id: "exp", label: "Expedientes", icon: FileText, count: exps.length }, + ]; + + return ( +
+ +
+
+
+
+

Adaptador Reels × Expedientes

+

+ Genera un brief de producción con el guion adaptado al estilo del creador. +

+
+
{loaded ? `${reels.length} reels · ${exps.length} exp.` : "cargando…"}
+
+ + {loadErr &&
{loadErr}
} + + + +
+ {tab === "generar" && ( +
+
+ + +
+
+ + {err &&

{err}

} +
+ {output && ( +
+
+ Brief de producción + +
+
{output}
+
+ )} +
+ )} + + {tab === "reels" && ( +
+
+

Nuevo análisis técnico

+ setReelForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), notas: (f.notas ? f.notas + "\n\n" : "") + text }))} /> + setReelForm({ ...reelForm, titulo: v })} placeholder="Ej. Reel viral @creador" /> + setReelForm({ ...reelForm, hook: v })} textarea rows={2} /> + setReelForm({ ...reelForm, estructura: v })} textarea rows={2} /> + setReelForm({ ...reelForm, tono: v })} textarea rows={2} /> + setReelForm({ ...reelForm, formato: v })} textarea rows={2} /> + setReelForm({ ...reelForm, notas: v })} textarea rows={3} /> + +
+ (<> + {r.titulo} + {r.hook &&

Hook: {r.hook}

} + {r.tono &&

Tono: {r.tono}

} + {r.formato &&

Formato: {r.formato}

} + )} /> +
+ )} + + {tab === "exp" && ( +
+
+

Nuevo expediente comercial

+ setExpForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), contenido: (f.contenido ? f.contenido + "\n\n" : "") + text }))} /> + setExpForm({ ...expForm, titulo: v })} placeholder="Ej. Solución CRM para pymes" /> + setExpForm({ ...expForm, contenido: v })} textarea rows={9} placeholder="Pega o sube propuesta de valor, beneficios, prueba, precio, CTA…" /> + +
+ (<> + {e.titulo} +

{e.contenido}

+ )} /> +
+ )} +
+
+
+ ); +} + +function Selector({ title, icon: Icon, items, selId, onSel, empty }) { + return ( +
+
{title}
+ {items.length === 0 ?

{empty}

: ( +
+ {items.map((it) => { + const active = selId === it.id; + return ( + + ); + })} +
+ )} +
+ ); +} + +function RecordList({ items, onDel, render, empty }) { + if (items.length === 0) + return
{empty}
; + return ( +
+ {items.map((it) => ( +
+
{render(it)}
+ +
+ ))} +
+ ); +} + +const rootStyle = { + "--ink": "#f3f0ff", "--muted": "#b9b4d6", "--accent": "#9cff8f", "--accent2": "#ff7eb6", + minHeight: "100vh", color: "var(--ink)", position: "relative", overflow: "hidden", + fontFamily: "'DM Sans', ui-sans-serif, system-ui, sans-serif", + background: "linear-gradient(135deg, #1a1040 0%, #2d1b69 45%, #0f2057 100%)", +}; +const bgBlobs = { background: "radial-gradient(40% 40% at 15% 20%, rgba(156,255,143,.22), transparent 70%), radial-gradient(45% 45% at 85% 15%, rgba(255,126,182,.20), transparent 70%), radial-gradient(50% 50% at 70% 85%, rgba(120,140,255,.22), transparent 70%)", filter: "blur(8px)" }; +const glassCard = { background: "rgba(255,255,255,.07)", backdropFilter: "blur(18px)", WebkitBackdropFilter: "blur(18px)", border: "1px solid rgba(255,255,255,.14)", borderRadius: 18, padding: 18, boxShadow: "0 8px 32px rgba(0,0,0,.25), inset 0 1px 0 rgba(255,255,255,.12)" }; +const headerStyle = { padding: "28px 24px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12, borderBottom: "1px solid rgba(255,255,255,.10)" }; +const h1Style = { margin: 0, fontFamily: "'Syne', sans-serif", fontSize: 27, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 }; +const pill = { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--muted)", border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", backdropFilter: "blur(10px)", padding: "6px 12px", borderRadius: 20 }; +const lblStyle = { display: "block", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6, fontWeight: 600 }; +const inputStyle = { width: "100%", background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.16)", borderRadius: 10, padding: "10px 12px", color: "var(--ink)", fontSize: 14, fontFamily: "inherit", resize: "vertical", outline: "none", boxSizing: "border-box" }; +const twoCol = { display: "grid", gridTemplateColumns: "minmax(300px,400px) 1fr", gap: 18 }; +const cardTitle = { margin: "0 0 14px", fontFamily: "'Syne',sans-serif", fontSize: 18 }; +const metaP = { margin: "6px 0 0", fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }; +const metaB = { color: "var(--ink)" }; +const tabStyle = (a) => ({ display: "flex", alignItems: "center", gap: 7, padding: "10px 16px", background: a ? "var(--accent)" : "rgba(255,255,255,.06)", color: a ? "#13123a" : "var(--ink)", backdropFilter: "blur(10px)", border: `1px solid ${a ? "var(--accent)" : "rgba(255,255,255,.14)"}`, borderRadius: 11, fontWeight: 600, fontSize: 13.5, transition: "all .15s" }); +const countBadge = (a) => ({ background: a ? "rgba(0,0,0,.16)" : "rgba(255,255,255,.10)", borderRadius: 6, padding: "1px 7px", fontSize: 11.5 }); +const genBtn = (b) => ({ width: "100%", padding: "14px", borderRadius: 12, border: "none", background: b ? "rgba(255,255,255,.15)" : "var(--accent)", color: b ? "var(--muted)" : "#13123a", fontWeight: 700, fontSize: 15, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }); +const copyBtn = { display: "flex", alignItems: "center", gap: 6, padding: "7px 12px", background: "rgba(255,255,255,.08)", border: "1px solid rgba(255,255,255,.16)", borderRadius: 9, color: "var(--ink)", fontSize: 13 }; +const addBtn = { width: "100%", marginTop: 6, padding: "12px", borderRadius: 11, border: "none", background: "var(--accent)", color: "#13123a", fontWeight: 700, fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }; +const delBtn = { flexShrink: 0, width: 34, height: 34, borderRadius: 9, border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", color: "var(--accent2)", display: "flex", alignItems: "center", justifyContent: "center" }; +const selItem = (a) => ({ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, textAlign: "left", padding: "10px 12px", borderRadius: 10, background: a ? "rgba(156,255,143,.12)" : "rgba(255,255,255,.05)", border: `1px solid ${a ? "var(--accent)" : "rgba(255,255,255,.14)"}`, color: "var(--ink)", fontSize: 13.5, fontWeight: 500 }); +const GLOBAL_CSS = `@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap'); +*::-webkit-scrollbar{width:8px;height:8px}*::-webkit-scrollbar-thumb{background:rgba(255,255,255,.18);border-radius:8px} +button{cursor:pointer;font-family:inherit}@keyframes spin{to{transform:rotate(360deg)}} +::placeholder{color:rgba(185,180,214,.55)}body{margin:0}`; diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..d7d667d --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,13 @@ +# ── Etapa 1: build del frontend ── +FROM node:20-slim AS build +WORKDIR /app +COPY package.json ./ +RUN npm install +COPY . . +RUN npm run build + +# ── Etapa 2: servir con nginx ── +FROM nginx:1.27-alpine +COPY --from=build /app/dist /usr/share/nginx/html +COPY nginx.conf /etc/nginx/conf.d/default.conf +EXPOSE 80 diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..9add42b --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,12 @@ + + + + + + Adaptador Reels × Expedientes · Collina Systems + + +
+ + + diff --git a/frontend/main.jsx b/frontend/main.jsx new file mode 100644 index 0000000..ce286a9 --- /dev/null +++ b/frontend/main.jsx @@ -0,0 +1,5 @@ +import React from "react"; +import { createRoot } from "react-dom/client"; +import App from "./App.jsx"; + +createRoot(document.getElementById("root")).render(); diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..d0113fc --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,22 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # API -> contenedor backend (nombre de servicio en la red de compose) + location /api/ { + proxy_pass http://backend:3001; + proxy_http_version 1.1; + 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; + proxy_read_timeout 300s; # generación con Opus puede tardar + } + + # SPA fallback + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..9703df7 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,20 @@ +{ + "name": "collina-reels-frontend", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "lucide-react": "^0.383.0", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.3.4", + "vite": "^5.4.11" + } +} diff --git a/frontend/vite.config.js b/frontend/vite.config.js new file mode 100644 index 0000000..425c778 --- /dev/null +++ b/frontend/vite.config.js @@ -0,0 +1,7 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +export default defineConfig({ + plugins: [react()], + build: { outDir: "dist" }, +});