Actualizar server.js
This commit is contained in:
65
server.js
65
server.js
@@ -506,59 +506,62 @@ app.get("/public/portal/:token", async (req, res) => {
|
||||
try {
|
||||
const { token } = req.params;
|
||||
|
||||
// 1. Validar Token
|
||||
// 1. Buscamos al cliente por su token exacto
|
||||
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 inválido" });
|
||||
|
||||
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;
|
||||
|
||||
// 2. Obtener Configuración Empresa
|
||||
// 2. Traer configuración de la empresa (Logo/Colores)
|
||||
const qConfig = await pool.query("SELECT portal_settings FROM users WHERE id = $1", [ownerId]);
|
||||
let company = { name: "IntegraRepara", logo: "" };
|
||||
if (qConfig.rowCount > 0 && qConfig.rows[0].portal_settings) {
|
||||
company = qConfig.rows[0].portal_settings;
|
||||
}
|
||||
const company = qConfig.rows[0]?.portal_settings || { name: "IntegraRepara" };
|
||||
|
||||
// 3. LA CONSULTA MÁS SIMPLE POSIBLE (Para evitar el Error 500)
|
||||
// Buscamos servicios que pertenezcan al dueño y que coincidan con el teléfono del cliente
|
||||
// He quitado los JOINs complejos y los filtros raros de JSON para que no explote
|
||||
// 3. Traer todos los servicios de este dueño
|
||||
const qServices = await pool.query(`
|
||||
SELECT id, service_ref, is_urgent, raw_data, created_at
|
||||
FROM scraped_services
|
||||
WHERE owner_id = $1
|
||||
AND provider != 'SYSTEM_BLOCK'
|
||||
AND raw_data::text LIKE '%' || $2 || '%'
|
||||
ORDER BY created_at DESC
|
||||
`, [ownerId, client.phone.replace('+34', '').trim()]);
|
||||
`, [ownerId]);
|
||||
|
||||
// 4. PROCESAMOS LOS ESTADOS EN JAVASCRIPT (No en SQL, para que no falle)
|
||||
// Necesitamos los nombres de los estados
|
||||
const qStats = await pool.query("SELECT id, name, is_final FROM service_statuses WHERE owner_id = $1", [ownerId]);
|
||||
const statsMap = {};
|
||||
qStats.rows.forEach(s => { statsMap[String(s.id)] = s; });
|
||||
|
||||
const formattedServices = qServices.rows.map(s => {
|
||||
const statusId = String(s.raw_data?.status_operativo || "");
|
||||
const statusObj = statsMap[statusId];
|
||||
// 4. Filtrado inteligente en Memoria (Evitamos el Error 500 de SQL)
|
||||
const cleanPhoneToMatch = String(client.phone || "").replace(/\D/g, "").slice(-9);
|
||||
|
||||
const formattedServices = qServices.rows
|
||||
.filter(s => {
|
||||
const rawString = JSON.stringify(s.raw_data || "").replace(/\D/g, "");
|
||||
return rawString.includes(cleanPhoneToMatch);
|
||||
})
|
||||
.map(s => {
|
||||
// Buscamos el nombre del estado si existe
|
||||
return {
|
||||
id: s.id,
|
||||
title: s.is_urgent ? `🚨 URGENTE: Expediente #${s.service_ref}` : `Expediente #${s.service_ref}`,
|
||||
description: s.raw_data?.["Descripción"] || s.raw_data?.["DESCRIPCION"] || "Revisión técnica.",
|
||||
status_name: statusObj ? statusObj.name : 'Pendiente',
|
||||
is_final: statusObj ? statusObj.is_final : false,
|
||||
scheduled_date: s.raw_data?.scheduled_date,
|
||||
scheduled_time: s.raw_data?.scheduled_time,
|
||||
assigned_worker: s.raw_data?.assigned_to_name || 'Pendiente',
|
||||
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.raw_data?.status_operativo_nombre || "En gestión",
|
||||
is_final: false, // Por ahora simplificado para asegurar carga
|
||||
scheduled_date: s.raw_data?.scheduled_date || "",
|
||||
scheduled_time: s.raw_data?.scheduled_time || "",
|
||||
assigned_worker: s.raw_data?.assigned_to_name || "Técnico asignado",
|
||||
raw_data: s.raw_data
|
||||
};
|
||||
});
|
||||
|
||||
res.json({ ok: true, client, company, services: formattedServices });
|
||||
res.json({
|
||||
ok: true,
|
||||
client: { name: client.full_name },
|
||||
company,
|
||||
services: formattedServices
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error("Error Crítico Portal:", e);
|
||||
res.status(500).json({ ok: false, error: "Error de conexión" });
|
||||
console.error("🔥 ERROR EN PORTAL:", e.message);
|
||||
res.status(500).json({ ok: false, error: "Error interno" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user