Actualizar server.js

This commit is contained in:
2026-03-04 08:35:40 +00:00
parent c52bab56e5
commit b81cc6f696

View File

@@ -384,52 +384,59 @@ 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 serviceIdParam = req.query.service; // Extraemos el ID si lo mandan
// 1. Buscamos al cliente por su token mágico // 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;
const clientId = client.id;
// 2. Buscamos los datos de la empresa para personalizar el portal // 2. Buscamos los datos de la empresa para personalizar el portal
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: userData.full_name || "IntegraRepara", name: qConfig.rows[0]?.full_name || "IntegraRepara",
logo: userData.company_logo || null logo: qConfig.rows[0]?.company_logo || null
}; };
// 3. TELÉFONO SEGURO E ID SEGURO (Esto evita el Error 500 y el fallo de enlace) // 3. OBTENER SERVICIOS (Lógica blindada anti-crashes)
let cleanPhoneToMatch = String(client.phone || "").replace(/\D/g, "").slice(-9); let qServices;
if (cleanPhoneToMatch.length < 8) cleanPhoneToMatch = "NO_VALIDO_123"; // Seguridad
// Si hay ID en el enlace lo usamos, si no, mandamos un "0" para que no explote la DB // Si nos pasan un ID de servicio en la URL, sacamos ESE servicio exacto
const requestedServiceId = req.query.service ? String(req.query.service) : "0"; if (serviceIdParam && serviceIdParam !== "undefined" && serviceIdParam !== "null") {
qServices = await pool.query(`
SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, s.client_id,
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
`, [parseInt(serviceIdParam), ownerId]);
}
// Si no hay ID en la URL, sacamos todos los del cliente usando su teléfono
else {
let phoneMatch = String(client.phone || "").replace(/\D/g, "").slice(-9);
if (phoneMatch.length < 8) phoneMatch = "NO_VALIDO_123";
const qServices = await pool.query(` qServices = await pool.query(`
SELECT SELECT s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, s.client_id,
s.id, s.service_ref, s.is_urgent, s.raw_data, s.created_at, s.client_id, st.name as real_status_name, st.is_final as is_status_final,
st.name as real_status_name, u.full_name as worker_name, u.phone as worker_phone
st.is_final as is_status_final, FROM scraped_services s
u.full_name as worker_name, LEFT JOIN users u ON u.id = s.assigned_to
u.phone as worker_phone LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text
FROM scraped_services s WHERE s.owner_id = $1 AND s.provider != 'SYSTEM_BLOCK'
LEFT JOIN users u ON u.id = s.assigned_to AND (
LEFT JOIN service_statuses st ON st.id::text = (s.raw_data->>'status_operativo')::text s.client_id = $2
WHERE s.owner_id = $1 OR REPLACE(s.raw_data->>'Teléfono', ' ', '') LIKE $3
AND s.provider != 'SYSTEM_BLOCK' OR REPLACE(s.raw_data->>'TELEFONO', ' ', '') LIKE $3
AND ( OR REPLACE(s.raw_data->>'TELEFONOS', ' ', '') LIKE $3
s.id::text = $4 )
OR s.client_id = $2 ORDER BY s.created_at DESC
OR (s.client_id IS NULL AND REPLACE(s.raw_data->>'Teléfono', ' ', '') LIKE $3) `, [ownerId, client.id, `%${phoneMatch}%`]);
OR (s.client_id IS NULL AND REPLACE(s.raw_data->>'TELEFONO', ' ', '') LIKE $3) }
OR (s.client_id IS NULL AND REPLACE(s.raw_data->>'TELEFONOS', ' ', '') LIKE $3)
)
ORDER BY s.created_at DESC
`, [ownerId, clientId, `%${cleanPhoneToMatch}%`, requestedServiceId]);
const formattedServices = qServices.rows.map(s => { const formattedServices = qServices.rows.map(s => {
return { return {
@@ -449,7 +456,7 @@ 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); console.error("🔥 ERROR EN PORTAL:", e.message);
res.status(500).json({ ok: false, error: "Error interno" }); res.status(500).json({ ok: false, error: "Error interno" });
} }
}); });