diff --git a/robot.js b/robot.js index 467a2af..a1beed6 100644 --- a/robot.js +++ b/robot.js @@ -41,18 +41,13 @@ async function main() { } } -// ========================================== -// 🏥 MULTIASISTENCIA V10 (CON DESCRIPCIÓN FIABLE) -// ========================================== async function runMultiasistencia(ownerId, user, pass) { const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] }); const context = await browser.newContext(); const page = await context.newPage(); try { - console.log("🌍 [Multi] Accediendo..."); await page.goto('https://web.multiasistencia.com/w3multi/acceso.php', { timeout: 60000 }); - await page.fill('input[name="usuario"]', user); await page.fill('input[type="password"]', pass); await page.click('input[type="submit"]'); @@ -66,8 +61,6 @@ async function runMultiasistencia(ownerId, user, pass) { return Array.from(new Set(links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean))); }); - 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); @@ -79,16 +72,13 @@ async function runMultiasistencia(ownerId, user, pass) { scrapData = await frame.evaluate(() => { const clean = (t) => t ? t.replace(/\s+/g, ' ').trim() : ""; const body = document.body?.innerText || ""; - if (!body.includes("Nombre Cliente") && !body.includes("Asegurado")) return null; const allCells = Array.from(document.querySelectorAll('td, th, b, div')); - 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; }; - const getV = (keys) => { const header = allCells.find(el => keys.some(k => el.innerText.trim().toUpperCase() === k.toUpperCase())); if (!header) return null; @@ -103,38 +93,41 @@ async function runMultiasistencia(ownerId, user, pass) { return nextRow && nextRow.cells[idx] ? clean(nextRow.cells[idx].innerText) : null; }; - // Lógica específica para la descripción del código que funciona - const getDescription = () => { - let text = getH(["Descripción de la Reparación", "Descripción", "Daños"]) || ""; - // Limpieza de fechas al final del texto - const idxDate = text.search(/\b\d{2}\/\d{2}\/\d{4}\b/); - if (idxDate !== -1) text = text.substring(0, idxDate).trim(); - return clean(text); - }; - - const d = {}; - d['Expediente'] = getH(["Número Reparación", "Número de Servicio"]) || ""; - d['Nombre Cliente'] = getV(["Nombre Cliente", "Asegurado"]) || ""; - d['Dirección'] = getV(["Dirección", "Domicilio"]) || ""; - d['Población_CP'] = getV(["Distrito Postal", "C.P", "Distrito"]) || ""; - d['Compañía'] = getH(["Procedencia", "Compañía"]) || "MULTI - MULTIASISTENCIA"; - d['Descripción'] = getDescription(); - d['Urgente'] = getH(["Urgente"]) || "No"; - d['Fecha Cita'] = getH(["Fecha realización", "Fecha de Realización"]) || ""; + // --- LÓGICA DE LIMPIEZA EN ORIGEN --- + // 1. DESCRIPCIÓN TÉCNICA (Corte por fecha) + let rawDesc = getH(["Descripción de la Reparación", "Descripción", "Daños"]) || ""; + const idxDate = rawDesc.search(/\b\d{2}\/\d{2}\/\d{4}\b/); + const cleanDesc = idxDate !== -1 ? rawDesc.substring(0, idxDate).trim() : rawDesc; + + // 2. SEPARACIÓN DE C.P. Y POBLACIÓN + const rawCPField = getV(["Distrito Postal", "C.P", "Distrito"]) || ""; + const cpMatch = rawCPField.match(/\b\d{5}\b/); + const cpOnly = cpMatch ? cpMatch[0] : ""; + // Extraemos la población eliminando el CP y el guion + const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim(); + + // 3. TELÉFONO LIMPIO (Solo 9 dígitos) const phoneMatch = body.match(/[6789]\d{8}/); - d['Teléfono'] = phoneMatch ? phoneMatch[0] : ""; - return d; + return { + "Expediente": getH(["Número Reparación", "Número de Servicio"]) || "", + "Nombre Cliente": getV(["Nombre Cliente", "Asegurado"]) || "", + "Dirección": getV(["Dirección", "Domicilio"]) || "", + "Población": popOnly, // Nueva clave limpia + "Código Postal": cpOnly, // Nueva clave limpia + "Compañía": getH(["Procedencia", "Compañía"]) || "MULTI", + "Descripción": cleanDesc, + "Teléfono": phoneMatch ? phoneMatch[0] : "", + "Urgente": getH(["Urgente"]) || "No" + }; }); - if (scrapData && scrapData['Nombre Cliente']) break; } catch (e) { continue; } } if (scrapData && scrapData['Nombre Cliente']) { await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData); - console.log(`✅ [Multi] Guardado: ${ref} - ${scrapData['Nombre Cliente']}`); } } } catch (e) { console.error("❌ Error Multi:", e.message); }