Actualizar server.js

This commit is contained in:
2026-03-04 08:53:26 +00:00
parent 47976642da
commit df474c00d2

View File

@@ -384,6 +384,7 @@ async function requirePlan(req, res, next, feature) {
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; // Recogemos el ID del enlace
// 1. Buscamos al cliente por su token // 1. Buscamos al cliente por su token
const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1 LIMIT 1", [token]); const qClient = await pool.query("SELECT * FROM clients WHERE portal_token = $1 LIMIT 1", [token]);
@@ -399,28 +400,40 @@ app.get("/public/portal/:token", async (req, res) => {
logo: qConfig.rows[0]?.company_logo || null logo: qConfig.rows[0]?.company_logo || null
}; };
// 3. TELÉFONO SEGURO: Extraemos SOLO los últimos 9 números, ignorando prefijos o símbolos let qServices;
let phoneMatch = String(client.phone || "").replace(/\D/g, "");
if (phoneMatch.length > 9) phoneMatch = phoneMatch.slice(-9);
if (phoneMatch.length < 8) phoneMatch = "NO_VALIDO_123";
// 4. BÚSQUEDA FUERZA BRUTA: Limpiamos los espacios de la BD antes de buscar // 3. LA SOLUCIÓN DEFINITIVA: Si el enlace trae ID, buscamos ESE expediente exacto y nada más
qServices = await pool.query(` if (serviceId && !isNaN(parseInt(serviceId))) {
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, qServices = await pool.query(`
st.name as real_status_name, st.is_final as is_status_final, SELECT 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,
FROM scraped_services s u.full_name as worker_name, u.phone as worker_phone
LEFT JOIN users u ON u.id = s.assigned_to FROM scraped_services s
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text LEFT JOIN users u ON u.id = s.assigned_to
WHERE s.owner_id = $1 AND s.provider != 'SYSTEM_BLOCK' LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
AND ( WHERE s.id = $1 AND s.owner_id = $2 AND s.provider != 'SYSTEM_BLOCK'
COALESCE(REPLACE(s.raw_data->>'Teléfono', ' ', ''), '') LIKE $2 `, [parseInt(serviceId), ownerId]);
OR COALESCE(REPLACE(s.raw_data->>'TELEFONO', ' ', ''), '') LIKE $2 }
OR COALESCE(REPLACE(s.raw_data->>'TELEFONOS', ' ', ''), '') LIKE $2 // 4. Si alguien abre el portal sin ID, buscamos por teléfono usando un filtro general seguro
) else {
ORDER BY s.created_at DESC let phoneMatch = String(client.phone || "").replace(/[^0-9]/g, "");
`, [ownerId, `%${phoneMatch}%`]); if (phoneMatch.length > 9) phoneMatch = phoneMatch.slice(-9);
if (phoneMatch.length < 6) phoneMatch = "TELEFONO_FALSO_123";
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
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
ORDER BY s.created_at DESC
`, [ownerId, `%${phoneMatch}%`]);
}
// 5. Formatear datos para el panel del cliente
const formattedServices = qServices.rows.map(s => { const formattedServices = qServices.rows.map(s => {
return { return {
id: s.id, id: s.id,
@@ -439,8 +452,8 @@ app.get("/public/portal/:token", async (req, res) => {
res.json({ ok: true, client: { name: client.full_name }, company, services: formattedServices }); res.json({ ok: true, client: { name: client.full_name }, company, services: formattedServices });
} catch (e) { } catch (e) {
console.error("🔥 ERROR EN PORTAL:", e.message); console.error("🔥 ERROR CRÍTICO EN PORTAL:", e.message);
res.status(500).json({ ok: false, error: "Error interno" }); res.status(500).json({ ok: false, error: e.message || "Error del servidor" });
} }
}); });