diff --git a/server.js b/server.js index 0ebdd5a..371be70 100644 --- a/server.js +++ b/server.js @@ -7,9 +7,15 @@ import pg from "pg"; const { Pool } = pg; const app = express(); +// ========================= +// MIDDLEWARES +// ========================= app.use(cors()); app.use(express.json()); +// ========================= +// VARIABLES DE ENTORNO +// ========================= const { DATABASE_URL, JWT_SECRET, @@ -23,19 +29,22 @@ if (!DATABASE_URL || !JWT_SECRET) { process.exit(1); } -// --- CONEXIÓN DB --- +// ========================= +// CONEXIÓN DB +// ========================= const pool = new Pool({ connectionString: DATABASE_URL, ssl: false // Correcto para Coolify interno }); // ========================================== -// 🛠️ INICIALIZACIÓN DE LA BASE DE DATOS +// 🛠️ RUTA DE INSTALACIÓN (Ejecutar una vez) // ========================================== -async function initDB() { - const client = await pool.connect(); +// Esta ruta crea las tablas si no existen. +// Úsala entrando a: https://tu-api.com/setup-db +app.get("/setup-db", async (req, res) => { try { - console.log("🛠️ Comprobando tablas de base de datos..."); + const client = await pool.connect(); await client.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, @@ -71,25 +80,24 @@ async function initDB() { created_at TIMESTAMP DEFAULT NOW() ); `); - console.log("✅ Tablas verificadas/creadas correctamente."); - } catch (e) { - console.error("❌ Error creando tablas:", e); - } finally { client.release(); + res.send("✅ ¡Base de datos configurada correctamente! Tablas creadas."); + } catch (e) { + console.error(e); + res.status(500).send("❌ Error creando tablas: " + e.message); } -} - -// Ejecutamos la creación de tablas al arrancar -initDB(); - -// ========================================== -// RESTO DEL SERVIDOR -// ========================================== +}); +// ========================= +// RUTA DE "ESTOY VIVO" +// ========================= app.get("/", (req, res) => { res.status(200).send("🚀 IntegraRepara API v1.0 - Online"); }); +// ========================= +// HELPERS +// ========================= function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; @@ -124,6 +132,9 @@ function authMiddleware(req, res, next) { } } +// ========================= +// WHATSAPP +// ========================= async function sendWhatsAppCode(phone, code) { if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) { console.log("⚠️ Evolution no configurado. Código simulado:", code); @@ -156,14 +167,16 @@ async function sendWhatsAppCode(phone, code) { } } -// --- RUTAS --- +// ========================= +// RUTAS +// ========================= +// 1. REGISTRO app.post("/auth/register", async (req, res) => { const client = await pool.connect(); try { const { fullName, phone, address, dni, email, password } = req.body; const p = normalizePhone(phone); - if (!fullName || !p || !email || !password) { return res.status(400).json({ ok: false, error: "Faltan datos obligatorios" }); } @@ -208,7 +221,6 @@ app.post("/auth/register", async (req, res) => { await client.query('COMMIT'); res.json({ ok: true, phone: p, msg: "Código enviado" }); - } catch (e) { await client.query('ROLLBACK'); console.error("Error en Registro:", e); @@ -218,6 +230,7 @@ app.post("/auth/register", async (req, res) => { } }); +// 2. VERIFICACIÓN app.post("/auth/verify", async (req, res) => { try { const { phone, code } = req.body; @@ -244,13 +257,13 @@ app.post("/auth/verify", async (req, res) => { const token = signToken({ id: row.uid, email: row.email, phone: p }); res.json({ ok: true, token }); - } catch (e) { console.error("Error Verify:", e); res.status(500).json({ ok: false, error: "Error verificando código" }); } }); +// 3. LOGIN app.post("/auth/login", async (req, res) => { try { const { email, password } = req.body; @@ -271,6 +284,7 @@ app.post("/auth/login", async (req, res) => { } }); +// 4. SERVICIOS (PROTEGIDO) app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM services WHERE user_id=$1 ORDER BY created_at DESC", [req.user.sub]); @@ -280,5 +294,6 @@ app.get("/services", authMiddleware, async (req, res) => { } }); +// ARRANCAR const port = process.env.PORT || 3000; app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); \ No newline at end of file