Actualizar robot.js
This commit is contained in:
96
robot.js
96
robot.js
@@ -153,25 +153,25 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
||||||
|
|
||||||
// 2. Buscar el botón "Página siguiente"
|
// 2. Buscar el botón "Página siguiente"
|
||||||
// Basado en el HTML: <a href="javascript:document.filtros.submit();" onclick="javascript:document.filtros.paginasiguiente.value=X+1">Página siguiente</a>
|
// Ejecutamos exactamente la lógica que usa la web (document.filtros.submit())
|
||||||
const hasNextPage = await page.evaluate(() => {
|
const hasNextPage = await page.evaluate(() => {
|
||||||
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
||||||
const nextBtn = links.find(a => a.innerText.trim() === 'Página siguiente');
|
const nextBtn = links.find(a => a.innerText.trim() === 'Página siguiente');
|
||||||
|
|
||||||
if (nextBtn) {
|
if (nextBtn) {
|
||||||
nextBtn.click(); // Ejecuta el javascript interno de la web
|
nextBtn.click();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (hasNextPage) {
|
if (hasNextPage) {
|
||||||
// Esperamos a que la red se calme tras el submit del formulario de la web
|
// Esperamos a que la red se calme tras el submit del formulario
|
||||||
await page.waitForLoadState('networkidle');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForTimeout(2000); // Un pequeño margen extra
|
await page.waitForTimeout(2000); // Margen extra por si acaso
|
||||||
paginaActual++;
|
paginaActual++;
|
||||||
|
|
||||||
// Medida de seguridad antbucle infinito
|
// Medida de seguridad antibucle
|
||||||
if(paginaActual > 15) {
|
if(paginaActual > 15) {
|
||||||
console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad.");
|
console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad.");
|
||||||
break;
|
break;
|
||||||
@@ -183,7 +183,7 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const expedientes = Array.from(todosExpedientes);
|
const expedientes = Array.from(todosExpedientes);
|
||||||
console.log(`✅ [Multi] Total expedientes únicos detectados: ${expedientes.length}`);
|
console.log(`✅ [Multi] Total expedientes detectados: ${expedientes.length}`);
|
||||||
|
|
||||||
// --- MEJORA: ARCHIVADO ---
|
// --- MEJORA: ARCHIVADO ---
|
||||||
if (expedientes.length > 0) {
|
if (expedientes.length > 0) {
|
||||||
@@ -253,6 +253,90 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// 🧹 HOMESERVE (CON INTELIGENCIA)
|
||||||
|
// ==========================================
|
||||||
|
async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
||||||
|
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
|
||||||
|
const page = await browser.newPage();
|
||||||
|
try {
|
||||||
|
console.log("🌍 [HomeServe] Entrando...");
|
||||||
|
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { timeout: 60000 });
|
||||||
|
|
||||||
|
if (await page.isVisible('input[name="CODIGO"]')) {
|
||||||
|
await page.fill('input[name="CODIGO"]', user);
|
||||||
|
await page.fill('input[type="password"]', pass);
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
const refs = await page.evaluate(() => {
|
||||||
|
const cells = Array.from(document.querySelectorAll('td'));
|
||||||
|
const found = [];
|
||||||
|
cells.forEach(td => {
|
||||||
|
const match = td.innerText.trim().match(/^15\d{6}$/);
|
||||||
|
if (match) found.push(match[0]);
|
||||||
|
});
|
||||||
|
return [...new Set(found)];
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- MEJORA: ARCHIVADO ---
|
||||||
|
if (refs.length > 0) {
|
||||||
|
await syncAndArchive(ownerId, 'homeserve', refs);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`🔍 [HomeServe] ${refs.length} expedientes detectados.`);
|
||||||
|
|
||||||
|
for (const ref of refs) {
|
||||||
|
await page.goto(`https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=ver_servicioencurso&Servicio=${ref}`);
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
const scrapData = await page.evaluate(() => {
|
||||||
|
const d = {};
|
||||||
|
const rows = Array.from(document.querySelectorAll('tr'));
|
||||||
|
rows.forEach(r => {
|
||||||
|
const cells = r.querySelectorAll('td');
|
||||||
|
if (cells.length >= 2) {
|
||||||
|
const k = cells[0].innerText.toUpperCase().trim().replace(':', '');
|
||||||
|
const v = cells[1].innerText.trim();
|
||||||
|
if (k.includes("COMENTARIOS")) {
|
||||||
|
const txt = cells[1].querySelector('textarea')?.value || "";
|
||||||
|
const cleanDesc = txt.split('\n').filter(line => {
|
||||||
|
const l = line.toUpperCase();
|
||||||
|
return !["CAMBIO DE ESTADO", "ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b));
|
||||||
|
}).slice(0, 3).join('\n').trim();
|
||||||
|
d['Descripción'] = cleanDesc;
|
||||||
|
} else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) {
|
||||||
|
d[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const rawPop = d['POBLACION-PROVINCIA'] || "";
|
||||||
|
const cpMatch = rawPop.match(/\b\d{5}\b/);
|
||||||
|
d['Código Postal'] = cpMatch ? cpMatch[0] : "";
|
||||||
|
d['Población'] = rawPop.replace(d['Código Postal'], '').replace('-', '').trim();
|
||||||
|
d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE");
|
||||||
|
d['Nombre Cliente'] = d['CLIENTE'] || "";
|
||||||
|
d['Dirección'] = d['DOMICILIO'] || "";
|
||||||
|
return d;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (scrapData && scrapData['Nombre Cliente']) {
|
||||||
|
// 🪄 MAGIA: Clasificamos el gremio basándonos en la descripción leída de la web
|
||||||
|
const idGremioDetectado = clasificarGremio(scrapData['Descripción'], gremiosDB);
|
||||||
|
if (idGremioDetectado) {
|
||||||
|
scrapData['guild_id'] = idGremioDetectado;
|
||||||
|
}
|
||||||
|
await saveServiceToDB(ownerId, 'homeserve', ref, scrapData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { console.error("❌ [HomeServe] Error:", e.message); }
|
||||||
|
finally { await browser.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
// --- NUEVA FUNCIÓN: SINCRONIZACIÓN Y ARCHIVADO ---
|
// --- NUEVA FUNCIÓN: SINCRONIZACIÓN Y ARCHIVADO ---
|
||||||
async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
|
|||||||
Reference in New Issue
Block a user