import express from "express"; import cors from "cors"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import pg from "pg"; const { Pool } = pg; const app = express(); app.use(cors()); app.use(express.json()); const { DATABASE_URL, JWT_SECRET, EVOLUTION_BASE_URL, EVOLUTION_API_KEY, EVOLUTION_INSTANCE, } = process.env; if (!DATABASE_URL || !JWT_SECRET) { console.error("❌ ERROR FATAL: Faltan variables de entorno"); process.exit(1); } const pool = new Pool({ connectionString: DATABASE_URL, ssl: false }); // ========================================== // 🧠 AUTO-ACTUALIZACIÓN DB (ESTADOS Y LOGS) // ========================================== async function autoUpdateDB() { const client = await pool.connect(); try { console.log("🔄 Revisando estructura de base de datos..."); // 1. Tablas Base await client.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, full_name TEXT NOT NULL, phone TEXT NOT NULL, email TEXT NOT NULL, dni TEXT, address TEXT, password_hash TEXT NOT NULL, is_verified BOOLEAN DEFAULT FALSE, owner_id INT, role TEXT DEFAULT 'operario', created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS login_codes ( id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id) ON DELETE CASCADE, phone TEXT NOT NULL, code_hash TEXT NOT NULL, purpose TEXT DEFAULT 'register_verify', consumed_at TIMESTAMP, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS guilds ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS user_guilds ( user_id INT REFERENCES users(id) ON DELETE CASCADE, guild_id INT REFERENCES guilds(id) ON DELETE CASCADE, PRIMARY KEY (user_id, guild_id) ); CREATE TABLE IF NOT EXISTS companies ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, cif TEXT, email TEXT, phone TEXT, address TEXT, created_at TIMESTAMP DEFAULT NOW() ); CREATE TABLE IF NOT EXISTS clients ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, full_name TEXT NOT NULL, phone TEXT NOT NULL, email TEXT, addresses JSONB DEFAULT '[]', notes TEXT, created_at TIMESTAMP DEFAULT NOW() ); `); // 2. NUEVO: TABLA DE ESTADOS DE SERVICIO await client.query(` CREATE TABLE IF NOT EXISTS service_statuses ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, -- Ej: Pendiente, En Proceso, Completado color TEXT DEFAULT 'gray', -- gray, blue, green, red, yellow is_default BOOLEAN DEFAULT FALSE, -- Estado inicial al crear servicio is_final BOOLEAN DEFAULT FALSE, -- Si es estado final (cierra el servicio) created_at TIMESTAMP DEFAULT NOW() ); `); // 3. TABLA SERVICIOS (Con FK a status) await client.query(` CREATE TABLE IF NOT EXISTS services ( id SERIAL PRIMARY KEY, owner_id INT REFERENCES users(id) ON DELETE CASCADE, client_id INT REFERENCES clients(id) ON DELETE SET NULL, status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL, -- NUEVO: ID del estado title TEXT, description TEXT, contact_phone TEXT NOT NULL, contact_name TEXT NOT NULL, address TEXT NOT NULL, email TEXT, scheduled_date DATE DEFAULT CURRENT_DATE, scheduled_time TIME DEFAULT CURRENT_TIME, duration_minutes INT DEFAULT 30, is_urgent BOOLEAN DEFAULT FALSE, is_company BOOLEAN DEFAULT FALSE, company_id INT REFERENCES companies(id) ON DELETE SET NULL, company_ref TEXT, internal_notes TEXT, client_notes TEXT, closed_at TIMESTAMP, created_at TIMESTAMP DEFAULT NOW() ); `); // 4. NUEVO: TABLA LOGS DE ESTADOS (TRAZABILIDAD) await client.query(` CREATE TABLE IF NOT EXISTS service_logs ( id SERIAL PRIMARY KEY, service_id INT REFERENCES services(id) ON DELETE CASCADE, user_id INT REFERENCES users(id) ON DELETE SET NULL, -- Quién hizo el cambio old_status_id INT REFERENCES service_statuses(id), new_status_id INT REFERENCES service_statuses(id), comment TEXT, -- Comentario del cambio (ej: "Cliente no estaba") created_at TIMESTAMP DEFAULT NOW() ); `); // 5. PARCHES Y DATOS POR DEFECTO try { await client.query(`ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key`); } catch (e) {} try { await client.query(`ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key`); } catch (e) {} await client.query(` DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='services' AND column_name='status_id') THEN ALTER TABLE services ADD COLUMN status_id INT REFERENCES service_statuses(id) ON DELETE SET NULL; END IF; END $$; `); // Crear estados por defecto para cada cuenta nueva (Esto se haría al registrarse, pero lo simulamos aquí) // Nota: Como es multitenant, cada usuario crea sus estados. Para simplificar, asumiremos que el frontend pide crear los defaults si no existen. console.log("✅ DB Sincronizada (Estados y Logs listos)."); } catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); } } // HELPERS function normalizePhone(phone) { let p = String(phone || "").trim().replace(/\s+/g, "").replace(/-/g, ""); if (!p) return ""; if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p; return p; } function signToken(user) { const accountId = user.owner_id || user.id; return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" }); } 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" }); } } // ========================= // RUTAS PRINCIPALES (AUTH, ETC.) // ========================= app.post("/auth/login", async (req, res) => { /* ... (Copia tu login actual) ... */ }); // (Mantén tus rutas de auth, usuarios y gremios iguales) // ========================= // API ESTADOS (STATUSES) // ========================= app.get("/statuses", authMiddleware, async (req, res) => { try { let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); // Si no tiene estados, creamos los por defecto if (q.rowCount === 0) { const defaults = [ { name: 'Pendiente', color: 'gray', def: true, fin: false }, { name: 'En Proceso', color: 'blue', def: false, fin: false }, { name: 'Completado', color: 'green', def: false, fin: true }, { name: 'Cancelado', color: 'red', def: false, fin: true } ]; for (const s of defaults) { await pool.query( "INSERT INTO service_statuses (owner_id, name, color, is_default, is_final) VALUES ($1, $2, $3, $4, $5)", [req.user.accountId, s.name, s.color, s.def, s.fin] ); } q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); } res.json({ ok: true, statuses: q.rows }); } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); // ========================= // API SERVICIOS (ACTUALIZADA) // ========================= // GET SERVICIOS (Con Estado actual) app.get("/services", authMiddleware, async (req, res) => { try { const q = await pool.query(` SELECT s.*, c.name as company_name, st.name as status_name, st.color as status_color FROM services s LEFT JOIN companies c ON s.company_id = c.id LEFT JOIN service_statuses st ON s.status_id = st.id WHERE s.owner_id=$1 ORDER BY s.created_at DESC`, [req.user.accountId] ); res.json({ ok: true, services: q.rows }); } catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); } }); // GET HISTORIAL DE UN SERVICIO app.get("/services/:id/logs", authMiddleware, async (req, res) => { try { const q = await pool.query(` SELECT l.*, u.full_name as user_name, s1.name as old_status, s2.name as new_status, s2.color as new_color FROM service_logs l LEFT JOIN users u ON l.user_id = u.id LEFT JOIN service_statuses s1 ON l.old_status_id = s1.id LEFT JOIN service_statuses s2 ON l.new_status_id = s2.id WHERE l.service_id = $1 ORDER BY l.created_at DESC `, [req.params.id]); res.json({ ok: true, logs: q.rows }); } catch (e) { res.status(500).json({ ok: false }); } }); // CAMBIAR ESTADO SERVICIO app.put("/services/:id/status", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { status_id, comment } = req.body; const serviceId = req.params.id; await client.query('BEGIN'); // 1. Obtener estado actual const current = await client.query("SELECT status_id FROM services WHERE id=$1", [serviceId]); const oldStatusId = current.rows[0].status_id; // 2. Actualizar servicio await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, serviceId]); // 3. Insertar Log await client.query(` INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5) `, [serviceId, req.user.sub, oldStatusId, status_id, comment || "Cambio de estado manual"]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); // CREAR SERVICIO (Asigna estado por defecto) app.post("/services", authMiddleware, async (req, res) => { const client = await pool.connect(); try { const { phone, name, address, email, description, scheduled_date, scheduled_time, duration, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes } = req.body; const p = normalizePhone(phone); await client.query('BEGIN'); // Buscar estado por defecto const defStatus = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]); const statusId = defStatus.rows[0]?.id; // ... (Lógica de Cliente igual que antes) ... // Simplificado para brevedad, aquí iría la búsqueda/creación de cliente que ya tienes. // Asumimos clientId ya obtenido. let clientId; // [TU CÓDIGO DE CLIENTE AQUÍ] - Si quieres que lo repita dímelo, pero es igual al anterior. // Crear Servicio const insert = await client.query(` INSERT INTO services ( owner_id, client_id, status_id, contact_phone, contact_name, address, email, description, scheduled_date, scheduled_time, duration_minutes, is_urgent, is_company, company_id, company_ref, internal_notes, client_notes, title ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) RETURNING id `, [ req.user.accountId, 1, statusId, p, name, address, email, // Pongo client_id=1 hardcodeado para ejemplo, usa tu lógica real description, scheduled_date || 'NOW()', scheduled_time || 'NOW()', duration || 30, is_urgent || false, is_company || false, company_id || null, company_ref, internal_notes, client_notes, name + " - Servicio" ]); // Log inicial await client.query(` INSERT INTO service_logs (service_id, user_id, new_status_id, comment) VALUES ($1, $2, $3, 'Servicio creado') `, [insert.rows[0].id, req.user.sub, statusId]); await client.query('COMMIT'); res.json({ ok: true }); } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } }); const port = process.env.PORT || 3000; autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });