Actualizar server.js

This commit is contained in:
2026-03-04 18:55:42 +00:00
parent cebf6e5e6a
commit 9d4fc462cf

View File

@@ -387,60 +387,50 @@ async function requirePlan(req, res, next, feature) {
app.get("/public/portal/:token", async (req, res) => {
try {
const { token } = req.params;
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]);
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]);
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;
const qConfig = await pool.query("SELECT full_name, company_logo, portal_settings FROM users WHERE id = $1", [ownerId]);
const userData = qConfig.rows[0] || {};
// 2. Buscamos los datos de la empresa
const qConfig = await pool.query("SELECT full_name, company_logo FROM users WHERE id = $1", [ownerId]);
const company = {
name: userData.full_name || "IntegraRepara",
logo: userData.company_logo || null
name: qConfig.rows[0]?.full_name || "IntegraRepara",
logo: qConfig.rows[0]?.company_logo || null
};
// 3. CONSULTA SEGURA (Con o sin ID)
let qServices;
// SI LA URL LLEVA EL ID, VAMOS A TIRO HECHO (A PRUEBA DE FALLOS)
if (serviceId) {
if (serviceId && !isNaN(parseInt(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
`, [serviceId, ownerId]);
WHERE s.id = $1 AND s.owner_id = $2 AND s.provider != 'SYSTEM_BLOCK'
`, [parseInt(serviceId), ownerId]);
} else {
// PLAN B: Búsqueda por teléfono (Si abren un enlace antiguo sin ID)
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";
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'
WHERE s.owner_id = $1 AND s.provider != 'SYSTEM_BLOCK'
AND s.raw_data::text ILIKE $2
ORDER BY s.created_at DESC
`, [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);
});
`, [ownerId, `%${phoneMatch}%`]);
}
const formattedServices = qServices.rows.map(s => {
@@ -448,7 +438,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 || "",
@@ -462,7 +452,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: "Error interno" });
res.status(500).json({ ok: false, error: e.message });
}
});