Actualizar server.js

This commit is contained in:
2026-03-07 21:57:53 +00:00
parent 9883a848b7
commit 120fff1820

View File

@@ -440,51 +440,66 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
if (!settings.wa_ai_enabled) return null; if (!settings.wa_ai_enabled) return null;
// 🕒 OBTENER FECHA ACTUAL REAL
const ahora = new Date(); const ahora = new Date();
const opciones = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const opciones = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const fechaHoyTexto = ahora.toLocaleDateString('es-ES', opciones); const fechaHoyTexto = ahora.toLocaleDateString('es-ES', opciones);
// 🧠 MEMORIA: Comprobar si ha habido mensajes en los últimos 60 minutos // 🧠 MEMORIA: Saludo único
// Usamos datosExpediente.dbId que le pasaremos desde el webhook
const chatCheck = await pool.query(` const chatCheck = await pool.query(`
SELECT id FROM service_communications SELECT id FROM service_communications
WHERE scraped_id = $1 WHERE scraped_id = $1 AND created_at > NOW() - INTERVAL '60 minutes' LIMIT 1
AND created_at > NOW() - INTERVAL '60 minutes'
LIMIT 1
`, [datosExpediente.dbId]); `, [datosExpediente.dbId]);
const yaSeHaPresentado = chatCheck.rowCount > 0; const yaSeHaPresentado = chatCheck.rowCount > 0;
// 📍 LOGÍSTICA: Buscar servicios agendados en la misma población para proponer huecos
const poblacion = datosExpediente.poblacion || "";
let sugerenciasRuta = "";
if (poblacion) {
const serviciosCercanos = await pool.query(`
SELECT raw_data->>'scheduled_date' as fecha, count(*)
FROM scraped_services
WHERE owner_id = $1
AND raw_data->>'Población' ILIKE $2
AND raw_data->>'scheduled_date' >= CURRENT_DATE::text
GROUP BY fecha ORDER BY fecha ASC LIMIT 2
`, [ownerId, poblacion]);
if (serviciosCercanos.rowCount > 0) {
sugerenciasRuta = serviciosCercanos.rows.map(r => r.fecha).join(", ");
}
}
const promptSistema = ` const promptSistema = `
Eres el Asistente IA de "${empresaNombre}". Eres el Asistente IA de "${empresaNombre}".
CONTEXTO TEMPORAL: Hoy es ${fechaHoyTexto}. Año 2026.
CONTEXTO TEMPORAL: DATOS EXPEDIENTE #${datosExpediente.ref}:
- Hoy es: ${fechaHoyTexto}.
- Estamos en el año 2026. Úsalo para calcular fechas.
DATOS DEL EXPEDIENTE #${datosExpediente.ref}:
- Estado: ${datosExpediente.estado} - Estado: ${datosExpediente.estado}
- Cita actual registrada: ${datosExpediente.cita || 'Ninguna'} - Población: ${poblacion}
- Dirección: ${datosExpediente.direccion}
- Cita actual: ${datosExpediente.cita || 'Ninguna'}
LOGÍSTICA Y RUTAS:
${sugerenciasRuta
? `- Tenemos técnicos previstos en ${poblacion} los días: ${sugerenciasRuta}. Intenta sugerir estas fechas al cliente para optimizar la ruta.`
: `- No hay rutas cerradas en ${poblacion} aún. Sugiere los próximos días hábiles.`
}
PRESENTACIÓN: PRESENTACIÓN:
${!yaSeHaPresentado ${!yaSeHaPresentado
? `- Al ser el primer mensaje, preséntate: "Hola, soy el asistente virtual de ${empresaNombre}. Estoy aquí para ayudarte con tu expediente #${datosExpediente.ref}."` ? `- Preséntate: "Hola, soy el asistente virtual de ${empresaNombre}. Estoy aquí para ayudarte con tu expediente #${datosExpediente.ref}."`
: `- YA TE HAS PRESENTADO. No digas hola, ni quién eres, ni el número de expediente. Ve directo a responder al cliente de forma natural.` : `- No te presentes más.`
} }
REGLA DE CITAS (CRÍTICA): REGLA DE CITAS:
- Tú NO confirmas citas finales, solo recoges la preferencia del cliente. - Si el cliente no propone nada, dile: "Para agilizar su reparación, tenemos técnicos por su zona (${poblacion}) los días [FECHAS SUGERIDAS]. ¿Le vendría bien alguno de esos días o prefiere proponer usted otro?".
- Si el cliente propone un día/hora, responde: "He recibido su preferencia para el [FECHA]. Voy a consultarlo con el técnico asignado y le confirmaremos por aquí en cuanto valide su agenda." - Si propone fecha/hora, di que lo consultas con el técnico y añade: [PROPUESTA:YYYY-MM-DD HH:mm].
- Al final de esa respuesta, añade el código: [PROPUESTA:YYYY-MM-DD HH:mm]
- Si el cliente no propone nada concreto, pídele que te indique qué franja horaria le viene mejor.
REGLAS DE ORO: REGLAS DE ORO:
1. Si el cliente pregunta "¿Cuándo venís?", usa la "Cita actual registrada". Si no hay, di que la oficina contactará con él. - Responde en máximo 2 frases. Sé muy natural.
2. NUNCA inventes precios. - Si no sabes la dirección o población, pídela con amabilidad.
3. Ante enfados, deriva a un humano con amabilidad. - NUNCA confirmes al 100%. Siempre di "le confirmaremos en breve".
4. Responde en máximo 2 frases. Sé muy natural.
5. No uses negritas (**), usa asteriscos (*) si es vital resaltar algo.
`; `;
const completion = await openai.chat.completions.create({ const completion = await openai.chat.completions.create({