Actualizar server.js

This commit is contained in:
2026-02-08 12:32:38 +00:00
parent 7727912234
commit 571088fe6c

222
server.js
View File

@@ -164,9 +164,6 @@ async function autoUpdateDB() {
END $$; 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)."); console.log("✅ DB Sincronizada (Estados y Logs listos).");
} catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); } } catch (e) { console.error("❌ Error DB:", e); } finally { client.release(); }
} }
@@ -178,6 +175,7 @@ function normalizePhone(phone) {
if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p; if (!p.startsWith("+") && /^[6789]\d{8}$/.test(p)) return "+34" + p;
return p; return p;
} }
function genCode6() { return String(Math.floor(100000 + Math.random() * 900000)); }
function signToken(user) { function signToken(user) {
const accountId = user.owner_id || user.id; 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" }); return jwt.sign({ sub: user.id, email: user.email, phone: user.phone, role: user.role || 'operario', accountId }, JWT_SECRET, { expiresIn: "30d" });
@@ -189,12 +187,46 @@ function authMiddleware(req, res, next) {
try { req.user = jwt.verify(token, JWT_SECRET); next(); } try { req.user = jwt.verify(token, JWT_SECRET); next(); }
catch { return res.status(401).json({ ok: false, error: "Token inválido" }); } catch { return res.status(401).json({ ok: false, error: "Token inválido" }); }
} }
async function sendWhatsAppCode(phone, code) {
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY) {
console.log("⚠️ Evolution no configurado. Código:", code);
return;
}
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: phone.replace("+", ""), text: `🔐 Código IntegraRepara: *${code}*` })
}).catch(console.error);
}
// ========================= // =========================
// RUTAS PRINCIPALES (AUTH, ETC.) // RUTAS AUTH (Standard)
// ========================= // =========================
app.post("/auth/login", async (req, res) => { /* ... (Copia tu login actual) ... */ }); app.post("/auth/register", async (req, res) => {
// (Mantén tus rutas de auth, usuarios y gremios iguales) 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" });
const passwordHash = await bcrypt.hash(password, 10);
await client.query('BEGIN');
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]);
const userId = insert.rows[0].id;
const code = genCode6(); const codeHash = await bcrypt.hash(code, 10); const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
await client.query("INSERT INTO login_codes (user_id, phone, code_hash, expires_at) VALUES ($1, $2, $3, $4)", [userId, p, codeHash, expiresAt]);
await sendWhatsAppCode(p, code);
await client.query('COMMIT'); res.json({ ok: true, phone: p });
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false, error: "Error server" }); } finally { client.release(); }
});
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: "Inválido" }); const row = q.rows[0]; 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 }); }
});
app.post("/auth/login", async (req, res) => {
try { const { email, password } = req.body; const q = await pool.query("SELECT * FROM users WHERE email=$1", [email]); if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Datos incorrectos" }); let user = null; for (const u of q.rows) { if (await bcrypt.compare(password, u.password_hash)) { user = u; break; } } if (!user) return res.status(401).json({ ok: false, error: "Datos incorrectos" }); res.json({ ok: true, token: signToken(user) }); } catch(e) { res.status(500).json({ ok: false }); }
});
// ========================= // =========================
// API ESTADOS (STATUSES) // API ESTADOS (STATUSES)
@@ -202,8 +234,7 @@ app.post("/auth/login", async (req, res) => { /* ... (Copia tu login actual) ...
app.get("/statuses", authMiddleware, async (req, res) => { app.get("/statuses", authMiddleware, async (req, res) => {
try { try {
let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]); let q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]);
// Si no existen estados, creamos los DEFAULT
// Si no tiene estados, creamos los por defecto
if (q.rowCount === 0) { if (q.rowCount === 0) {
const defaults = [ const defaults = [
{ name: 'Pendiente', color: 'gray', def: true, fin: false }, { name: 'Pendiente', color: 'gray', def: true, fin: false },
@@ -212,10 +243,8 @@ app.get("/statuses", authMiddleware, async (req, res) => {
{ name: 'Cancelado', color: 'red', def: false, fin: true } { name: 'Cancelado', color: 'red', def: false, fin: true }
]; ];
for (const s of defaults) { for (const s of defaults) {
await pool.query( await pool.query("INSERT INTO service_statuses (owner_id, name, color, is_default, is_final) VALUES ($1, $2, $3, $4, $5)",
"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]);
[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]); q = await pool.query("SELECT * FROM service_statuses WHERE owner_id=$1 ORDER BY id ASC", [req.user.accountId]);
} }
@@ -224,26 +253,41 @@ app.get("/statuses", authMiddleware, async (req, res) => {
}); });
// ========================= // =========================
// API SERVICIOS (ACTUALIZADA) // API CLIENTES & COMPAÑIAS
// =========================
app.get("/clients/search", authMiddleware, async (req, res) => {
try {
const { phone } = req.query; const p = normalizePhone(phone); if(!p) return res.json({ok:true,client:null});
const q = await pool.query("SELECT * FROM clients WHERE phone=$1 AND owner_id=$2 LIMIT 1", [p, req.user.accountId]);
res.json({ ok: true, client: q.rows[0] || null });
} catch (e) { res.status(500).json({ ok: false }); }
});
app.get("/companies", authMiddleware, async (req, res) => {
try { const q = await pool.query("SELECT * FROM companies WHERE owner_id=$1 ORDER BY name ASC", [req.user.accountId]); res.json({ ok: true, companies: q.rows }); } catch (e) { res.status(500).json({ ok: false }); }
});
app.post("/companies", authMiddleware, async (req, res) => {
try { const { name } = req.body; await pool.query("INSERT INTO companies (name, owner_id) VALUES ($1, $2)", [name, req.user.accountId]); res.json({ ok: true }); } catch (e) { res.status(500).json({ ok: false }); }
});
// =========================
// API SERVICIOS (CON LOGS)
// ========================= // =========================
// GET SERVICIOS (Con Estado actual) // LISTAR
app.get("/services", authMiddleware, async (req, res) => { app.get("/services", authMiddleware, async (req, res) => {
try { try {
const q = await pool.query(` const q = await pool.query(`
SELECT s.*, c.name as company_name, st.name as status_name, st.color as status_color SELECT s.*, st.name as status_name, st.color as status_color, c.name as company_name
FROM services s FROM services s
LEFT JOIN companies c ON s.company_id = c.id
LEFT JOIN service_statuses st ON s.status_id = st.id LEFT JOIN service_statuses st ON s.status_id = st.id
WHERE s.owner_id=$1 LEFT JOIN companies c ON s.company_id = c.id
ORDER BY s.created_at DESC`, WHERE s.owner_id=$1 ORDER BY s.created_at DESC`, [req.user.accountId]);
[req.user.accountId]
);
res.json({ ok: true, services: q.rows }); res.json({ ok: true, services: q.rows });
} catch (e) { res.status(500).json({ ok: false, error: "Error servicios" }); } } catch (e) { res.status(500).json({ ok: false }); }
}); });
// GET HISTORIAL DE UN SERVICIO // HISTORIAL / LOGS
app.get("/services/:id/logs", authMiddleware, async (req, res) => { app.get("/services/:id/logs", authMiddleware, async (req, res) => {
try { try {
const q = await pool.query(` const q = await pool.query(`
@@ -252,88 +296,92 @@ app.get("/services/:id/logs", authMiddleware, async (req, res) => {
LEFT JOIN users u ON l.user_id = u.id 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 s1 ON l.old_status_id = s1.id
LEFT JOIN service_statuses s2 ON l.new_status_id = s2.id LEFT JOIN service_statuses s2 ON l.new_status_id = s2.id
WHERE l.service_id = $1 WHERE l.service_id=$1 ORDER BY l.created_at DESC
ORDER BY l.created_at DESC
`, [req.params.id]); `, [req.params.id]);
res.json({ ok: true, logs: q.rows }); res.json({ ok: true, logs: q.rows });
} catch (e) { res.status(500).json({ ok: false }); } } catch (e) { res.status(500).json({ ok: false }); }
}); });
// CAMBIAR ESTADO SERVICIO // CAMBIAR ESTADO
app.put("/services/:id/status", authMiddleware, async (req, res) => { app.put("/services/:id/status", authMiddleware, async (req, res) => {
const client = await pool.connect(); const client = await pool.connect();
try { try {
const { status_id, comment } = req.body; const { status_id, comment } = req.body;
const serviceId = req.params.id; const serviceId = req.params.id;
await client.query('BEGIN'); await client.query('BEGIN');
// 1. Obtener estado actual
const current = await client.query("SELECT status_id FROM services WHERE id=$1", [serviceId]); const current = await client.query("SELECT status_id FROM services WHERE id=$1", [serviceId]);
const oldStatusId = current.rows[0].status_id; const oldStatus = current.rows[0].status_id;
// 2. Actualizar servicio
await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, serviceId]); await client.query("UPDATE services SET status_id=$1 WHERE id=$2", [status_id, serviceId]);
await client.query("INSERT INTO service_logs (service_id, user_id, old_status_id, new_status_id, comment) VALUES ($1, $2, $3, $4, $5)",
// 3. Insertar Log [serviceId, req.user.sub, oldStatus, status_id, comment || "Cambio manual"]);
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'); await client.query('COMMIT');
res.json({ ok: true }); res.json({ ok: true });
} catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); } } catch (e) { await client.query('ROLLBACK'); res.status(500).json({ ok: false }); } finally { client.release(); }
}); });
// CREAR SERVICIO
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,
status_id // <--- NUEVO: Recibimos el estado manual
} = req.body;
const p = normalizePhone(phone);
await client.query('BEGIN');
// 1. GESTIÓN DEL ESTADO
let finalStatusId = status_id;
// Si no nos envían estado, buscamos el "por defecto" (Pendiente)
if (!finalStatusId) {
const defStatus = await client.query("SELECT id FROM service_statuses WHERE owner_id=$1 AND is_default=TRUE LIMIT 1", [req.user.accountId]);
finalStatusId = defStatus.rows[0]?.id;
}
// 2. GESTIÓN CLIENTE
let clientId;
const clientCheck = await client.query("SELECT id, addresses FROM clients WHERE phone=$1 AND owner_id=$2", [p, req.user.accountId]);
if (clientCheck.rowCount > 0) {
clientId = clientCheck.rows[0].id;
let addrs = clientCheck.rows[0].addresses || [];
if(!addrs.includes(address)) addrs.push(address);
await client.query("UPDATE clients SET addresses=$1 WHERE id=$2", [JSON.stringify(addrs), clientId]);
} else {
const newC = await client.query("INSERT INTO clients (owner_id, full_name, phone, email, addresses) VALUES ($1, $2, $3, $4, $5) RETURNING id", [req.user.accountId, name, p, email, JSON.stringify([address])]);
clientId = newC.rows[0].id;
}
// 3. INSERTAR 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, clientId, finalStatusId, p, name, address, email,
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 + " - Svc"
]);
// 4. 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, finalStatusId]);
await client.query('COMMIT');
res.json({ ok: true });
} catch (e) { await client.query('ROLLBACK'); console.error(e); res.status(500).json({ ok: false, error: e.message }); } finally { client.release(); }
});
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
autoUpdateDB().then(() => { autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); });
app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`));
});