Actualizar server.js

This commit is contained in:
2026-02-26 08:02:58 +00:00
parent 240db1f550
commit 34be61c4cb

View File

@@ -502,34 +502,35 @@ async function ensureInstance(instanceName) {
// ========================================== // ==========================================
// 🔗 PORTAL PÚBLICO DEL CLIENTE (BLINDADO SQL) // 🔗 PORTAL PÚBLICO DEL CLIENTE (BLINDADO SQL)
// ========================================== // ==========================================
// ==========================================
// 🔗 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;
// 1. Buscamos al cliente por su token exacto
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", [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. Traer configuración de la empresa (Logo/Colores)
const qConfig = await pool.query("SELECT portal_settings FROM users WHERE id = $1", [ownerId]); const qConfig = await pool.query("SELECT portal_settings FROM users WHERE id = $1", [ownerId]);
const company = qConfig.rows[0]?.portal_settings || { name: "IntegraRepara" }; const company = qConfig.rows[0]?.portal_settings || { name: "IntegraRepara" };
// 3. Traer todos los servicios de este dueño // AQUÍ ESTÁ LA MAGIA: Hacemos un LEFT JOIN para traernos el nombre y teléfono del técnico
const qServices = await pool.query(` const qServices = await pool.query(`
SELECT id, service_ref, is_urgent, raw_data, created_at SELECT
FROM scraped_services s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at,
WHERE owner_id = $1 u.full_name as worker_name,
AND provider != 'SYSTEM_BLOCK' u.phone as worker_phone
ORDER BY created_at DESC FROM scraped_services s
LEFT JOIN users u ON u.id = s.assigned_to
WHERE s.owner_id = $1
AND s.provider != 'SYSTEM_BLOCK'
ORDER BY s.created_at DESC
`, [ownerId]); `, [ownerId]);
// 4. Filtrado inteligente en Memoria (Evitamos el Error 500 de SQL)
const cleanPhoneToMatch = String(client.phone || "").replace(/\D/g, "").slice(-9); const cleanPhoneToMatch = String(client.phone || "").replace(/\D/g, "").slice(-9);
const formattedServices = qServices.rows const formattedServices = qServices.rows
@@ -538,26 +539,21 @@ app.get("/public/portal/:token", async (req, res) => {
return rawString.includes(cleanPhoneToMatch); return rawString.includes(cleanPhoneToMatch);
}) })
.map(s => { .map(s => {
// Buscamos el nombre del estado si existe
return { return {
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.raw_data?.status_operativo_nombre || "En gestión", status_name: s.raw_data?.status_operativo_nombre || "En gestión",
is_final: false, // Por ahora simplificado para asegurar carga is_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 || "",
assigned_worker: s.raw_data?.assigned_to_name || "Técnico asignado", assigned_worker: s.worker_name || null, // Nombre real del técnico
worker_phone: s.worker_phone || null, // Teléfono real del técnico
raw_data: s.raw_data raw_data: s.raw_data
}; };
}); });
res.json({ res.json({ ok: true, client: { name: client.full_name }, company, services: formattedServices });
ok: true,
client: { name: client.full_name },
company,
services: formattedServices
});
} catch (e) { } catch (e) {
console.error("🔥 ERROR EN PORTAL:", e.message); console.error("🔥 ERROR EN PORTAL:", e.message);