Actualizar server.js
This commit is contained in:
67
server.js
67
server.js
@@ -1541,7 +1541,7 @@ app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
|
||||
});
|
||||
|
||||
// ==========================================
|
||||
// 📝 ACTUALIZACIÓN MANUAL (RUTA PRINCIPAL CORREGIDA CON LOGS)
|
||||
// 📝 ACTUALIZACIÓN MANUAL (CONEXIÓN ROBOT HOMESERVE)
|
||||
// ==========================================
|
||||
app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
|
||||
const { id } = req.params;
|
||||
@@ -1557,40 +1557,37 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
|
||||
if (current.rows.length === 0) return res.status(404).json({ error: 'No encontrado' });
|
||||
|
||||
let rawActual = current.rows[0].raw_data || {};
|
||||
let oldStatus = rawActual.status_operativo || null;
|
||||
let newStatus = extra.status_operativo || oldStatus;
|
||||
if (newStatus === "") newStatus = null;
|
||||
|
||||
// 1. Capturar valores antiguos y nuevos para comparar
|
||||
let oldStatus = String(rawActual.status_operativo || "");
|
||||
let newStatus = String(extra.status_operativo !== undefined ? extra.status_operativo : oldStatus);
|
||||
|
||||
const oldDate = String(rawActual.scheduled_date || "");
|
||||
const newDate = String(extra.scheduled_date !== undefined ? extra.scheduled_date : oldDate);
|
||||
|
||||
const statusChanged = (newStatus !== oldStatus && newStatus !== "" && newStatus !== "null");
|
||||
const dateChanged = (newDate !== oldDate && newDate !== "" && newDate !== "null");
|
||||
|
||||
const oldWorkerId = current.rows[0].assigned_to || rawActual.assigned_to;
|
||||
let finalAssignedTo = assigned_to !== undefined ? (assigned_to === "" ? null : assigned_to) : oldWorkerId;
|
||||
|
||||
const oldDate = rawActual.scheduled_date || "";
|
||||
const newDate = extra.scheduled_date !== undefined ? extra.scheduled_date : oldDate;
|
||||
const dateChanged = (newDate !== "" && newDate !== oldDate);
|
||||
const statusChanged = (String(newStatus) !== String(oldStatus));
|
||||
|
||||
// Obtener nombre del estado para la lógica
|
||||
// 2. Obtener nombre del estado para saber qué regla aplicar
|
||||
let stName = "";
|
||||
if (newStatus) {
|
||||
if (newStatus && newStatus !== "null") {
|
||||
const statusQ = await pool.query("SELECT name FROM service_statuses WHERE id=$1", [newStatus]);
|
||||
stName = (statusQ.rows[0]?.name || "").toLowerCase();
|
||||
}
|
||||
|
||||
console.log(`DEBUG HS: Exp ${id} | Estado: ${stName} | statusChanged: ${statusChanged} | dateChanged: ${dateChanged}`);
|
||||
console.log(`🤖 [DEBUG HS] Exp: ${id} | Estado: ${stName} | statusChanged: ${statusChanged} | dateChanged: ${dateChanged}`);
|
||||
|
||||
// --- DISPARADORES DE EVENTOS ---
|
||||
|
||||
// 1. WhatsApp Asignación
|
||||
// --- DISPARADORES WHATSAPP ---
|
||||
if (stName.includes('asignado') && finalAssignedTo && statusChanged) {
|
||||
console.log("DEBUG HS: Disparando WA Asignación");
|
||||
await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned');
|
||||
triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_assigned').catch(console.error);
|
||||
}
|
||||
|
||||
// 2. WhatsApp Cita
|
||||
if ((statusChanged && stName.includes('citado') && newDate !== "") || (dateChanged && stName.includes('citado'))) {
|
||||
console.log("DEBUG HS: Disparando WA Cita");
|
||||
if (oldDate === "") await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date');
|
||||
else await triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update');
|
||||
if ((stName.includes('citado') || stName.includes('cita')) && (statusChanged || dateChanged)) {
|
||||
if (oldDate === "" || oldDate === "null") triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_date').catch(console.error);
|
||||
else triggerWhatsAppEvent(req.user.accountId, id, 'wa_evt_update').catch(console.error);
|
||||
}
|
||||
|
||||
// 3. ACTUALIZAR BASE DE DATOS
|
||||
@@ -1600,7 +1597,7 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
|
||||
"Teléfono": phone || rawActual["Teléfono"],
|
||||
"Dirección": address || rawActual["Dirección"],
|
||||
"scheduled_date": newDate,
|
||||
"status_operativo": newStatus
|
||||
"status_operativo": newStatus === "null" ? null : newStatus
|
||||
};
|
||||
|
||||
await pool.query(
|
||||
@@ -1608,24 +1605,30 @@ app.put('/providers/scraped/:id', authMiddleware, async (req, res) => {
|
||||
[JSON.stringify(updatedRawData), finalAssignedTo, id, req.user.accountId]
|
||||
);
|
||||
|
||||
// 4. 🤖 DISPARAR ROBOT HOMESERVE (Lógica reforzada)
|
||||
const esCitado = stName.includes('citado') || stName.includes('cita');
|
||||
const esAsignado = stName.includes('asignado');
|
||||
// 4. 🚀 DISPARAR ROBOT HOMESERVE (SÓLO SI ES HOMESERVE)
|
||||
// Comprobamos si el proveedor es HomeServe antes de mandarlo a la cola
|
||||
const checkHs = await pool.query("SELECT provider FROM scraped_services WHERE id=$1", [id]);
|
||||
if (checkHs.rows[0]?.provider === 'homeserve') {
|
||||
|
||||
if (statusChanged && esAsignado && finalAssignedTo) {
|
||||
console.log("DEBUG HS: Enviando ASIGNACIÓN a la cola del Robot");
|
||||
// Regla de Asignación
|
||||
if (statusChanged && stName.includes('asignado') && finalAssignedTo) {
|
||||
console.log("✅ Enviando ASIGNACIÓN a HomeServe...");
|
||||
triggerHomeServeRobot(req.user.accountId, id, 'assign').catch(console.error);
|
||||
}
|
||||
|
||||
if ((statusChanged && esCitado && newDate !== "") || (dateChanged && esCitado)) {
|
||||
console.log(`DEBUG HS: Enviando CITA (${newDate}) a la cola del Robot`);
|
||||
// Regla de Cita (Si cambia estado a citado O cambia la fecha estando citado)
|
||||
if ((stName.includes('citado') || stName.includes('cita')) && (statusChanged || dateChanged)) {
|
||||
if (newDate && newDate !== "null") {
|
||||
console.log(`✅ Enviando CITA (${newDate}) a HomeServe...`);
|
||||
triggerHomeServeRobot(req.user.accountId, id, 'date').catch(console.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ ok: true });
|
||||
} catch (error) {
|
||||
console.error("ERROR CRÍTICO EN PUT SCRAPED:", error);
|
||||
res.status(500).json({ error: 'Error interno' });
|
||||
console.error("❌ ERROR EN ACTUALIZACIÓN:", error);
|
||||
res.status(500).json({ ok: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user