From cebf6e5e6ae8fed2213857a979feaae7e5eda42a Mon Sep 17 00:00:00 2001 From: marsalva Date: Wed, 4 Mar 2026 15:11:24 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 67 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 27 deletions(-) diff --git a/server.js b/server.js index 2a04389..073dba0 100644 --- a/server.js +++ b/server.js @@ -381,53 +381,66 @@ async function requirePlan(req, res, next, feature) { // 🔐 RUTAS DE AUTENTICACIÓN (LOGIN) - RESTAURADAS // ========================================== +// ========================================== +// 🔗 PORTAL PÚBLICO DEL CLIENTE +// ========================================== app.get("/public/portal/:token", async (req, res) => { try { const { token } = req.params; - const serviceId = req.query.service; - - // 1. Buscamos al cliente por su token - const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1 LIMIT 1", [token]); + const serviceId = req.query.service; // ¡NUEVO! Leemos el ID directamente de la URL + + const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1", [token]); if (qClient.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace no válido" }); const client = qClient.rows[0]; const ownerId = client.owner_id; - // 2. Buscamos los datos de la empresa - const qConfig = await pool.query("SELECT full_name, company_logo FROM users WHERE id = $1", [ownerId]); + const qConfig = await pool.query("SELECT full_name, company_logo, portal_settings FROM users WHERE id = $1", [ownerId]); + const userData = qConfig.rows[0] || {}; + const company = { - name: qConfig.rows[0]?.full_name || "IntegraRepara", - logo: qConfig.rows[0]?.company_logo || null + name: userData.full_name || "IntegraRepara", + logo: userData.company_logo || null }; - // 3. CONSULTA SEGURA (Con o sin ID) let qServices; - if (serviceId && !isNaN(parseInt(serviceId))) { + + // SI LA URL LLEVA EL ID, VAMOS A TIRO HECHO (A PRUEBA DE FALLOS) + if (serviceId) { qServices = await pool.query(` - SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, - st.name as real_status_name, st.is_final as is_status_final, - u.full_name as worker_name, u.phone as worker_phone + SELECT + s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, + st.name as real_status_name, + st.is_final as is_status_final, + u.full_name as worker_name, + u.phone as worker_phone FROM scraped_services s LEFT JOIN users u ON u.id = s.assigned_to LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text - WHERE s.id = $1 AND s.owner_id = $2 AND s.provider != 'SYSTEM_BLOCK' - `, [parseInt(serviceId), ownerId]); + WHERE s.id = $1 AND s.owner_id = $2 + `, [serviceId, ownerId]); } else { - let phoneMatch = String(client.phone || "").replace(/[^0-9]/g, ""); - if (phoneMatch.length > 9) phoneMatch = phoneMatch.slice(-9); - if (phoneMatch.length < 6) phoneMatch = "TELEFONO_FALSO_123"; - + // PLAN B: Búsqueda por teléfono (Si abren un enlace antiguo sin ID) qServices = await pool.query(` - SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, - st.name as real_status_name, st.is_final as is_status_final, - u.full_name as worker_name, u.phone as worker_phone + SELECT + s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, + st.name as real_status_name, + st.is_final as is_status_final, + u.full_name as worker_name, + u.phone as worker_phone FROM scraped_services s LEFT JOIN users u ON u.id = s.assigned_to LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text - WHERE s.owner_id = $1 AND s.provider != 'SYSTEM_BLOCK' - AND s.raw_data::text ILIKE $2 + WHERE s.owner_id = $1 + AND s.provider != 'SYSTEM_BLOCK' ORDER BY s.created_at DESC - `, [ownerId, `%${phoneMatch}%`]); + `, [ownerId]); + + const cleanPhoneToMatch = String(client.phone || "").replace(/\D/g, "").slice(-9); + qServices.rows = qServices.rows.filter(s => { + const rawString = JSON.stringify(s.raw_data || "").replace(/\D/g, ""); + return rawString.includes(cleanPhoneToMatch); + }); } const formattedServices = qServices.rows.map(s => { @@ -435,7 +448,7 @@ app.get("/public/portal/:token", async (req, res) => { id: s.id, title: s.is_urgent ? `🚨 URGENTE: #${s.service_ref}` : `Expediente #${s.service_ref}`, description: s.raw_data?.["Descripción"] || s.raw_data?.["DESCRIPCION"] || "Aviso de reparación", - status_name: s.real_status_name || "En gestión", + status_name: s.real_status_name || "En gestión", is_final: s.is_status_final || false, scheduled_date: s.raw_data?.scheduled_date || "", scheduled_time: s.raw_data?.scheduled_time || "", @@ -449,7 +462,7 @@ app.get("/public/portal/:token", async (req, res) => { } catch (e) { console.error("🔥 ERROR EN PORTAL:", e.message); - res.status(500).json({ ok: false, error: e.message }); + res.status(500).json({ ok: false, error: "Error interno" }); } });