From d1d6d037e908d145e259e2b761df4586b19a6d58 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 8 Feb 2026 00:25:49 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 190 +++++++++++++++++++++++++++++------------------------- 1 file changed, 103 insertions(+), 87 deletions(-) diff --git a/server.js b/server.js index c14c5b0..aeec1e6 100644 --- a/server.js +++ b/server.js @@ -29,14 +29,13 @@ const pool = new Pool({ }); // ========================================== -// 🧠 AUTO-ACTUALIZACIÓN DE BASE DE DATOS (AISLAMIENTO DE DATOS) +// 🧠 AUTO-ACTUALIZACIÓN DB // ========================================== async function autoUpdateDB() { const client = await pool.connect(); try { console.log("🔄 Revisando estructura de base de datos..."); - // 1. Crear tablas básicas await client.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, @@ -81,50 +80,27 @@ async function autoUpdateDB() { ); `); - // 2. AÑADIR COLUMNAS FALTANTES (PARCHES) - - // Parche A: Roles + // Parches de columnas await client.query(` DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='role') THEN ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'operario'; END IF; - END $$; - `); - - // Parche B: DUEÑO (owner_id) en Usuarios - await client.query(` - DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='users' AND column_name='owner_id') THEN ALTER TABLE users ADD COLUMN owner_id INT; END IF; - END $$; - `); - - // Parche C: DUEÑO en Gremios - await client.query(` - DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='owner_id') THEN ALTER TABLE guilds ADD COLUMN owner_id INT REFERENCES users(id) ON DELETE CASCADE; END IF; - END $$; - `); - - // Parche D: DUEÑO en Servicios - await client.query(` - DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='owner_id') THEN ALTER TABLE services ADD COLUMN owner_id INT REFERENCES users(id) ON DELETE CASCADE; END IF; END $$; `); - // 3. LIMPIEZA DE RESTRICCIONES VIEJAS - try { - await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`); - } catch (e) {} + try { await client.query(`ALTER TABLE guilds DROP CONSTRAINT IF EXISTS guilds_name_key`); } catch (e) {} - console.log("✅ DB Sincronizada: Aislamiento de datos activado."); + console.log("✅ DB Sincronizada."); } catch (e) { console.error("❌ Error DB:", e); } finally { @@ -144,17 +120,9 @@ function normalizePhone(phone) { function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); } function signToken(user) { - // LÓGICA DE AISLAMIENTO: const accountId = user.owner_id || user.id; - return jwt.sign( - { - sub: user.id, - email: user.email, - phone: user.phone, - role: user.role || 'operario', - accountId: accountId - }, + { sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId: accountId }, JWT_SECRET, { expiresIn: "30d" } ); @@ -164,19 +132,15 @@ function authMiddleware(req, res, next) { const h = req.headers.authorization || ""; const token = h.startsWith("Bearer ") ? h.slice(7) : ""; if (!token) return res.status(401).json({ ok: false, error: "No token" }); - try { - req.user = jwt.verify(token, JWT_SECRET); - next(); - } catch { - return res.status(401).json({ ok: false, error: "Token inválido" }); - } + try { req.user = jwt.verify(token, JWT_SECRET); next(); } + catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } } // ========================= // RUTAS // ========================= -// 1. REGISTRO (Crea un DUEÑO / JEFE) +// REGISTRO app.post("/auth/register", async (req, res) => { const client = await pool.connect(); try { @@ -185,10 +149,8 @@ app.post("/auth/register", async (req, res) => { if (!fullName || !p || !email || !password) return res.status(400).json({ ok: false, error: "Faltan datos" }); const passwordHash = await bcrypt.hash(password, 10); - await client.query('BEGIN'); - // Verificamos duplicados const checkUser = await client.query("SELECT * FROM users WHERE email = $1 OR phone = $2", [email, p]); let userId; @@ -198,11 +160,9 @@ app.post("/auth/register", async (req, res) => { await client.query('ROLLBACK'); return res.status(409).json({ ok: false, error: "Usuario ya registrado." }); } - // Actualizamos reintento await client.query("UPDATE users SET full_name=$1, address=$2, dni=$3, password_hash=$4 WHERE id=$5", [fullName, address, dni, passwordHash, existing.id]); userId = existing.id; } else { - // Insertamos nuevo. owner_id se deja NULL porque ÉL es el jefe. const insert = await client.query( "INSERT INTO users (full_name, phone, address, dni, email, password_hash, role, owner_id) VALUES ($1, $2, $3, $4, $5, $6, 'admin', NULL) RETURNING id", [fullName, p, address, dni, email, passwordHash] @@ -217,43 +177,32 @@ app.post("/auth/register", async (req, res) => { await client.query("DELETE FROM login_codes WHERE user_id = $1", [userId]); await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]); - // Enviar WhatsApp if (EVOLUTION_BASE_URL && EVOLUTION_API_KEY) { const url = `${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${EVOLUTION_INSTANCE}`; - await fetch(url, { - method: "POST", - headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, - body: JSON.stringify({ number: p.replace("+", ""), text: `🔐 Código IntegraRepara: *${code}*` }) - }).catch(console.error); - } else { - console.log("📨 Código simulado:", code); + await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, body: JSON.stringify({ number: p.replace("+", ""), text: `🔐 Código: *${code}*` }) }).catch(console.error); } await client.query('COMMIT'); res.json({ ok: true, phone: p }); } catch (e) { await client.query('ROLLBACK'); - console.error(e); res.status(500).json({ ok: false, error: "Error server" }); } finally { client.release(); } }); -// 2. VERIFICACIÓN & LOGIN +// VERIFICACIÓN & LOGIN app.post("/auth/verify", async (req, res) => { try { const { phone, code } = req.body; const p = normalizePhone(phone); const q = await pool.query(`SELECT lc.*, u.id as uid, u.email, u.role, u.owner_id FROM login_codes lc JOIN users u ON lc.user_id = u.id WHERE lc.phone=$1 AND lc.consumed_at IS NULL AND lc.expires_at > NOW() ORDER BY lc.created_at DESC LIMIT 1`, [p]); if (q.rowCount === 0) return res.status(400).json({ ok: false, error: "Código inválido" }); - const row = q.rows[0]; - if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false, error: "Código incorrecto" }); - + if (!(await bcrypt.compare(String(code), row.code_hash))) return res.status(400).json({ ok: false, error: "Incorrecto" }); await pool.query("UPDATE login_codes SET consumed_at=NOW() WHERE id=$1", [row.id]); await pool.query("UPDATE users SET is_verified=TRUE WHERE id=$1", [row.uid]); - res.json({ ok: true, token: signToken({ id: row.uid, email: row.email, phone: p, role: row.role, owner_id: row.owner_id }) }); } catch (e) { res.status(500).json({ ok: false, error: "Error verify" }); } }); @@ -265,16 +214,11 @@ app.post("/auth/login", async (req, res) => { if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Datos incorrectos" }); const u = q.rows[0]; if (!(await bcrypt.compare(password, u.password_hash))) return res.status(401).json({ ok: false, error: "Datos incorrectos" }); - res.json({ ok: true, token: signToken(u) }); } catch(e) { res.status(500).json({ ok: false, error: "Error login" }); } }); -// ========================================== -// 🔒 RUTAS PROTEGIDAS (DATOS AISLADOS) -// ========================================== - -// GET SERVICIOS (Solo los de MI empresa) +// SERVICES app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM services WHERE owner_id=$1 ORDER BY created_at DESC", [req.user.accountId]); @@ -282,7 +226,7 @@ app.get("/services", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); } }); -// GET GREMIOS +// GREMIOS app.get("/guilds", authMiddleware, async (req, res) => { try { const q = await pool.query("SELECT * FROM guilds WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); @@ -290,12 +234,10 @@ app.get("/guilds", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); -// POST GREMIOS app.post("/guilds", authMiddleware, async (req, res) => { try { const { name } = req.body; if (!name) return res.status(400).json({ ok: false, error: "Falta nombre" }); - const q = await pool.query("INSERT INTO guilds (name, owner_id) VALUES ($1, $2) RETURNING *", [name.toUpperCase(), req.user.accountId]); res.json({ ok: true, guild: q.rows[0] }); } catch (e) { res.status(500).json({ ok: false, error: "Gremio duplicado" }); } @@ -308,23 +250,49 @@ app.delete("/guilds/:id", authMiddleware, async (req, res) => { } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); -// CREAR USUARIO (Se vincula a MI empresa) +// ========================= +// GESTIÓN DE USUARIOS (CRUD COMPLETO) +// ========================= + +// 1. LISTAR USUARIOS (GET) +app.get("/admin/users", authMiddleware, async (req, res) => { + try { + // Obtenemos usuarios y sus gremios en una sola consulta + const q = await pool.query(` + SELECT u.id, u.full_name, u.email, u.phone, u.role, + COALESCE(json_agg(g.id) FILTER (WHERE g.id IS NOT NULL), '[]') as guilds + FROM users u + LEFT JOIN user_guilds ug ON u.id = ug.user_id + LEFT JOIN guilds g ON ug.guild_id = g.id + WHERE u.owner_id = $1 + GROUP BY u.id + ORDER BY u.id DESC + `, [req.user.accountId]); + + res.json({ ok: true, users: q.rows }); + } catch (e) { + console.error(e); + res.status(500).json({ ok: false, error: "Error al listar usuarios" }); + } +}); + +// 2. CREAR USUARIO (POST) - AHORA CON TELÉFONO REAL app.post("/admin/users", authMiddleware, async (req, res) => { const client = await pool.connect(); try { - const { fullName, email, password, role, guilds } = req.body; - if (!email || !password || !fullName) return res.status(400).json({ ok: false, error: "Faltan datos" }); + const { fullName, email, password, role, guilds, phone } = req.body; + + if (!email || !password || !fullName || !phone) return res.status(400).json({ ok: false, error: "Faltan datos (nombre, email, pass, teléfono)" }); + const p = normalizePhone(phone); const passwordHash = await bcrypt.hash(password, 10); - const dummyPhone = `manual_${Date.now()}_${Math.floor(Math.random()*1000)}`; await client.query('BEGIN'); - // AQUÍ ESTÁ LA MAGIA: owner_id = req.user.accountId const insert = await client.query( `INSERT INTO users (full_name, email, password_hash, role, phone, is_verified, owner_id) VALUES ($1, $2, $3, $4, $5, TRUE, $6) RETURNING id`, - [fullName, email, passwordHash, role || 'operario', dummyPhone, req.user.accountId] + [fullName, email, passwordHash, role || 'operario', p, req.user.accountId] ); const userId = insert.rows[0].id; @@ -338,15 +306,10 @@ app.post("/admin/users", authMiddleware, async (req, res) => { res.json({ ok: true, msg: "Usuario creado" }); } catch (e) { await client.query('ROLLBACK'); - - // --- NUEVO: GESTIÓN DE ERRORES MEJORADA --- - if (e.code === '23505') { // Código de clave duplicada - if (e.constraint && e.constraint.includes('email')) { - return res.status(400).json({ ok: false, error: "❌ El email ya está registrado." }); - } + if (e.code === '23505') { + if (e.constraint && e.constraint.includes('email')) return res.status(400).json({ ok: false, error: "❌ El email ya existe." }); + if (e.constraint && e.constraint.includes('phone')) return res.status(400).json({ ok: false, error: "❌ El teléfono ya existe." }); } - // ------------------------------------------- - console.error(e); res.status(500).json({ ok: false, error: "Error creando usuario" }); } finally { @@ -354,8 +317,61 @@ app.post("/admin/users", authMiddleware, async (req, res) => { } }); -// ARRANCAR +// 3. EDITAR USUARIO (PUT) +app.put("/admin/users/:id", authMiddleware, async (req, res) => { + const client = await pool.connect(); + try { + const userId = req.params.id; + const { fullName, email, phone, role, guilds, password } = req.body; + const p = normalizePhone(phone); + + await client.query('BEGIN'); + + // Verificar que el usuario pertenece a mi empresa + const check = await client.query("SELECT id FROM users WHERE id=$1 AND owner_id=$2", [userId, req.user.accountId]); + if(check.rowCount === 0) throw new Error("Usuario no encontrado o no tienes permiso"); + + // Actualizar datos básicos + if(password) { + const hash = await bcrypt.hash(password, 10); + await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4, password_hash=$5 WHERE id=$6", [fullName, email, p, role, hash, userId]); + } else { + await client.query("UPDATE users SET full_name=$1, email=$2, phone=$3, role=$4 WHERE id=$5", [fullName, email, p, role, userId]); + } + + // Actualizar Gremios (Borrar y Crear) + if (guilds && Array.isArray(guilds)) { + await client.query("DELETE FROM user_guilds WHERE user_id=$1", [userId]); + for (const guildId of guilds) { + await client.query("INSERT INTO user_guilds (user_id, guild_id) VALUES ($1, $2)", [userId, guildId]); + } + } + + await client.query('COMMIT'); + res.json({ ok: true, msg: "Usuario actualizado" }); + + } catch (e) { + await client.query('ROLLBACK'); + console.error(e); + res.status(500).json({ ok: false, error: "Error actualizando (Revisa email/teléfono duplicados)" }); + } finally { + client.release(); + } +}); + +// 4. BORRAR USUARIO (DELETE) +app.delete("/admin/users/:id", authMiddleware, async (req, res) => { + try { + const result = await pool.query("DELETE FROM users WHERE id=$1 AND owner_id=$2", [req.params.id, req.user.accountId]); + if (result.rowCount === 0) return res.status(404).json({ ok: false, error: "Usuario no encontrado" }); + res.json({ ok: true }); + } catch (e) { + console.error(e); + res.status(500).json({ ok: false, error: "Error borrando usuario" }); + } +}); + const port = process.env.PORT || 3000; autoUpdateDB().then(() => { - app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port} (Multitenant)`)); + app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); }); \ No newline at end of file