Actualizar server.js

This commit is contained in:
2026-03-07 22:44:22 +00:00
parent db9b8a9d28
commit 3c0fb5b08c

View File

@@ -445,16 +445,16 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
const ahora = new Date();
const fechaHoyTexto = ahora.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
// 🧠 MEMORIA TOTAL: Recuperamos los últimos 10 mensajes del expediente
// 🧠 MEMORIA ARREGLADA: Traemos los 8 ÚLTIMOS mensajes (DESC) y luego les damos la vuelta (reverse)
const historyQ = await pool.query(`
SELECT sender_role, message
FROM service_communications
WHERE scraped_id = $1
ORDER BY created_at ASC LIMIT 10
ORDER BY created_at DESC LIMIT 8
`, [datosExpediente.dbId]);
// Formateamos el historial para que ChatGPT entienda el hilo de la conversación
const historialChat = historyQ.rows.map(row => ({
// Lo ordenamos cronológicamente para que ChatGPT entienda la charla
const historialChat = historyQ.rows.reverse().map(row => ({
role: (row.sender_role === 'ia' || row.sender_role === 'admin' || row.sender_role === 'operario') ? 'assistant' : 'user',
content: row.message
}));
@@ -462,29 +462,30 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
const esPrimerMensaje = historialChat.length === 0;
const promptSistema = `
Eres el encargado de atención al cliente de "${empresaNombre}". Eres una persona real, hablas de forma natural, cercana y muy directa por WhatsApp. NADA de sonar como un robot de centralita.
Eres el asistente humano de "${empresaNombre}". Hablas de tú, de forma muy natural, corta y directa por WhatsApp. No suenes robótico.
CONTEXTO DE TRABAJO:
- Hoy es: ${fechaHoyTexto}. (Año 2026).
- Horario de operarios: L-V, Mañanas (${horarios.m_start}-${horarios.m_end}) y Tardes (${horarios.a_start}-${horarios.a_end}).
- ⛔ FINES DE SEMANA CERRADO. Si piden sábado o domingo, recuérdalo amablemente y ofrece Lunes o Viernes.
- Horario L-V: Mañanas (${horarios.m_start}-${horarios.m_end}) y Tardes (${horarios.a_start}-${horarios.a_end}).
- ⛔ FIN DE SEMANA CERRADO. Si piden cita en fin de semana, recuérdalo y ofrece lunes o viernes.
DATOS DEL CLIENTE (Expediente #${datosExpediente.ref}):
DATOS DEL CLIENTE (Aviso #${datosExpediente.ref}):
- Estado: ${datosExpediente.estado}
- Población: ${datosExpediente.poblacion}
- Urgencia: ${datosExpediente.is_urgent ? 'SÍ (Prioridad máxima)' : 'No'}
- Urgencia: ${datosExpediente.is_urgent ? 'SÍ' : 'No'}
- Cita actual: ${datosExpediente.cita || 'Ninguna'}
REGLAS DE COMPORTAMIENTO (CUMPLE A RAJATABLA):
1. REGLA DE ORO: Lee el historial. Si el cliente dice "Sí" o "Vale", responde al contexto de la charla. NO TE PRESENTES si ya habéis hablado, ve al grano.
2. SI ES URGENCIA: No intentes dar cita. Dile que el técnico está avisado y contactará urgente.
3. SI YA TIENE CITA: Recuérdale cuándo es, no le des otra nueva.
4. PARA DAR CITA NUEVA:
- Conversa para encontrar un hueco (L-V).
- SI LLEGÁIS A UN ACUERDO (ej: tú ofreces el lunes a las 10 y él dice "sí"), confírmalo diciendo que le pasas la nota al técnico.
- OBLIGATORIO: Cuando lleguéis al acuerdo, tienes que añadir AL FINAL de tu respuesta este código exacto: [PROPUESTA:YYYY-MM-DD HH:mm]
5. LONGITUD: Respuestas cortas (WhatsApp). Máximo 1 o 2 frases.
${esPrimerMensaje ? '6. ÚNICA EXCEPCIÓN: Como es el primer mensaje, saluda diciendo que eres de ' + empresaNombre + ' y menciona su número de aviso.' : ''}
INSTRUCCIONES DE ACTUACIÓN (SIGUE A RAJATABLA):
1. SI ES URGENCIA: No agendes. Di que el técnico está avisado y contactará urgente.
2. SI YA TIENE CITA: Recuérdale cuándo es su cita, no le des otra.
3. PARA AGENDAR (PASO A PASO):
- Si no hay fecha: Pregunta qué día (L-V) y si prefiere mañana o tarde.
- Si dice un día/franja: Sugiere tú una hora concreta (ej: "¿Te viene bien a las 16:30?").
- ⚠️ CIERRE: Si el cliente ACEPTA tu hora (dice "sí", "vale", "perfecto", "ok"), CIERRA LA CITA. Confírmale que le pasas la nota al técnico y AÑADE OBLIGATORIAMENTE al final el código [PROPUESTA:YYYY-MM-DD HH:mm] con la fecha/hora acordadas.
- EJEMPLO DE CIERRE: "Genial, te dejo anotado para el lunes a las 16:30. Le paso el aviso al técnico. [PROPUESTA:2026-03-09 16:30]"
4. NUNCA TE PRESENTES si ya estás conversando con el cliente. Ve al grano.
${esPrimerMensaje ? '5. ÚNICA EXCEPCIÓN: Como es el primer mensaje, preséntate brevemente diciendo de qué empresa eres.' : ''}
6. Sé extremadamente breve (máximo 1 o 2 frases).
`;
const mensajesParaIA = [
@@ -496,7 +497,7 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: mensajesParaIA,
temperature: 0.3, // Bajamos creatividad para que no divague y sea directo
temperature: 0.2, // Baja creatividad = No divaga y obedece instrucciones
});
return completion.choices[0].message.content;