diff --git a/index.js b/index.js
index 55a8797..a0aeab0 100644
--- a/index.js
+++ b/index.js
@@ -1,4 +1,4 @@
-// worker-homeserve.js (Versión Detective V2 - URL Corregida)
+// worker-homeserve.js (Versión Final - Selectores Exactos + Validación Fecha)
'use strict';
const { chromium } = require('playwright');
@@ -10,8 +10,9 @@ const CONFIG = {
RESULT_COLLECTION: process.env.RESULT_COLLECTION || 'homeserve_cambios_estado_log',
HS_CRED_DOC_PATH: process.env.HS_CRED_DOC_PATH || 'providerCredentials/homeserve',
- // ¡CAMBIO IMPORTANTE! Usamos la URL completa de login
+ // URL de Login (la que me confirmaste que funciona)
LOGIN_URL: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS',
+ // Base para construir la URL del servicio
BASE_CGI: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe',
NAV_TIMEOUT: 60000,
@@ -26,11 +27,25 @@ function mustEnv(name) {
if (!v) throw new Error(`Falta variable: ${name}`);
return v;
}
-function pickFirstNonEmpty(...vals) {
- for (const v of vals) {
- if (v !== undefined && v !== null && String(v).trim() !== '') return String(v).trim();
- }
- return '';
+
+// --- VALIDACIÓN DE FECHA (NO SÁBADOS NI DOMINGOS) ---
+function checkWeekend(dateStr) {
+ if (!dateStr) return; // Si no hay fecha, no validamos
+
+ // Formato esperado: DD/MM/AAAA
+ const parts = dateStr.split('/');
+ if (parts.length !== 3) return; // Formato inválido, dejamos que la web se queje
+
+ const day = parseInt(parts[0], 10);
+ const month = parseInt(parts[1], 10) - 1; // Meses en JS son 0-11
+ const year = parseInt(parts[2], 10);
+
+ const d = new Date(year, month, day);
+ const dayOfWeek = d.getDay(); // 0 = Domingo, 6 = Sábado
+
+ if (dayOfWeek === 0 || dayOfWeek === 6) {
+ throw new Error(`⛔ ERROR DE NEGOCIO: La fecha ${dateStr} es fin de semana (Sáb/Dom). No permitido.`);
+ }
}
// --- FIREBASE ---
@@ -48,29 +63,25 @@ function initFirebase() {
return admin.firestore();
}
-// --- CREDENCIALES (Lectura de Firestore) ---
+// --- CREDS ---
async function getHomeServeCreds(db) {
- // Prioridad 1: ENV
- const envUser = pickFirstNonEmpty(process.env.HOMESERVE_USER);
- const envPass = pickFirstNonEmpty(process.env.HOMESERVE_PASS);
- if (envUser && envPass) return { user: envUser, pass: envPass };
-
- // Prioridad 2: Firestore (providerCredentials/homeserve)
- const path = CONFIG.HS_CRED_DOC_PATH;
+ // Intentar ENV primero
+ if (process.env.HOMESERVE_USER && process.env.HOMESERVE_PASS) {
+ return { user: process.env.HOMESERVE_USER, pass: process.env.HOMESERVE_PASS };
+ }
+ // Intentar Firestore
+ const path = CONFIG.HS_CRED_DOC_PATH;
const parts = path.split('/');
-
if (parts.length === 2) {
const snap = await db.collection(parts[0]).doc(parts[1]).get();
if (snap.exists) {
const d = snap.data();
- const user = pickFirstNonEmpty(d.user, d.username, d.usuario);
- const pass = pickFirstNonEmpty(d.pass, d.password, d.clave);
-
- console.log(`[Creds] Leído de Firestore: Usuario termina en ...${user.slice(-3)}`); // Log seguro
+ const user = d.user || d.username || d.usuario;
+ const pass = d.pass || d.password || d.clave;
if (user && pass) return { user, pass };
}
}
- throw new Error('No se encontraron credenciales en providerCredentials/homeserve');
+ throw new Error('Sin credenciales disponibles.');
}
// --- PLAYWRIGHT HELPERS ---
@@ -89,14 +100,6 @@ async function findLocatorInFrames(page, selector) {
return null;
}
-async function fillFirstThatExists(page, selectors, value) {
- for (const sel of selectors) {
- const hit = await findLocatorInFrames(page, sel);
- if (hit) { await hit.locator.first().fill(String(value)); return sel; }
- }
- return null;
-}
-
async function clickFirstThatExists(page, selectors) {
for (const sel of selectors) {
const hit = await findLocatorInFrames(page, sel);
@@ -105,105 +108,123 @@ async function clickFirstThatExists(page, selectors) {
return null;
}
+async function fillFirstThatExists(page, selectors, value) {
+ for (const sel of selectors) {
+ const hit = await findLocatorInFrames(page, sel);
+ if (hit) { await hit.locator.first().fill(String(value)); return sel; }
+ }
+ return null;
+}
+
// --- DIAGNÓSTICO ---
async function getDebugInfo(page) {
try {
const title = await page.title();
const url = page.url();
- // Coge los primeros 500 caracteres de texto visible para ver si hay mensajes de error
- const bodyText = await page.evaluate(() => document.body.innerText.substring(0, 500).replace(/\n/g, ' '));
- return `URL: ${url} || TITULO: "${title}" || TEXTO: "${bodyText}..."`;
- } catch (e) {
- return "No se pudo obtener info de debug.";
- }
+ const bodyText = await page.evaluate(() => document.body.innerText.substring(0, 300).replace(/\n/g, ' '));
+ return `URL: ${url} | Titulo: ${title} | Texto: ${bodyText}...`;
+ } catch (e) { return "Error debug info"; }
}
-// --- LÓGICA PRINCIPAL ---
+// --- LÓGICA PRINCIPAL (TU FLUJO ACTUALIZADO) ---
async function loginAndProcess(page, creds, jobData) {
- console.log('>>> 1. Iniciando navegación a LOGIN...');
+ console.log('>>> 1. Login...');
- // 1. IR A LA PÁGINA DE LOGIN CORRECTA
+ // 1. VALIDAR FECHA ANTES DE NAVEGAR
+ if (jobData.dateString) {
+ checkWeekend(jobData.dateString);
+ }
+ // VALIDAR OBSERVACIONES (Son obligatorias según tu indicación)
+ if (!jobData.observation || jobData.observation.trim().length === 0) {
+ throw new Error('⛔ ERROR: El campo Observaciones es obligatorio.');
+ }
+
+ // 2. LOGIN
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
- await page.waitForTimeout(1000);
+ await page.waitForTimeout(1000); // Estabilidad
- // 2. RELLENAR LOGIN
- const userFilled = await fillFirstThatExists(page, ['input[name="w3user"]', 'input[name*="user" i]', 'input[type="text"]'], creds.user);
- const passFilled = await fillFirstThatExists(page, ['input[name="w3clau"]', 'input[name*="pass" i]', 'input[type="password"]'], creds.pass);
-
- if (!userFilled || !passFilled) {
- const debug = await getDebugInfo(page);
- throw new Error(`No encontré los campos de usuario/contraseña. ¿La página cargó bien? DEBUG: ${debug}`);
- }
-
- // 3. CLICK ENTRAR
- await page.keyboard.press('Enter');
- // Opcional: click en botón si Enter no va
- // await clickFirstThatExists(page, ['input[type="image"]', 'button[type="submit"]']);
+ await fillFirstThatExists(page, ['input[name="w3user"]', 'input[type="text"]'], creds.user);
+ await fillFirstThatExists(page, ['input[name="w3clau"]', 'input[type="password"]'], creds.pass);
- await page.waitForTimeout(3000); // Esperar redirección
+ await page.keyboard.press('Enter');
+ await page.waitForTimeout(3000); // Esperar redirección de login
- // VERIFICACIÓN DE LOGIN: Si seguimos viendo el campo de password, falló.
- const stillLogin = await findLocatorInFrames(page, 'input[type="password"]');
- if (stillLogin) {
- const debug = await getDebugInfo(page);
- throw new Error(`Parece que el login falló (sigo viendo el input password). DEBUG: ${debug}`);
- }
+ // Chequeo rápido de fallo login
+ const loginFail = await findLocatorInFrames(page, 'input[type="password"]');
+ if (loginFail) throw new Error('Login fallido (sigo viendo el password). Revise credenciales.');
- console.log('>>> 2. Login parece correcto. Buscando servicio...');
+ console.log(`>>> 2. Login OK. Yendo al servicio ${jobData.serviceNumber}...`);
- // 4. IR AL SERVICIO DIRECTAMENTE
- const serviceUrl = new URL(CONFIG.BASE_CGI);
- serviceUrl.searchParams.set('w3exec', 'ver_servicioencurso');
- serviceUrl.searchParams.set('Servicio', String(jobData.serviceNumber));
- serviceUrl.searchParams.set('Pag', '1');
+ // 3. CONSTRUIR URL DEL SERVICIO (TU ENLACE EXACTO)
+ // https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=ver_servicioencurso&Servicio=XXXX&Pag=1
+ const serviceUrl = `${CONFIG.BASE_CGI}?w3exec=ver_servicioencurso&Servicio=${jobData.serviceNumber}&Pag=1`;
- await page.goto(serviceUrl.toString(), { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
- await page.waitForTimeout(2000);
+ await page.goto(serviceUrl, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
+ await page.waitForTimeout(1500);
- // 5. BUSCAR BOTÓN "CAMBIAR ESTADO" (REPASO)
- const changeBtn = await clickFirstThatExists(page, [
- 'input[name="repaso"]',
- 'input[title*="Cambiar el Estado" i]',
- 'input[src*="estado1.gif" i]'
- ]);
+ // 4. BUSCAR BOTÓN "REPASO" (TU SELECTOR EXACTO)
+ //
+ const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
if (!changeBtn) {
const debug = await getDebugInfo(page);
- throw new Error(`Login OK, pero NO veo el botón 'repaso' en el servicio ${jobData.serviceNumber}. ¿El parte está cerrado? DEBUG: ${debug}`);
+ throw new Error(`No veo el botón 'repaso'. ¿Servicio ${jobData.serviceNumber} existe/abierto? DEBUG: ${debug}`);
}
- // 6. CAMBIAR ESTADO
+ console.log('>>> 3. Botón repaso clickado. Rellenando formulario...');
+
+ // 5. RELLENAR FORMULARIO
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1000);
- // Seleccionar estado
+ // A) SELECCIONAR ESTADO
+ // Buscamos un