Adaptador Reels x Expedientes - versión inicial
Estado tal cual recibido antes de hardening: - backend Express + Postgres + Anthropic SDK - frontend Vite + React + nginx proxy - docker-compose para Coolify
This commit is contained in:
commit
506de5e271
17 files changed
+777
No files matched your search
@@ -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
|
||||
+17
@@ -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
|
||||
+102
@@ -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: <IP pública del VPS> 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.
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
.env
|
||||
@@ -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"]
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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); });
|
||||
@@ -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"
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
npm-debug.log
|
||||
.env
|
||||
@@ -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 (
|
||||
<label style={{ display: "block", marginBottom: 14 }}>
|
||||
<span style={lblStyle}>{label}</span>
|
||||
<Comp value={value} rows={textarea ? rows : undefined} placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)} style={inputStyle} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div style={{ marginBottom: 14 }}>
|
||||
<span style={lblStyle}>Soltar archivo (MD, TXT, DOCX, PDF)</span>
|
||||
<div
|
||||
onDragOver={(e) => { 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)",
|
||||
}}>
|
||||
<UploadCloud size={22} style={{ opacity: .8 }} />
|
||||
<div style={{ fontSize: 13, marginTop: 6, color: "var(--ink)" }}>Arrastra aquí o haz clic para subir</div>
|
||||
<div style={{ fontSize: 11.5, marginTop: 3 }}>{hint}</div>
|
||||
<input ref={inputRef} type="file" accept=".md,.txt,.docx,.pdf" style={{ display: "none" }}
|
||||
onChange={(e) => handle(e.target.files[0])} />
|
||||
</div>
|
||||
{status && (
|
||||
<div style={{ marginTop: 8, fontSize: 12.5, display: "flex", alignItems: "center", gap: 6,
|
||||
color: status.type === "err" ? "var(--accent2)" : status.type === "ok" ? "var(--accent)" : "var(--muted)" }}>
|
||||
{status.type === "err" ? <FileWarning size={14} /> : status.type === "load" ? <Loader2 size={14} style={{ animation: "spin 1s linear infinite" }} /> : <Check size={14} />}
|
||||
{status.msg}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div style={rootStyle}>
|
||||
<style>{GLOBAL_CSS}</style>
|
||||
<div style={{ position: "fixed", inset: 0, zIndex: 0, ...bgBlobs }} />
|
||||
<div style={{ position: "relative", zIndex: 1 }}>
|
||||
<header style={headerStyle}>
|
||||
<div>
|
||||
<h1 style={h1Style}>Adaptador <span style={{ color: "var(--accent)" }}>Reels × Expedientes</span></h1>
|
||||
<p style={{ margin: "6px 0 0", color: "var(--muted)", fontSize: 13 }}>
|
||||
Genera un brief de producción con el guion adaptado al estilo del creador.
|
||||
</p>
|
||||
</div>
|
||||
<div style={pill}><Database size={13} /> {loaded ? `${reels.length} reels · ${exps.length} exp.` : "cargando…"}</div>
|
||||
</header>
|
||||
|
||||
{loadErr && <div style={{ ...glassCard, margin: "16px 24px 0", borderColor: "var(--accent2)", color: "var(--accent2)", fontSize: 13 }}>{loadErr}</div>}
|
||||
|
||||
<nav style={{ display: "flex", gap: 8, padding: "16px 24px 0", flexWrap: "wrap" }}>
|
||||
{TABS.map((t) => {
|
||||
const active = tab === t.id; const Icon = t.icon;
|
||||
return (
|
||||
<button key={t.id} onClick={() => setTab(t.id)} style={tabStyle(active)}>
|
||||
<Icon size={15} /> {t.label}
|
||||
{typeof t.count === "number" && <span style={countBadge(active)}>{t.count}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<main style={{ maxWidth: 1080, margin: "0 auto", padding: "22px 24px 60px" }}>
|
||||
{tab === "generar" && (
|
||||
<div style={{ display: "grid", gap: 18 }}>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px,1fr))", gap: 14 }}>
|
||||
<Selector title="1 · Análisis técnico" icon={Film} items={reels} selId={selReel} onSel={setSelReel}
|
||||
empty="Aún no hay análisis. Ve a «Análisis técnicos»." />
|
||||
<Selector title="2 · Expediente comercial" icon={FileText} items={exps} selId={selExp} onSel={setSelExp}
|
||||
empty="Aún no hay expedientes. Ve a «Expedientes»." />
|
||||
</div>
|
||||
<div style={glassCard}>
|
||||
<button onClick={generar} disabled={busy} style={genBtn(busy)}>
|
||||
{busy ? <><Loader2 size={17} style={{ animation: "spin 1s linear infinite" }} /> Generando brief…</>
|
||||
: <><Sparkles size={17} /> Generar brief de producción</>}
|
||||
</button>
|
||||
{err && <p style={{ color: "var(--accent2)", fontSize: 13, marginTop: 12, marginBottom: 0 }}>{err}</p>}
|
||||
</div>
|
||||
{output && (
|
||||
<div style={glassCard}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
|
||||
<span style={{ fontWeight: 700, fontFamily: "'Syne',sans-serif", fontSize: 18 }}>Brief de producción</span>
|
||||
<button onClick={copy} style={copyBtn}>{copied ? <><Check size={14} /> Copiado</> : <><Copy size={14} /> Copiar</>}</button>
|
||||
</div>
|
||||
<pre style={{ whiteSpace: "pre-wrap", fontFamily: "inherit", fontSize: 14, lineHeight: 1.65, margin: 0 }}>{output}</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "reels" && (
|
||||
<div style={twoCol}>
|
||||
<div style={glassCard}>
|
||||
<h3 style={cardTitle}>Nuevo análisis técnico</h3>
|
||||
<DropBox hint="Se vuelca en «Notas adicionales»"
|
||||
onText={(text, fname) => setReelForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), notas: (f.notas ? f.notas + "\n\n" : "") + text }))} />
|
||||
<Field label="Etiqueta / nombre del creador" value={reelForm.titulo} onChange={(v) => setReelForm({ ...reelForm, titulo: v })} placeholder="Ej. Reel viral @creador" />
|
||||
<Field label="Hook / primeros 3 s" value={reelForm.hook} onChange={(v) => setReelForm({ ...reelForm, hook: v })} textarea rows={2} />
|
||||
<Field label="Estructura y ritmo" value={reelForm.estructura} onChange={(v) => setReelForm({ ...reelForm, estructura: v })} textarea rows={2} />
|
||||
<Field label="Tono y lenguaje" value={reelForm.tono} onChange={(v) => setReelForm({ ...reelForm, tono: v })} textarea rows={2} />
|
||||
<Field label="Duración / formato / CTA" value={reelForm.formato} onChange={(v) => setReelForm({ ...reelForm, formato: v })} textarea rows={2} />
|
||||
<Field label="Notas adicionales" value={reelForm.notas} onChange={(v) => setReelForm({ ...reelForm, notas: v })} textarea rows={3} />
|
||||
<button onClick={addReel} style={addBtn}><Plus size={16} /> Guardar análisis</button>
|
||||
</div>
|
||||
<RecordList items={reels} onDel={delReel} empty="No hay análisis técnicos guardados todavía."
|
||||
render={(r) => (<>
|
||||
<strong style={{ fontSize: 15 }}>{r.titulo}</strong>
|
||||
{r.hook && <p style={metaP}><b style={metaB}>Hook:</b> {r.hook}</p>}
|
||||
{r.tono && <p style={metaP}><b style={metaB}>Tono:</b> {r.tono}</p>}
|
||||
{r.formato && <p style={metaP}><b style={metaB}>Formato:</b> {r.formato}</p>}
|
||||
</>)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "exp" && (
|
||||
<div style={twoCol}>
|
||||
<div style={glassCard}>
|
||||
<h3 style={cardTitle}>Nuevo expediente comercial</h3>
|
||||
<DropBox hint="Se vuelca en «Contenido del expediente»"
|
||||
onText={(text, fname) => setExpForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), contenido: (f.contenido ? f.contenido + "\n\n" : "") + text }))} />
|
||||
<Field label="Nombre de la solución" value={expForm.titulo} onChange={(v) => setExpForm({ ...expForm, titulo: v })} placeholder="Ej. Solución CRM para pymes" />
|
||||
<Field label="Contenido del expediente" value={expForm.contenido} onChange={(v) => setExpForm({ ...expForm, contenido: v })} textarea rows={9} placeholder="Pega o sube propuesta de valor, beneficios, prueba, precio, CTA…" />
|
||||
<button onClick={addExp} style={addBtn}><Plus size={16} /> Guardar expediente</button>
|
||||
</div>
|
||||
<RecordList items={exps} onDel={delExp} empty="No hay expedientes guardados todavía."
|
||||
render={(e) => (<>
|
||||
<strong style={{ fontSize: 15 }}>{e.titulo}</strong>
|
||||
<p style={{ ...metaP, display: "-webkit-box", WebkitLineClamp: 4, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{e.contenido}</p>
|
||||
</>)} />
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Selector({ title, icon: Icon, items, selId, onSel, empty }) {
|
||||
return (
|
||||
<div style={glassCard}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 7, ...lblStyle, marginBottom: 12 }}><Icon size={14} /> {title}</div>
|
||||
{items.length === 0 ? <p style={{ color: "var(--muted)", fontSize: 13, margin: 0 }}>{empty}</p> : (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 7, maxHeight: 240, overflowY: "auto" }}>
|
||||
{items.map((it) => {
|
||||
const active = selId === it.id;
|
||||
return (
|
||||
<button key={it.id} onClick={() => onSel(it.id)} style={selItem(active)}>
|
||||
<span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.titulo}</span>
|
||||
{active ? <Check size={15} color="var(--accent)" /> : <ChevronRight size={15} color="var(--muted)" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RecordList({ items, onDel, render, empty }) {
|
||||
if (items.length === 0)
|
||||
return <div style={{ ...glassCard, border: "1px dashed rgba(255,255,255,.18)", padding: 40, textAlign: "center", color: "var(--muted)", fontSize: 14 }}>{empty}</div>;
|
||||
return (
|
||||
<div style={{ display: "grid", gap: 12, alignContent: "start" }}>
|
||||
{items.map((it) => (
|
||||
<div key={it.id} style={{ ...glassCard, padding: 15, display: "flex", justifyContent: "space-between", gap: 12 }}>
|
||||
<div style={{ minWidth: 0 }}>{render(it)}</div>
|
||||
<button onClick={() => onDel(it.id)} title="Borrar" style={delBtn}><Trash2 size={15} /></button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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}`;
|
||||
@@ -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
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Adaptador Reels × Expedientes · Collina Systems</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import App from "./App.jsx";
|
||||
|
||||
createRoot(document.getElementById("root")).render(<App />);
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: { outDir: "dist" },
|
||||
});
|
||||
Reference in new issue
Block a user