Actualizar server.js

This commit is contained in:
2026-03-07 22:39:30 +00:00
parent 011d51d258
commit db9b8a9d28

View File

@@ -444,7 +444,6 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
const ahora = new Date(); const ahora = new Date();
const fechaHoyTexto = ahora.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); const fechaHoyTexto = ahora.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
const esViernesOSabado = ahora.getDay() === 5 || ahora.getDay() === 6;
// 🧠 MEMORIA TOTAL: Recuperamos los últimos 10 mensajes del expediente // 🧠 MEMORIA TOTAL: Recuperamos los últimos 10 mensajes del expediente
const historyQ = await pool.query(` const historyQ = await pool.query(`
@@ -454,40 +453,40 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
ORDER BY created_at ASC LIMIT 10 ORDER BY created_at ASC LIMIT 10
`, [datosExpediente.dbId]); `, [datosExpediente.dbId]);
// Formateamos el historial para que ChatGPT lo entienda // Formateamos el historial para que ChatGPT entienda el hilo de la conversación
const historialChat = historyQ.rows.map(row => ({ const historialChat = historyQ.rows.map(row => ({
role: (row.sender_role === 'ia' || row.sender_role === 'admin' || row.sender_role === 'operario') ? 'assistant' : 'user', role: (row.sender_role === 'ia' || row.sender_role === 'admin' || row.sender_role === 'operario') ? 'assistant' : 'user',
content: row.message content: row.message
})); }));
// Evaluamos cuántos mensajes hay para saber si es el primer saludo
const esPrimerMensaje = historialChat.length === 0; const esPrimerMensaje = historialChat.length === 0;
const promptSistema = ` const promptSistema = `
Eres el Asistente de "${empresaNombre}". Habla de tú, de forma natural, sin parecer un robot. 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.
DATOS DEL EXPEDIENTE #${datosExpediente.ref}: CONTEXTO DE TRABAJO:
- Estado actual: ${datosExpediente.estado} - Hoy es: ${fechaHoyTexto}. (Año 2026).
- Operario asignado: ${datosExpediente.operario || 'Pendiente de asignar'} - Horario de operarios: L-V, Mañanas (${horarios.m_start}-${horarios.m_end}) y Tardes (${horarios.a_start}-${horarios.a_end}).
- Cita registrada: ${datosExpediente.cita || 'Ninguna'} - ⛔ FINES DE SEMANA CERRADO. Si piden sábado o domingo, recuérdalo amablemente y ofrece Lunes o Viernes.
- Urgencia: ${datosExpediente.is_urgent ? 'SÍ (CRÍTICO)' : 'No'}
DATOS DEL CLIENTE (Expediente #${datosExpediente.ref}):
- Estado: ${datosExpediente.estado}
- Población: ${datosExpediente.poblacion} - Población: ${datosExpediente.poblacion}
- Urgencia: ${datosExpediente.is_urgent ? 'SÍ (Prioridad máxima)' : 'No'}
- Cita actual: ${datosExpediente.cita || 'Ninguna'}
REGLAS SEGÚN LA SITUACIÓN (CUMPLE A RAJATABLA): REGLAS DE COMPORTAMIENTO (CUMPLE A RAJATABLA):
1. SI ES URGENCIA: NO pidas cita. Diles que al ser un aviso de urgencia, el técnico (${datosExpediente.operario || 'de guardia'}) se pondrá en contacto y acudirá lo antes posible. 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 YA ESTÁ CITADO: No intentes dar cita nueva a menos que pidan cambiarla. Recuérdales que su cita es el ${datosExpediente.cita || 'día acordado'} y que irá ${datosExpediente.operario || 'el técnico'}. 2. SI ES URGENCIA: No intentes dar cita. Dile que el técnico está avisado y contactará urgente.
3. SI YA ESTÁ FINALIZADO/ANULADO: Informa de que el expediente ya está cerrado. 3. SI YA TIENE CITA: Recuérdale cuándo es, no le des otra nueva.
4. PARA DAR CITA NUEVA:
REGLA PARA AGENDAR (SOLO SI NO ES URGENCIA Y NO ESTÁ CITADO): - Conversa para encontrar un hueco (L-V).
- Horario: L-V de ${horarios.m_start} a ${horarios.m_end} y ${horarios.a_start} a ${horarios.a_end}. Fines de semana NO trabajamos. Hoy es ${fechaHoyTexto}. - 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.
- Si el cliente confirma día/hora, anótalo y pon al final de tu frase: [PROPUESTA:YYYY-MM-DD HH:mm] - 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.
REGLAS DE CONVERSACIÓN: ${esPrimerMensaje ? '6. ÚNICA EXCEPCIÓN: Como es el primer mensaje, saluda diciendo que eres de ' + empresaNombre + ' y menciona su número de aviso.' : ''}
${esPrimerMensaje ? `- Es tu primer mensaje. Preséntate: "¡Hola! Soy el asistente de ${empresaNombre}..."` : `- Ya estás hablando con él. NO te presentes ni digas hola. Continúa la charla.`}
- Responde en máximo 2 frases. Corto y directo.
`; `;
// Construimos el array final de mensajes: Prompt + Historial + Mensaje actual
const mensajesParaIA = [ const mensajesParaIA = [
{ role: "system", content: promptSistema }, { role: "system", content: promptSistema },
...historialChat, ...historialChat,
@@ -497,7 +496,7 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
const completion = await openai.chat.completions.create({ const completion = await openai.chat.completions.create({
model: "gpt-4o-mini", model: "gpt-4o-mini",
messages: mensajesParaIA, messages: mensajesParaIA,
temperature: 0.3, // Muy bajo para que sea estricto con las reglas de urgencia y estados temperature: 0.3, // Bajamos creatividad para que no divague y sea directo
}); });
return completion.choices[0].message.content; return completion.choices[0].message.content;