// ================================================================== // MULTI SCAN (SELECTOR INTELIGENTE) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; // Limpieza básica const yyyy = String(anio || ''); const mesNum = parseInt(mes, 10); // Ejemplo: convierte "01" a 1 if (isNaN(mesNum) || !/^\d{4}$/.test(yyyy)) { throw new Error("Mes o Año inválidos. Ejemplo correcto: month='01', year='2026'."); } // Mapa de meses para buscar por texto si falla el número const nombresMeses = [ "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" ]; const nombreMes = nombresMeses[mesNum - 1]; // "enero" try { send('LOG', `🚀 (MULTI) Iniciando scan: ${nombreMes.toUpperCase()} ${yyyy}`); // Login const { browser: b, page } = await loginMulti(send); browser = b; send('LOG', "📂 Yendo a Cerrados..."); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); // --- LÓGICA INTELIGENTE PARA EL DESPLEGABLE D1 --- const selectorD1 = 'select[name="D1"]'; if (await page.isVisible(selectorD1)) { // Ejecutamos código DENTRO del navegador para encontrar la opción correcta const valorASeleccionar = await page.evaluate(({ sel, m, y, name }) => { const select = document.querySelector(sel); if (!select) return null; // Buscamos entre todas las opciones for (const op of select.options) { const txt = op.text.toLowerCase(); // Lo que ve el usuario (ej: "Enero 2026") const val = op.value; // El valor interno (ej: "1_2026") // Criterio 1: Que contenga el año if (!txt.includes(y) && !val.includes(y)) continue; // Criterio 2: Que coincida el mes (por número 1, 01 o por nombre "enero") // Verificamos si el texto contiene "enero" O si el valor empieza por "1_" o "01_" const mesMatchTexto = txt.includes(name); const mesMatchValor = val.startsWith(m + '_') || val.startsWith('0' + m + '_'); if (mesMatchTexto || mesMatchValor) { return op.value; // ¡Encontrado! Devolvemos el valor exacto que necesita la web } } return null; }, { sel: selectorD1, m: mesNum, y: yyyy, name: nombreMes }); if (valorASeleccionar) { send('LOG', `✅ Opción encontrada: "${valorASeleccionar}". Seleccionando...`); await page.selectOption(selectorD1, valorASeleccionar); } else { throw new Error(`❌ No encontré ninguna opción en el desplegable para ${nombreMes} del ${yyyy}`); } // Seleccionar D2 (Año) si existe, por seguridad if (await page.isVisible('select[name="D2"]')) { await page.selectOption('select[name="D2"]', yyyy).catch(() => {}); } await page.click('input[name="continuar"]'); await page.waitForTimeout(3000); } else { send('LOG', "⚠️ No veo el filtro D1 (¿cambió la página?)."); } // --- (EL RESTO DEL CÓDIGO SIGUE IGUAL: FASE 1 IDs y FASE 2 DETALLES) --- // Copia aquí el bloque "FASE 1: IDS" y "FASE 2: DETALLES" de tu código anterior // ... // ... // (Para no hacer el mensaje eterno, asumo que mantienes el resto igual) // --- PEGA ESTO JUSTO DESPUÉS DEL IF DEL SELECTOR --- let idsServicios = []; let tieneSiguiente = true; let pagActual = 1; while (tieneSiguiente && pagActual <= 10) { send('LOG', `📄 Leyendo página ${pagActual}...`); const nuevosIds = await page.evaluate(() => { const celdas = Array.from(document.querySelectorAll('td.tdet')); const lista = []; celdas.forEach(td => { const txt = (td.innerText || '').trim(); if (/^\d{8}$/.test(txt)) lista.push(txt); }); return lista; }); idsServicios.push(...[...new Set(nuevosIds)]); send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`); const haySiguiente = await page.$('a:has-text("Página siguiente")'); if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; } else { tieneSiguiente = false; } } idsServicios = [...new Set(idsServicios)]; send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); if (idsServicios.length === 0) { send('FINISH_SCAN', {}); return; } for (const [index, idServicio] of idsServicios.entries()) { send('PROGRESS', { current: index + 1, total: idsServicios.length }); const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`; try { await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' }); await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {}); let clienteWeb = "Desconocido"; let direccionWeb = "Sin dirección"; for (const frame of page.frames()) { try { const data = await frame.evaluate(() => { let c = ""; let d = ""; const bloques = Array.from(document.querySelectorAll('.policy-info-block')); bloques.forEach(b => { const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || ""; const v = b.querySelector('.policy-info-value')?.innerText || ""; if (t.includes("CLIENTE")) c = v; if (t.includes("DIRECCIÓN")) d = v; }); return { c, d }; }); if (data.c) clienteWeb = data.c.trim(); if (data.d) direccionWeb = data.d.trim(); } catch {} } const importe = await getTotalReparacion(page); if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} en 0€ (no encontrado).`); let docId = null; let enBD = false; let clienteFinal = clienteWeb; let direccionFinal = direccionWeb; if (db) { const q = await db.collection("appointments").where("serviceNumber", "==", idServicio).get(); if (!q.empty) { const doc = q.docs[0]; docId = doc.id; enBD = true; if (doc.data().clientName) clienteFinal = doc.data().clientName; if (doc.data().address) direccionFinal = doc.data().address; } } send('ITEM_FOUND', { servicio: idServicio, direccion: direccionFinal, cliente: clienteFinal, importe, enBD, docId }); } catch (errDetail) { send('LOG', `⚠️ Error ${idServicio}: ${errDetail.message}`); } } send('FINISH_SCAN', {}); } finally { if (browser) await browser.close().catch(()=>{}); } }