Actualizar server.js

This commit is contained in:
2026-03-07 22:01:17 +00:00
parent 120fff1820
commit bbe8419660

110
server.js
View File

@@ -440,66 +440,64 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
if (!settings.wa_ai_enabled) return null; if (!settings.wa_ai_enabled) return null;
// 🕒 1. Sincronización de Fecha Real
const ahora = new Date(); const ahora = new Date();
const opciones = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const fechaHoyTexto = ahora.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
const fechaHoyTexto = ahora.toLocaleDateString('es-ES', opciones);
// 🧠 MEMORIA: Saludo único // 🧠 2. Memoria de Conversación (Evitar saludos repetitivos)
const chatCheck = await pool.query(` const chatCheck = await pool.query(`
SELECT id FROM service_communications SELECT id FROM service_communications
WHERE scraped_id = $1 AND created_at > NOW() - INTERVAL '60 minutes' LIMIT 1 WHERE scraped_id = $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 // 📍 3. Inteligencia de Ruta (Buscar técnicos cerca)
const poblacion = datosExpediente.poblacion || ""; const poblacion = datosExpediente.poblacion || "";
let sugerenciasRuta = ""; let fechasSugeridas = "";
if (poblacion) { if (poblacion) {
const serviciosCercanos = await pool.query(` const rutasCercanas = await pool.query(`
SELECT raw_data->>'scheduled_date' as fecha, count(*) SELECT raw_data->>'scheduled_date' as fecha
FROM scraped_services FROM scraped_services
WHERE owner_id = $1 WHERE owner_id = $1
AND raw_data->>'Población' ILIKE $2 AND raw_data->>'Población' ILIKE $2
AND raw_data->>'scheduled_date' >= CURRENT_DATE::text AND raw_data->>'scheduled_date' >= CURRENT_DATE::text
AND id != $3
GROUP BY fecha ORDER BY fecha ASC LIMIT 2 GROUP BY fecha ORDER BY fecha ASC LIMIT 2
`, [ownerId, poblacion]); `, [ownerId, poblacion, datosExpediente.dbId]);
if (serviciosCercanos.rowCount > 0) { if (rutasCercanas.rowCount > 0) {
sugerenciasRuta = serviciosCercanos.rows.map(r => r.fecha).join(", "); fechasSugeridas = rutasCercanas.rows.map(r => {
const [y, m, d] = r.fecha.split('-');
return `${d}/${m}`;
}).join(" y el ");
} }
} }
const promptSistema = ` const promptSistema = `
Eres el Asistente IA de "${empresaNombre}". Eres el Asistente IA de "${empresaNombre}".
CONTEXTO TEMPORAL: Hoy es ${fechaHoyTexto}. Año 2026. Hoy es ${fechaHoyTexto}. Estamos en el año 2026.
DATOS EXPEDIENTE #${datosExpediente.ref}: DATOS EXPEDIENTE #${datosExpediente.ref}:
- Estado: ${datosExpediente.estado} - Estado: ${datosExpediente.estado}
- Población: ${poblacion} - Población: ${poblacion}
- Dirección: ${datosExpediente.direccion}
- Cita actual: ${datosExpediente.cita || 'Ninguna'} - Cita actual: ${datosExpediente.cita || 'Ninguna'}
LOGÍSTICA Y RUTAS: LÓGICA DE SALUDO:
${sugerenciasRuta ${!yaSeHaPresentado
? `- Tenemos técnicos previstos en ${poblacion} los días: ${sugerenciasRuta}. Intenta sugerir estas fechas al cliente para optimizar la ruta.` ? `- Inicio de chat: Preséntate brevemente y menciona el expediente #${datosExpediente.ref}.`
: `- No hay rutas cerradas en ${poblacion} aún. Sugiere los próximos días hábiles.` : `- Conversación fluida: NO te presentes, NO digas hola, ve directo a la respuesta.`
} }
PRESENTACIÓN: ESTRATEGIA DE RUTA (LOGÍSTICA):
${!yaSeHaPresentado ${fechasSugeridas
? `- Preséntate: "Hola, soy el asistente virtual de ${empresaNombre}. Estoy aquí para ayudarte con tu expediente #${datosExpediente.ref}."` ? `- Tenemos otros técnicos en ${poblacion} el ${fechasSugeridas}. SUGIERE estas fechas prioritariamente para optimizar la ruta.`
: `- No te presentes más.` : `- No hay rutas previas en ${poblacion}. Pide al cliente su preferencia de mañana o tarde.`
} }
REGLA DE CITAS: REGLA DE CITAS:
- 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 algo, di que lo consultas y añade al final: [PROPUESTA:YYYY-MM-DD HH:mm]
- Si propone fecha/hora, di que lo consultas con el técnico y añade: [PROPUESTA:YYYY-MM-DD HH:mm]. - Máximo 2 frases. Sé muy natural, no parezcas un robot.
REGLAS DE ORO:
- Responde en máximo 2 frases. Sé muy natural.
- Si no sabes la dirección o población, pídela con amabilidad.
- NUNCA confirmes al 100%. Siempre di "le confirmaremos en breve".
`; `;
const completion = await openai.chat.completions.create({ const completion = await openai.chat.completions.create({
@@ -508,7 +506,7 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
{ role: "system", content: promptSistema }, { role: "system", content: promptSistema },
{ role: "user", content: mensajeCliente } { role: "user", content: mensajeCliente }
], ],
temperature: 0.5, temperature: 0.4, // Más preciso, menos creativo
}); });
return completion.choices[0].message.content; return completion.choices[0].message.content;
@@ -517,60 +515,6 @@ async function procesarConIA(ownerId, mensajeCliente, datosExpediente) {
return null; return null;
} }
} }
// 🛡️ MIDDLEWARE DE PLANES
async function requirePlan(req, res, next, feature) {
try {
const q = await pool.query("SELECT plan_tier FROM users WHERE id=$1", [req.user.accountId]);
const userPlan = 'pro'; // Forzamos a 'pro' para tus pruebas actuales sin límites
const limits = PLAN_LIMITS[userPlan];
if (!limits || !limits[feature]) {
return res.status(403).json({ ok: false, error: `Función exclusiva del plan Profesional.` });
}
next();
} catch (e) {
console.error("Error comprobando plan:", e);
res.status(500).json({ ok: false, error: "Error interno verificando plan" });
}
}
// ==========================================
// 🔐 RUTAS DE AUTENTICACIÓN (LOGIN) - RESTAURADAS
// ==========================================
app.post("/auth/login", async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ ok: false, error: "Faltan credenciales" });
// Buscamos al usuario por email o por teléfono
const q = await pool.query("SELECT * FROM users WHERE email = $1 OR phone = $1", [email]);
if (q.rowCount === 0) return res.status(401).json({ ok: false, error: "Usuario no encontrado" });
const user = q.rows[0];
if (user.status !== 'active') return res.status(401).json({ ok: false, error: "Cuenta desactivada. Contacta con el administrador." });
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) return res.status(401).json({ ok: false, error: "Contraseña incorrecta" });
const token = signToken(user);
res.json({ ok: true, token, role: user.role, name: user.full_name });
} catch (e) {
console.error("Login error:", e);
res.status(500).json({ ok: false, error: "Error de servidor al iniciar sesión" });
}
});
app.get("/auth/me", authMiddleware, async (req, res) => {
try {
const q = await pool.query("SELECT id, full_name, email, phone, role, owner_id, status, company_slug, plan_tier FROM users WHERE id = $1", [req.user.sub]);
if (q.rowCount === 0) return res.status(404).json({ ok: false });
res.json({ ok: true, user: q.rows[0] });
} catch (e) {
res.status(500).json({ ok: false });
}
});
// ========================================== // ==========================================
// 🔗 PORTAL PÚBLICO DEL CLIENTE // 🔗 PORTAL PÚBLICO DEL CLIENTE
// ========================================== // ==========================================