Actualizar robot.js
This commit is contained in:
43
robot.js
43
robot.js
@@ -125,7 +125,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🏥 MULTIASISTENCIA (CON REINTENTOS ANTI-CAÍDAS)
|
// 🏥 MULTIASISTENCIA (ROBOT REPARADO Y BLINDADO)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
||||||
const browser = await chromium.launch({
|
const browser = await chromium.launch({
|
||||||
@@ -139,8 +139,9 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
});
|
});
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// INICIO DE SESIÓN CON REINTENTOS
|
console.log("🌍 [Multi] Iniciando sesión...");
|
||||||
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php');
|
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php');
|
||||||
|
|
||||||
await page.fill('input[name="usuario"]', user);
|
await page.fill('input[name="usuario"]', user);
|
||||||
@@ -148,25 +149,19 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
await page.click('input[type="submit"]');
|
await page.click('input[type="submit"]');
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(4000);
|
||||||
|
|
||||||
// ENTRAR AL BUZÓN CON REINTENTOS
|
console.log("📥 [Multi] Entrando al buzón...");
|
||||||
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
|
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
console.log("🔄 [Multi] Forzando recarga segura mediante script interno...");
|
|
||||||
try {
|
|
||||||
await page.evaluate(() => {
|
|
||||||
if (typeof refrescar === 'function') refrescar();
|
|
||||||
});
|
|
||||||
await page.waitForLoadState('networkidle');
|
|
||||||
await page.waitForTimeout(3000);
|
|
||||||
} catch (e) {}
|
|
||||||
|
|
||||||
// --- BUCLE DE PAGINACIÓN ---
|
// --- BUCLE DE PAGINACIÓN ---
|
||||||
let todosExpedientes = new Set();
|
let todosExpedientes = new Set();
|
||||||
let paginaActual = 1;
|
let paginaActual = 1;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
console.log(`\n📄 [Multi] Escaneando página ${paginaActual}...`);
|
console.log(`📄 [Multi] Escaneando página ${paginaActual}...`);
|
||||||
|
|
||||||
|
// Esperamos un poco a que cargue la tabla para evitar que lea en blanco
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
const expedientesPagina = await page.evaluate(() => {
|
const expedientesPagina = await page.evaluate(() => {
|
||||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||||
@@ -176,14 +171,13 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
console.log(` 👉 Encontrados ${expedientesPagina.length} expedientes en la página ${paginaActual}.`);
|
console.log(` 👉 Encontrados ${expedientesPagina.length} expedientes en la página ${paginaActual}.`);
|
||||||
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
||||||
|
|
||||||
const hasNextPage = await page.evaluate(() => {
|
// Buscamos el botón de página siguiente con el selector nativo
|
||||||
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
const nextBtn = page.locator('a.lnkheader:has-text("Página siguiente")').first();
|
||||||
return links.some(a => a.innerText.trim() === 'Página siguiente');
|
const hasNextPage = await nextBtn.count() > 0;
|
||||||
});
|
|
||||||
|
|
||||||
if (hasNextPage) {
|
if (hasNextPage) {
|
||||||
console.log(` ➡️ Botón 'Siguiente' detectado. Pulsando...`);
|
console.log(` ➡️ Botón 'Siguiente' detectado. Pulsando...`);
|
||||||
await page.locator('a.lnkheader:has-text("Página siguiente")').first().click();
|
await nextBtn.click();
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
paginaActual++;
|
paginaActual++;
|
||||||
if(paginaActual > 15) {
|
if(paginaActual > 15) {
|
||||||
@@ -199,9 +193,8 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
const expedientes = Array.from(todosExpedientes);
|
const expedientes = Array.from(todosExpedientes);
|
||||||
console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientes.length}`);
|
console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientes.length}`);
|
||||||
|
|
||||||
// 🛑 NUEVO SEGURO DE VIDA: Si lee menos de 5, desconfiamos de la web y NO archivamos nada, por si es un error puntual.
|
|
||||||
if (expedientes.length > 5 || paginaActual === 1) {
|
if (expedientes.length > 5 || paginaActual === 1) {
|
||||||
console.log(`🧹 Llamando a la escoba (syncAndArchive) con ${expedientes.length} refs...`);
|
console.log(`🧹 [Multi] Llamando a la escoba con ${expedientes.length} refs...`);
|
||||||
await syncAndArchive(ownerId, 'multiasistencia', expedientes);
|
await syncAndArchive(ownerId, 'multiasistencia', expedientes);
|
||||||
} else {
|
} else {
|
||||||
console.log("⚠️ [Multi] Pocos expedientes detectados. ABORTANDO ARCHIVADO DE SEGURIDAD.");
|
console.log("⚠️ [Multi] Pocos expedientes detectados. ABORTANDO ARCHIVADO DE SEGURIDAD.");
|
||||||
@@ -230,16 +223,11 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación"));
|
const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación"));
|
||||||
if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText);
|
if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText);
|
||||||
|
|
||||||
// CORRECCIÓN: Borrado el recorte de fechas destructivo.
|
|
||||||
// Ahora le pasamos todo el bloque de texto completo a la IA para que no se pierdan palabras clave.
|
|
||||||
const cleanDesc = rawDesc;
|
|
||||||
|
|
||||||
const rawCPField = findByCab("Distrito Postal") || "";
|
const rawCPField = findByCab("Distrito Postal") || "";
|
||||||
const cpMatch = rawCPField.match(/\b\d{5}\b/);
|
const cpMatch = rawCPField.match(/\b\d{5}\b/);
|
||||||
const cpOnly = cpMatch ? cpMatch[0] : "";
|
const cpOnly = cpMatch ? cpMatch[0] : "";
|
||||||
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
|
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
|
||||||
|
|
||||||
// 📞 EXTRAER TELÉFONO REAL (Evita coger el de la oficina)
|
|
||||||
let telefonoReal = "";
|
let telefonoReal = "";
|
||||||
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
|
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
|
||||||
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
|
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
|
||||||
@@ -247,7 +235,6 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
|
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
|
||||||
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
|
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
|
||||||
}
|
}
|
||||||
// Fallback por si acaso falla, usamos el que tenías antes
|
|
||||||
if (!telefonoReal || telefonoReal.length < 9) {
|
if (!telefonoReal || telefonoReal.length < 9) {
|
||||||
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
|
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
|
||||||
}
|
}
|
||||||
@@ -259,9 +246,9 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
"Población": popOnly,
|
"Población": popOnly,
|
||||||
"Código Postal": cpOnly,
|
"Código Postal": cpOnly,
|
||||||
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
|
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
|
||||||
"Descripción": cleanDesc,
|
"Descripción": rawDesc,
|
||||||
"Teléfono": telefonoReal,
|
"Teléfono": telefonoReal,
|
||||||
"Estado": findByCab("Estado") || "", // 🛑 AÑADIDO EL ESTADO AQUÍ
|
"Estado": findByCab("Estado") || "",
|
||||||
"Urgente": findByCab("Urgente") || "No"
|
"Urgente": findByCab("Urgente") || "No"
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user