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