Actualizar server.js

This commit is contained in:
2026-03-04 15:11:24 +00:00
parent d49d584296
commit cebf6e5e6a

View File

@@ -381,53 +381,66 @@ async function requirePlan(req, res, next, feature) {
// 🔐 RUTAS DE AUTENTICACIÓN (LOGIN) - RESTAURADAS // 🔐 RUTAS DE AUTENTICACIÓN (LOGIN) - RESTAURADAS
// ========================================== // ==========================================
// ==========================================
// 🔗 PORTAL PÚBLICO DEL CLIENTE
// ==========================================
app.get("/public/portal/:token", async (req, res) => { app.get("/public/portal/:token", async (req, res) => {
try { try {
const { token } = req.params; const { token } = req.params;
const serviceId = req.query.service; const serviceId = req.query.service; // ¡NUEVO! Leemos el ID directamente de la URL
// 1. Buscamos al cliente por su token const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1", [token]);
const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1 LIMIT 1", [token]);
if (qClient.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace no válido" }); if (qClient.rowCount === 0) return res.status(404).json({ ok: false, error: "Enlace no válido" });
const client = qClient.rows[0]; const client = qClient.rows[0];
const ownerId = client.owner_id; const ownerId = client.owner_id;
// 2. Buscamos los datos de la empresa const qConfig = await pool.query("SELECT full_name, company_logo, portal_settings FROM users WHERE id = $1", [ownerId]);
const qConfig = await pool.query("SELECT full_name, company_logo FROM users WHERE id = $1", [ownerId]); const userData = qConfig.rows[0] || {};
const company = { const company = {
name: qConfig.rows[0]?.full_name || "IntegraRepara", name: userData.full_name || "IntegraRepara",
logo: qConfig.rows[0]?.company_logo || null logo: userData.company_logo || null
}; };
// 3. CONSULTA SEGURA (Con o sin ID)
let qServices; 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(` qServices = await pool.query(`
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, SELECT
st.name as real_status_name, st.is_final as is_status_final, s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at,
u.full_name as worker_name, u.phone as worker_phone 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 FROM scraped_services s
LEFT JOIN users u ON u.id = s.assigned_to 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 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' WHERE s.id = $1 AND s.owner_id = $2
`, [parseInt(serviceId), ownerId]); `, [serviceId, ownerId]);
} else { } else {
let phoneMatch = String(client.phone || "").replace(/[^0-9]/g, ""); // PLAN B: Búsqueda por teléfono (Si abren un enlace antiguo sin ID)
if (phoneMatch.length > 9) phoneMatch = phoneMatch.slice(-9);
if (phoneMatch.length < 6) phoneMatch = "TELEFONO_FALSO_123";
qServices = await pool.query(` qServices = await pool.query(`
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, SELECT
st.name as real_status_name, st.is_final as is_status_final, s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at,
u.full_name as worker_name, u.phone as worker_phone 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 FROM scraped_services s
LEFT JOIN users u ON u.id = s.assigned_to 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 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' WHERE s.owner_id = $1
AND s.raw_data::text ILIKE $2 AND s.provider != 'SYSTEM_BLOCK'
ORDER BY s.created_at DESC 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 => { const formattedServices = qServices.rows.map(s => {
@@ -435,7 +448,7 @@ app.get("/public/portal/:token", async (req, res) => {
id: s.id, id: s.id,
title: s.is_urgent ? `🚨 URGENTE: #${s.service_ref}` : `Expediente #${s.service_ref}`, 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", 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, is_final: s.is_status_final || false,
scheduled_date: s.raw_data?.scheduled_date || "", scheduled_date: s.raw_data?.scheduled_date || "",
scheduled_time: s.raw_data?.scheduled_time || "", scheduled_time: s.raw_data?.scheduled_time || "",
@@ -449,7 +462,7 @@ app.get("/public/portal/:token", async (req, res) => {
} catch (e) { } catch (e) {
console.error("🔥 ERROR EN PORTAL:", e.message); 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" });
} }
}); });