Actualizar server.js

This commit is contained in:
2026-03-04 21:53:05 +00:00
parent 5b887db2ce
commit 5bf47aba8d

View File

@@ -1446,6 +1446,7 @@ app.put("/services/set-appointment/:id", authMiddleware, async (req, res) => {
// ==========================================
// 📞 RUTA PARA CLIENTE NO LOCALIZADO
// ==========================================
// ==========================================
// 📞 RUTA PARA CLIENTE NO LOCALIZADO
// ==========================================
@@ -1472,7 +1473,8 @@ app.post("/services/not-found/:id", authMiddleware, async (req, res) => {
if (cleanPhoneToMatch.length >= 9) { // Solo intentamos enviar si hay un número válido
const tplQ = await pool.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type='not_found'", [req.user.accountId]);
// 🚨 Búsqueda flexible por si la plantilla se guardó con otro nombre interno
const tplQ = await pool.query("SELECT content FROM message_templates WHERE owner_id=$1 AND type IN ('not_found', 'unreachable', 'no_reply') LIMIT 1", [req.user.accountId]);
let text = tplQ.rowCount > 0 && tplQ.rows[0].content
? tplQ.rows[0].content
: `Hola {{NOMBRE}}, soy el técnico de {{COMPANIA}}. He intentado contactar contigo para agendar tu reparación (Exp. {{REFERENCIA}}), pero no ha sido posible. Por favor, pulsa aquí para elegir tu cita: {{ENLACE}}`;
@@ -1494,7 +1496,21 @@ app.post("/services/not-found/:id", authMiddleware, async (req, res) => {
const linkMagico = `https://portal.integrarepara.es/?token=${token}&service=${id}`;
let fechaLimpia = raw["scheduled_date"] || "la fecha acordada";
if (fechaLimpia.includes("-")) {
const partes = fechaLimpia.split("-");
if (partes.length === 3) {
const fechaObj = new Date(partes[0], partes[1] - 1, partes[2], 12, 0, 0);
const diaSemana = fechaObj.toLocaleDateString('es-ES', { weekday: 'long' });
fechaLimpia = `(${diaSemana}) ${partes[2]}/${partes[1]}/${partes[0]}`;
}
}
// REEMPLAZO DE TODAS LAS VARIABLES (Como en la foto)
text = text.replace(/{{NOMBRE}}/g, raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente");
text = text.replace(/{{DIRECCION}}/g, raw["Dirección"] || raw["DOMICILIO"] || "su domicilio");
text = text.replace(/{{FECHA}}/g, fechaLimpia);
text = text.replace(/{{HORA}}/g, raw["scheduled_time"] || "la hora acordada");
text = text.replace(/{{COMPANIA}}/g, raw["Compañía"] || raw["COMPAÑIA"] || "su Aseguradora");
text = text.replace(/{{REFERENCIA}}/g, current.rows[0].service_ref || id);
text = text.replace(/{{ENLACE}}/g, linkMagico);
@@ -1503,16 +1519,16 @@ app.post("/services/not-found/:id", authMiddleware, async (req, res) => {
const settings = userQ.rows[0]?.wa_settings || {};
const useDelay = settings.wa_delay_enabled !== false;
// MODO PRUEBAS: Redirigir el mensaje a tu móvil si está activado
// MODO PRUEBAS: Redirigir el mensaje a tu móvil
const MODO_PRUEBAS = true;
const MI_TELEFONO = "34667248132";
if (MODO_PRUEBAS) {
console.log(`🛡️ [MODO PRUEBAS NO LOCALIZADO] Desvío a tu móvil (${MI_TELEFONO})`);
const textoPrueba = `*(SIMULACIÓN NO LOCALIZADO PARA: ${finalPhoneToSend})*\n\n` + text;
sendWhatsAppAuto(MI_TELEFONO, textoPrueba, `cliente_${req.user.accountId}`, useDelay).catch(console.error);
await sendWhatsAppAuto(MI_TELEFONO, textoPrueba, `cliente_${req.user.accountId}`, useDelay);
} else {
sendWhatsAppAuto(finalPhoneToSend, text, `cliente_${req.user.accountId}`, useDelay).catch(console.error);
await sendWhatsAppAuto(finalPhoneToSend, text, `cliente_${req.user.accountId}`, useDelay);
}
}