Actualizar robot.js
This commit is contained in:
116
robot.js
116
robot.js
@@ -42,10 +42,10 @@ async function main() {
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 🏥 MULTIASISTENCIA V7 (EXTRACCIÓN POR PATRONES DE TEXTO)
|
||||
// 🏥 MULTIASISTENCIA V8 (LÓGICA BASADA EN FRAMES)
|
||||
// ==========================================
|
||||
async function runMultiasistencia(ownerId, user, pass) {
|
||||
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
|
||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
@@ -53,78 +53,84 @@ async function runMultiasistencia(ownerId, user, pass) {
|
||||
console.log("🌍 [Multi] Accediendo...");
|
||||
await page.goto('https://web.multiasistencia.com/w3multi/acceso.php', { timeout: 60000 });
|
||||
|
||||
const userInput = await page.$('input[name="usuario"]') || await page.$('input[type="text"]');
|
||||
if(userInput) {
|
||||
await userInput.fill(user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.waitForTimeout(5000);
|
||||
}
|
||||
await page.fill('input[name="usuario"]', user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.waitForTimeout(4000);
|
||||
|
||||
await page.goto('https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1', { waitUntil: 'domcontentloaded' });
|
||||
// Forzar recarga de listado
|
||||
await page.goto('https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
const expedientes = await page.evaluate(() => {
|
||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||
return Array.from(new Set(links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean)));
|
||||
});
|
||||
|
||||
console.log(`🔍 [Multi] Procesando ${expedientes.length} expedientes.`);
|
||||
console.log(`🔍 [Multi] ${expedientes.length} expedientes encontrados.`);
|
||||
|
||||
for (const ref of expedientes) {
|
||||
await page.goto(`https://web.multiasistencia.com/w3multi/repasos1.php?reparacion=${ref}`, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
const fullData = await page.evaluate(() => {
|
||||
const text = document.body.innerText;
|
||||
const data = {};
|
||||
let scrapData = null;
|
||||
|
||||
// Función para extraer texto entre dos palabras clave
|
||||
const extract = (start, end) => {
|
||||
const regex = new RegExp(`${start}\\s*:?\\s*([\\s\\S]*?)(?=${end}|$)`, 'i');
|
||||
const match = text.match(regex);
|
||||
return match ? match[1].trim() : null;
|
||||
};
|
||||
// RECORREMOS LOS FRAMES (La clave del éxito)
|
||||
for (const frame of page.frames()) {
|
||||
try {
|
||||
scrapData = await frame.evaluate(() => {
|
||||
const clean = (t) => t ? t.replace(/\s+/g, ' ').trim() : "";
|
||||
const body = document.body?.innerText || "";
|
||||
|
||||
// CAPTURA POR BLOQUES DE TEXTO (IGNORANDO TABLAS)
|
||||
data['Número Reparación'] = extract('Número Reparación', 'Número de Póliza');
|
||||
data['Número de Póliza'] = extract('Número de Póliza', 'Nombre Cliente');
|
||||
data['Nombre Cliente'] = extract('Nombre Cliente', 'Dirección');
|
||||
data['Dirección'] = extract('Dirección', 'Baremo');
|
||||
data['Distrito Postal'] = extract('Distrito Postal', 'Más información');
|
||||
data['Procedencia'] = extract('Procedencia', 'Forma de pago');
|
||||
data['Descripción'] = extract('Descripción de la Reparación', 'Urgente');
|
||||
data['Tramitador'] = extract('Tramitador', 'Teléfono del Cliente');
|
||||
data['Urgente'] = extract('Urgente', 'Fecha realización');
|
||||
data['Fecha realización'] = extract('Fecha realización', 'Estado');
|
||||
// Si este frame no tiene datos de cliente, lo saltamos
|
||||
if (!body.includes("Nombre Cliente") && !body.includes("Asegurado")) return null;
|
||||
|
||||
// Teléfonos (Regex de 9 dígitos limpia)
|
||||
const phones = text.match(/[6789]\d{8}/g);
|
||||
if (phones) data['phone_fixed'] = [...new Set(phones)].join(' / ');
|
||||
const allCells = Array.from(document.querySelectorAll('td, th, b'));
|
||||
|
||||
// Limpieza final: si el valor capturado contiene el nombre de otra etiqueta, está mal
|
||||
const labels = ["Número Reparación", "Dirección", "Nombre Cliente", "Urgente", "Estado"];
|
||||
Object.keys(data).forEach(k => {
|
||||
if (data[k]) {
|
||||
// Cortamos si se nos ha colado la siguiente etiqueta
|
||||
labels.forEach(l => {
|
||||
if (data[k].includes(l)) data[k] = data[k].split(l)[0].trim();
|
||||
});
|
||||
// Quitamos saltos de línea molestos
|
||||
data[k] = data[k].replace(/\n/g, ' ').replace(/\s+/g, ' ');
|
||||
}
|
||||
});
|
||||
// Lógica de búsqueda horizontal (Etiqueta -> Valor al lado)
|
||||
const getH = (keys) => {
|
||||
const header = allCells.find(el => keys.some(k => el.innerText.toUpperCase().includes(k.toUpperCase())));
|
||||
return header && header.nextElementSibling ? clean(header.nextElementSibling.innerText) : null;
|
||||
};
|
||||
|
||||
return data;
|
||||
});
|
||||
// Lógica de búsqueda vertical (Etiqueta -> Valor abajo)
|
||||
const getV = (keys) => {
|
||||
const header = allCells.find(el => keys.some(k => el.innerText.trim().toUpperCase() === k.toUpperCase()));
|
||||
if (!header) return null;
|
||||
const idx = header.cellIndex;
|
||||
const nextRow = header.parentElement.nextElementSibling;
|
||||
return nextRow && nextRow.cells[idx] ? clean(nextRow.cells[idx].innerText) : null;
|
||||
};
|
||||
|
||||
if (fullData && Object.keys(fullData).length > 2) {
|
||||
await saveServiceToDB(ownerId, 'multiasistencia', ref, fullData);
|
||||
// Recolectamos todo con nombres estables para el mapeador
|
||||
const data = {};
|
||||
data['Expediente'] = getH(["Número Reparación", "Expediente"]) || "";
|
||||
data['Nombre Cliente'] = getV(["Nombre Cliente", "Asegurado"]) || "";
|
||||
data['Dirección'] = getV(["Dirección", "Domicilio"]) || "";
|
||||
data['Población_CP'] = getV(["Distrito Postal", "C.P"]) || "";
|
||||
data['Compañía'] = getH(["Procedencia", "Compañía"]) || "";
|
||||
data['Descripción'] = getH(["Descripción de la Reparación", "Descripción"]) || "";
|
||||
data['Urgente'] = getH(["Urgente"]) || "No";
|
||||
data['Fecha Cita'] = getH(["Fecha realización"]) || "";
|
||||
data['Tramitador'] = getH(["Tramitador"]) || "";
|
||||
|
||||
// Teléfono (Busca patrón de 9 dígitos)
|
||||
const phoneMatch = body.match(/[6789]\d{8}/);
|
||||
data['Teléfono'] = phoneMatch ? phoneMatch[0] : "";
|
||||
|
||||
return data;
|
||||
});
|
||||
|
||||
if (scrapData && scrapData['Nombre Cliente']) break; // Si ya encontramos los datos, salimos del bucle de frames
|
||||
} catch (e) { continue; }
|
||||
}
|
||||
|
||||
if (scrapData && scrapData['Nombre Cliente']) {
|
||||
await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("❌ [Multi] Error Crítico:", e.message);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
} catch (e) { console.error("❌ Error Multi:", e.message); }
|
||||
finally { await browser.close(); }
|
||||
}
|
||||
|
||||
// ... (Mantén el resto del archivo igual)
|
||||
|
||||
Reference in New Issue
Block a user