This commit is contained in:
2025-07-17 13:47:44 -05:00
parent f93c3da38a
commit d006b9acf8
4 changed files with 2255 additions and 596 deletions
BIN
View File
Binary file not shown.
+151 -593
View File
@@ -616,7 +616,7 @@ async function createNewWindow() {
show: false, show: false,
webPreferences: { webPreferences: {
nodeIntegration: true, nodeIntegration: true,
contextIsolation: false, // contextIsolation: false,
partition: 'nopersist' partition: 'nopersist'
}, },
}); });
@@ -657,433 +657,11 @@ const mainIni = async () => {
}; };
async function openExternalBrowserForTYD075(webApp) {
console.log('>> Iniciando TYD075 en navegador externo');
try {
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
args: [
`--app=${webApp.url}`,
'--start-maximized',
'--no-sandbox',
'--disable-setuid-sandbox'
],
executablePath: process.platform === 'win32'
? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
: undefined
});
const pages = await browser.pages();
const page = pages[0];
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('>> Rellenando credenciales para TYD075');
await page.waitForSelector('#username', { timeout: 10000 });
const usernameField = await page.$('#username');
if (usernameField) {
await usernameField.click({ clickCount: 3 });
await usernameField.type(webApp.username, { delay: 5 });
console.log('>> Campo usuario rellenado');
}
await page.waitForSelector('#password', { timeout: 5000 });
const passwordField = await page.$('#password');
if (passwordField) {
await passwordField.click({ clickCount: 3 });
await passwordField.type(webApp.password, { delay: 5 });
console.log('>> Campo contraseña rellenado');
}
await page.waitForSelector('#loginform fieldset button', { timeout: 5000 });
const loginButton = await page.$('#loginform fieldset button');
if (loginButton) {
await loginButton.click();
console.log('>> Click en botón de login realizado');
try {
await page.waitForNavigation({
waitUntil: 'networkidle0',
timeout: 1500
});
console.log('>> Navegación después del login completada');
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
});
console.log('>> Medidas de seguridad aplicadas correctamente');
} catch (navError) {
console.log('>> No hubo navegación o ya estamos en la página correcta');
try {
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
const userField = document.querySelector('#username');
const passField = document.querySelector('#password');
const loginBtn = document.querySelector('#loginform fieldset button');
if (userField) {
userField.setAttribute('readonly', 'true');
userField.style.pointerEvents = 'none';
}
if (passField) {
passField.setAttribute('readonly', 'true');
passField.style.pointerEvents = 'none';
}
if (loginBtn) {
loginBtn.style.pointerEvents = 'none';
}
});
} catch (evalError) {
console.log('>> Error al aplicar medidas de seguridad:', evalError.message);
}
}
}
await new Promise(resolve => setTimeout(resolve, 5000));
try {
const errorElements = await page.$x('//*[contains(text(), "incorrect") or contains(text(), "error") or contains(text(), "invalid")]');
if (errorElements.length > 0) {
console.log('>> Error de credenciales detectado');
dialog.showErrorBox('Error', 'Credenciales incorrectas para TYD075. Por favor, repórtalo al Coordinador');
await browser.close();
return false;
}
} catch (e) {
console.log('>> No se detectaron errores de login');
}
console.log('>> TYD075 iniciado exitosamente en navegador externo');
return true;
} catch (error) {
console.error('>> Error al abrir TYD075 en navegador externo:', error);
dialog.showErrorBox('Error', `No se pudo abrir TYD075: ${error.message}`);
return false;
}
}
async function openExternalBrowserForDIM072(webApp) {
console.log('>> Iniciando DIM072 en navegador externo');
try {
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
args: [
`--app=${webApp.url}`,
'--start-maximized',
'--no-sandbox',
'--disable-setuid-sandbox'
],
executablePath: process.platform === 'win32'
? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
: undefined
});
const pages = await browser.pages();
const page = pages[0];
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('>> Rellenando credenciales para DIM072');
await page.waitForSelector('#Usuario', { timeout: 5000 });
const usernameField = await page.$('#Usuario');
if (usernameField) {
await usernameField.click({ clickCount: 3 });
await usernameField.type(webApp.username, { delay: 5 });
console.log('>> Campo usuario rellenado');
}
await page.waitForSelector('#Contrase_a', { timeout: 5000 });
const passwordField = await page.$('#Contrase_a');
if (passwordField) {
await passwordField.click({ clickCount: 3 });
await passwordField.type(webApp.password, { delay: 5 });
console.log('>> Campo contraseña rellenado');
}
await new Promise(resolve => setTimeout(resolve, 250));
await page.waitForSelector('button[class="btn btn-lg red"]', { timeout: 5000 });
const loginButton = await page.$('button[class="btn btn-lg red"]');
if (loginButton) {
await loginButton.click();
console.log('>> Click en botón de login realizado');
try {
await page.waitForNavigation({
waitUntil: 'networkidle0',
timeout: 1500
});
console.log('>> Navegación después del login completada');
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
});
console.log('>> Medidas de seguridad aplicadas correctamente');
} catch (navError) {
console.log('>> No hubo navegación o ya estamos en la página correcta');
try {
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
const userField = document.querySelector('#Usuario');
const passField = document.querySelector('#Contrase_a');
const loginBtn = document.querySelector('button[class="btn btn-lg red"]');
if (userField) {
userField.setAttribute('readonly', 'true');
userField.style.pointerEvents = 'none';
}
if (passField) {
passField.setAttribute('readonly', 'true');
passField.style.pointerEvents = 'none';
}
if (loginBtn) {
loginBtn.style.pointerEvents = 'none';
}
});
} catch (evalError) {
console.log('>> Error al aplicar medidas de seguridad:', evalError.message);
}
}
}
await new Promise(resolve => setTimeout(resolve, 5000));
try {
const errorElements = await page.$x('//*[contains(text(), "incorrect") or contains(text(), "error") or contains(text(), "invalid")]');
if (errorElements.length > 0) {
console.log('>> Error de credenciales detectado');
dialog.showErrorBox('Error', 'Credenciales incorrectas para DIM072. Por favor, repórtalo al Coordinador');
await browser.close();
return false;
}
} catch (e) {
console.log('>> No se detectaron errores de login');
}
console.log('>> DIM072 iniciado exitosamente en navegador externo');
return true;
} catch (error) {
console.error('>> Error al abrir DIM072 en navegador externo:', error);
dialog.showErrorBox('Error', `No se pudo abrir DIM072: ${error.message}`);
return false;
}
}
async function openExternalBrowserForTUN065(webApp) {
console.log('>> Iniciando TUN065 en navegador externo');
try {
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
args: [
`--app=${webApp.url}`,
'--start-maximized',
'--no-sandbox',
'--disable-setuid-sandbox'
],
executablePath: process.platform === 'win32'
? 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe'
: undefined
});
const pages = await browser.pages();
const page = pages[0];
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('>> Rellenando credenciales para TUN065');
await page.waitForSelector('input[name="ctl00$cpC$dcLogin$txtUserId"]', { timeout: 5000 });
const usernameField = await page.$('input[name="ctl00$cpC$dcLogin$txtUserId"]');
if (usernameField) {
await usernameField.click({ clickCount: 3 });
await usernameField.type(webApp.username, { delay: 5 });
console.log('>> Campo usuario rellenado');
}
await page.waitForSelector('input[name="ctl00$cpC$dcLogin$txtPassword"]', { timeout: 5000 });
const passwordField = await page.$('input[name="ctl00$cpC$dcLogin$txtPassword"]');
if (passwordField) {
await passwordField.click({ clickCount: 3 });
await passwordField.type(webApp.password, { delay: 5 });
console.log('>> Campo contraseña rellenado');
}
await new Promise(resolve => setTimeout(resolve, 50));
await page.waitForSelector('div[class="button fs-bold text-center"]', { timeout: 5000 });
const loginButton = await page.$('div[class="button fs-bold text-center"]');
if (loginButton) {
await loginButton.click();
console.log('>> Click en botón de login realizado');
try {
await page.waitForNavigation({
waitUntil: 'networkidle0',
timeout: 1000
});
console.log('>> Navegación después del login completada');
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
});
console.log('>> Medidas de seguridad aplicadas correctamente');
} catch (navError) {
console.log('>> No hubo navegación o ya estamos en la página correcta');
try {
await page.evaluate(() => {
document.addEventListener('contextmenu', event => event.preventDefault());
document.addEventListener('keydown', (e) => {
if (
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I') ||
(e.ctrlKey && e.shiftKey && e.key === 'J') ||
(e.ctrlKey && e.key === 'U')
) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
const userField = document.querySelector('input[name="ctl00$cpC$dcLogin$txtUserId"]');
const passField = document.querySelector('input[name="ctl00$cpC$dcLogin$txtPassword"]');
const loginBtn = document.querySelector('div[class="button fs-bold text-center"]');
if (userField) {
userField.setAttribute('readonly', 'true');
userField.style.pointerEvents = 'none';
}
if (passField) {
passField.setAttribute('readonly', 'true');
passField.style.pointerEvents = 'none';
}
if (loginBtn) {
loginBtn.style.pointerEvents = 'none';
}
});
} catch (evalError) {
console.log('>> Error al aplicar medidas de seguridad:', evalError.message);
}
}
}
await new Promise(resolve => setTimeout(resolve, 5000));
try {
const errorElements = await page.$x('//*[contains(text(), "incorrect") or contains(text(), "error") or contains(text(), "invalid")]');
if (errorElements.length > 0) {
console.log('>> Error de credenciales detectado');
dialog.showErrorBox('Error', 'Credenciales incorrectas para TUN065. Por favor, repórtalo al Coordinador');
await browser.close();
return false;
}
} catch (e) {
console.log('>> No se detectaron errores de login');
}
console.log('>> TUN065 iniciado exitosamente en navegador externo');
return true;
} catch (error) {
console.error('>> Error al abrir TUN065 en navegador externo:', error);
dialog.showErrorBox('Error', `No se pudo abrir IDV03: ${error.message}`);
return false;
}
}
async function openExternalBrowserForPOL(webApp) { async function openExternalBrowserForPOL(webApp) {
console.log('>> Iniciando POLIEDRO en navegador externo'); console.log('>> Iniciando POLIEDRO en navegador externo');
@@ -1118,10 +696,10 @@ async function openExternalBrowserForPOL(webApp) {
for (let attempt = 1; attempt <= maxRetries; attempt++) { for (let attempt = 1; attempt <= maxRetries; attempt++) {
try { try {
console.log(`>> Intento ${attempt} para llenar ${fieldName}`); console.log(`>> Intento ${attempt} para llenar ${fieldName}`);
await page.waitForSelector(selector, { timeout: 10000 }); await page.waitForSelector(selector, { timeout: 10000 });
const field = await page.$(selector); const field = await page.$(selector);
if (!field) { if (!field) {
throw new Error(`Campo ${fieldName} no encontrado`); throw new Error(`Campo ${fieldName} no encontrado`);
} }
@@ -1141,7 +719,7 @@ async function openExternalBrowserForPOL(webApp) {
// Verificar que el valor se escribió correctamente // Verificar que el valor se escribió correctamente
await new Promise(resolve => setTimeout(resolve, 500)); await new Promise(resolve => setTimeout(resolve, 500));
const currentValue = await page.$eval(selector, el => el.value); const currentValue = await page.$eval(selector, el => el.value);
if (currentValue === value) { if (currentValue === value) {
console.log(`>> ${fieldName} rellenado correctamente: `); console.log(`>> ${fieldName} rellenado correctamente: `);
return true; return true;
@@ -1186,7 +764,7 @@ async function openExternalBrowserForPOL(webApp) {
await page.waitForSelector('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]', { timeout: 5000 }); await page.waitForSelector('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]', { timeout: 5000 });
const loginButton = await page.$('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]'); const loginButton = await page.$('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]');
if (loginButton) { if (loginButton) {
const isDisabled = await page.$eval('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]', el => el.disabled); const isDisabled = await page.$eval('input[name="ctl00$ContentPlaceHolder1$btnIngresarUsuarioContraseña"]', el => el.disabled);
if (isDisabled) { if (isDisabled) {
@@ -1209,7 +787,7 @@ async function openExternalBrowserForPOL(webApp) {
for (let element of elements) { for (let element of elements) {
const text = element.textContent.toLowerCase(); const text = element.textContent.toLowerCase();
if (text.includes('incorrect') || text.includes('error') || text.includes('invalid') || if (text.includes('incorrect') || text.includes('error') || text.includes('invalid') ||
text.includes('incorrecto') || text.includes('inválido') || text.includes('incorrecto') || text.includes('inválido') ||
(text.includes('usuario') && text.includes('contraseña'))) { (text.includes('usuario') && text.includes('contraseña'))) {
return true; return true;
} }
@@ -1282,7 +860,7 @@ async function openExternalBrowserForPOL(webApp) {
if (!authCompleted && attempts >= maxAttempts) { if (!authCompleted && attempts >= maxAttempts) {
console.log('>> Tiempo de espera agotado para autenticación OTP'); console.log('>> Tiempo de espera agotado para autenticación OTP');
dialog.showWarningBox('Tiempo Agotado', dialog.showWarningBox('Tiempo Agotado',
'El tiempo de espera para la autenticación OTP ha expirado. La sesión seguirá activa, pero puede que necesite completar manualmente el proceso.'); 'El tiempo de espera para la autenticación OTP ha expirado. La sesión seguirá activa, pero puede que necesite completar manualmente el proceso.');
} }
} }
@@ -1447,57 +1025,31 @@ async function rpa(data_code) {
xpath_password = webApp.xpath_pass; xpath_password = webApp.xpath_pass;
xpath_button = webApp.btn_login; xpath_button = webApp.btn_login;
if (data_code === 'TYD075') { // if (data_code === 'POL911' || data_code === 'POL912' || data_code === 'POL913' || data_code === 'POL914' || data_code === 'POL915' || data_code === 'POD911') {
console.log('>> Detectado TYD075 - Usando navegador externo'); // console.log('poliedro test');
const success = await openExternalBrowserForTYD075(webApp); // await page.evaluateOnNewDocument(() => {
if (!success) { // const script = document.createElement('script');
console.log('>> Error al procesar TYD075'); // script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
} // script.type = 'text/javascript';
return; // document.head.appendChild(script);
} // })
if (data_code === 'DIM072') {
console.log('>> Detectado DIM072 - Usando navegador externo');
const success = await openExternalBrowserForDIM072(webApp);
if (!success) {
console.log('>> Error al procesar DIM072');
}
return;
}
if (data_code === 'TUN065') { // }
console.log('>> Detectado TUN065 - Usando navegador externo');
const success = await openExternalBrowserForTUN065(webApp);
if (!success) {
console.log('>> Error al procesar TUN065');
}
return;
}
if (data_code === 'POL911' || data_code === 'POL912' || data_code === 'POL913' || data_code === 'POL914' || data_code === 'POL915' || data_code === 'POD911') {
console.log('>> Detectado POLIEDRO - Usando navegador externo');
const success = await openExternalBrowserForPOL(webApp);
if (!success) {
console.log('>> Error al procesar POLIEDRO');
}
return;
}
if (!windowNew || windowNew.isDestroyed()) {
windowNew = new BrowserWindow({
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
ignoreHTTPSErrors: true,
width: 1200,
height: 650,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
partition: 'nopersist'
},
});
}
windowNew = new BrowserWindow({
args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors'],
ignoreHTTPSErrors: true,
width: 1200,
height: 650,
show: false,
webPreferences: {
nodeIntegration: true,
// contextIsolation: false,
partition: 'nopersist',
},
});
windowNew.setMenu(null);
windowNew.on('closed', function () { windowNew.on('closed', function () {
windowNew = null; windowNew = null;
console.log('>> Ventana cerrada'); console.log('>> Ventana cerrada');
@@ -1509,6 +1061,8 @@ async function rpa(data_code) {
webApp.url = 'https://poliedro.comcel.com.co/LoginPoliedro/Login.aspx'; webApp.url = 'https://poliedro.comcel.com.co/LoginPoliedro/Login.aspx';
} }
windowNew.loadURL(webApp.url); windowNew.loadURL(webApp.url);
windowNew.show(); windowNew.show();
windowNew.maximize(); windowNew.maximize();
windowNew.setIgnoreMouseEvents(false); windowNew.setIgnoreMouseEvents(false);
@@ -1684,78 +1238,45 @@ async function rpa(data_code) {
// var page; // var page;
var pageUrl; var pageUrl;
// for (const pages_sel of pages) {
// const pageUrl = await pages_sel.url();
// // console.log('la obtenida: ' + pageUrl + '_____' + 'la real: ' + url_mod);
// if (pageUrl == 'http://100.126.20.149:8080/sara/login') {
// url_mod = 'http://100.126.20.149:8080/sara/login';
// }
// if (pageUrl == 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0') {
// url_mod = 'http://dime.claro.com.co/Portal/Produccion/Sesion/Inicio/Ingresar?ReturnUrl=%2FPortal%2FProduccion%2FFidelizacion%2FRetencion%2FRegistrarSolicitud%3Fdato%3D1007227477%26Cuenta%3D89715445%26Ticket%3D1%26Internet%3D1%26TV%3D1%26Telefonia%3D0';
// }
// if (pageUrl === url_mod) {
// console.log(`Ok pagina`);
// page = pages_sel;
// break; // Detén el bucle cuando encuentras la coincidencia
// }
// }
if (page) { if (page) {
console.log(`Nombre de la pagina: ${await page.title()}`); console.log(`Nombre de la pagina: ${await page.title()}`);
if (data_code == 'ASW049') { console.log('Debug - username:', username);
console.log('avaya web'); console.log('Debug - password:', password);
await new Promise(resolve => setTimeout(resolve, 5000)); console.log('Debug - webApp.username:', webApp.username);
console.log('okan avaya'); console.log('Debug - webApp.password:', webApp.password);
} console.log('Debug - xpath_username:', xpath_username);
console.log('Debug - xpath_password:', xpath_password);
// await page.waitForLoad();
if (xpath_username != 'na') { const performLogin = async (page, appCode, username, password, webApp, xpath_username, xpath_password, xpath_button) => {
// if (data_code == 'POL911' || data_code == 'POL912' || data_code == 'POL913' || data_code == 'POL914' || data_code == 'POL915' || data_code == 'POD911') { if (appCode === 'TYD075') {
// await page.waitForXPath('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]'); console.log('>> Detectado TYD075 - Usando Puppeteer interno');
// const backBtn = await page.$x('//input[@id="ctl00_ContentPlaceHolder1_BtnRegresarMensaje"]'); await page.waitForSelector('#username', { timeout: 15000 });
// await backBtn[0].click(); await page.type('#username', webApp.username, { delay: 5 });
// } await page.waitForSelector('#password', { timeout: 15000 });
if (!loginCodes.includes(data_code)) { await page.type('#password', webApp.password, { delay: 5 });
await page.click('button[type="submit"]');
if (data_code == 'CLU100') { } else if (appCode === 'DIM072') {
const elementHandleClu = await page.$('.sign-in-uclaro'); console.log('>> Detectado DIM072 - Usando Puppeteer interno');
if (elementHandleClu) { await page.waitForSelector('#Usuario', { timeout: 15000 });
await elementHandleClu.click(); await page.type('#Usuario', webApp.username, { delay: 5 });
} await page.waitForSelector('#Contrase_a', { timeout: 15000 });
} await page.type('#Contrase_a', webApp.password, { delay: 5 });
//empieza a llenar el campo de usuario await page.click('button#btiniciar');
await page.waitForXPath(xpath_username); } else if (appCode === 'TUN065') {
const elementHandleUser = await page.$x(xpath_username); console.log('>> Detectado TUN065 - Usando Puppeteer interno');
await elementHandleUser[0].type('', { delay: 100 }); await page.waitForSelector('input[name="ctl00$cpC$dcLogin$txtUserId"]', { timeout: 15000 });
await elementHandleUser[0].type(username); await page.type('input[name="ctl00$cpC$dcLogin$txtUserId"]', webApp.username, { delay: 5 });
console.log('>> Diligencio campo usuario'); await page.waitForSelector('input[name="ctl00$cpC$dcLogin$txtPassword"]', { timeout: 15000 });
await page.type('input[name="ctl00$cpC$dcLogin$txtPassword"]', webApp.password, { delay: 5 });
if (data_code == 'ABS099') { await page.click('div[class="button fs-bold text-center"]');
await page.keyboard.press("Enter"); } else if (appCode === 'ASW049') {
} else { console.log('avaya web');
await page.keyboard.press("Tab"); await new Promise(resolve => setTimeout(resolve, 5000));
} console.log('okan avaya');
} else if (appCode === 'MAP039') {
if (data_code == 'AGE036') {
await page.waitForTimeout(4000);
} else {
await page.waitForTimeout(1000);
}
await page.waitForXPath(xpath_password);
const elementHandlePass = await page.$x(xpath_password);
await elementHandlePass[0].type('', { delay: 100 });
await elementHandlePass[0].type(password);
console.log('>> Diligencio campo password');
await page.waitForTimeout(1000);
// Manejo específico para MAP039
if (data_code === 'MAP039') {
console.log('>> Procesando botón de login para MAP039...'); console.log('>> Procesando botón de login para MAP039...');
try { try {
console.log('>> Intentando submit directo del formulario...'); console.log('>> Intentando submit directo del formulario...');
const formSubmitted = await page.evaluate(() => { const formSubmitted = await page.evaluate(() => {
@@ -1766,7 +1287,6 @@ async function rpa(data_code) {
} }
return false; return false;
}); });
if (formSubmitted) { if (formSubmitted) {
console.log('>> Formulario enviado con submit()'); console.log('>> Formulario enviado con submit()');
} else { } else {
@@ -1783,10 +1303,8 @@ async function rpa(data_code) {
}); });
console.log('>> Evento submit disparado'); console.log('>> Evento submit disparado');
} }
} catch (error) { } catch (error) {
console.log('>> Error con submit:', error.message); console.log('>> Error con submit:', error.message);
try { try {
console.log('>> Intentando click forzado en div Entrar...'); console.log('>> Intentando click forzado en div Entrar...');
await page.evaluate(() => { await page.evaluate(() => {
@@ -1803,45 +1321,86 @@ async function rpa(data_code) {
console.log('>> Click forzado realizado'); console.log('>> Click forzado realizado');
} catch (clickError) { } catch (clickError) {
console.log('>> Click forzado falló:', clickError.message); console.log('>> Click forzado falló:', clickError.message);
console.log('>> Intentando Enter en campo contraseña...'); console.log('>> Intentando Enter en campo contraseña...');
await page.focus('#contra'); await page.focus('#contra');
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
} }
} }
await page.waitForTimeout(2000); await page.waitForTimeout(2000);
} else if (xpath_username !== 'na') {
if (!loginCodes.includes(appCode)) {
if (appCode === 'CLU100') {
const elementHandleClu = await page.$('.sign-in-uclaro');
if (elementHandleClu) {
await elementHandleClu.click();
}
}
await page.waitForXPath(xpath_username);
const elementHandleUser = await page.$x(xpath_username);
await elementHandleUser[0].type('', { delay: 100 });
await elementHandleUser[0].type(username);
console.log('>> Diligencio campo usuario');
} else { if (appCode === 'ABS099') {
const xpathMap = { await page.keyboard.press("Enter");
'DIM072': '//button[contains(@id, "btiniciar")]', } else {
'CLU100': '//button[contains(@class, "ingresarBoton")]', await page.keyboard.press("Tab");
'CMC093': xpath_button, }
'MCA030': '//input[contains(@id, "login-button")]'
};
const xpath = xpathMap[data_code] || null; if (appCode === 'AGE036') {
await page.waitForTimeout(4000);
} else {
await page.waitForTimeout(1000);
}
if (xpath) { await page.waitForXPath(xpath_password);
try { const elementHandlePass = await page.$x(xpath_password);
await page.waitForXPath(xpath, { timeout: 5000 }); await elementHandlePass[0].type('', { delay: 100 });
const elementHandle = await page.$x(xpath); await elementHandlePass[0].type(password);
if (elementHandle && elementHandle.length > 0) { console.log('>> Diligencio campo password');
await elementHandle[0].click();
console.log('>> Se dio click en boton'); await page.waitForTimeout(1000);
} else {
console.log('>> No encontro boton'); const xpathMap = {
'DIM072': '//button[contains(@id, "btiniciar")]',
'CLU100': '//button[contains(@class, "ingresarBoton")]',
'CMC093': xpath_button,
'MCA030': '//input[contains(@id, "login-button")]'
};
const xpath = xpathMap[appCode] || null;
if (xpath) {
try {
await page.waitForXPath(xpath, { timeout: 5000 });
const elementHandle = await page.$x(xpath);
if (elementHandle && elementHandle.length > 0) {
await elementHandle[0].click();
console.log('>> Se dio click en boton');
} else {
console.log('>> No encontro boton');
await page.keyboard.press('Enter');
}
} catch (error) {
console.log('>> Error esperando botón, usando Enter');
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
} }
} catch (error) { } else {
console.log('>> Error esperando botón, usando Enter');
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
} }
} else {
await page.keyboard.press('Enter');
} }
} }
} };
console.log(`DEBUG: username = ${username}`);
console.log(`DEBUG: password = ${password}`);
console.log(`DEBUG: webApp.username = ${webApp.username}`);
console.log(`DEBUG: webApp.password = ${webApp.password}`);
await performLogin(page, data_code, username, password, webApp, xpath_username, xpath_password, xpath_button);
// await page.waitForNavigation({ waitUntil: 'networkidle0', timeout: 60000 });
console.log('>> Cargo la pagina');
console.log('>> Formulario enviado');
// await page.waitForTimeout(70000); // await page.waitForTimeout(70000);
@@ -1854,57 +1413,57 @@ async function rpa(data_code) {
console.log('>> Procesando aplicativo Poliedro'); console.log('>> Procesando aplicativo Poliedro');
try { try {
console.log('>> Esperando campo de token...'); console.log('>> Esperando campo de token...');
try { try {
await page.waitForSelector('td[colspan="2"][class="auto-style1"]', { await page.waitForSelector('td[colspan="2"][class="auto-style1"]', {
visible: true, visible: true,
timeout: 10000 timeout: 10000
}); });
const element = await page.$('td[colspan="2"][class="auto-style1"]'); const element = await page.$('td[colspan="2"][class="auto-style1"]');
const textContent = await page.evaluate(el => el.textContent, element); const textContent = await page.evaluate(el => el.textContent, element);
console.log(`>> Contenido encontrado: ${textContent.trim()}`); console.log(`>> Contenido encontrado: ${textContent.trim()}`);
if (textContent.includes('token') && textContent.includes('SMS')) { if (textContent.includes('token') && textContent.includes('SMS')) {
console.log('>> Campo de token detectado - Habilitando interacción completa'); console.log('>> Campo de token detectado - Habilitando interacción completa');
windowNew.setIgnoreMouseEvents(false); windowNew.setIgnoreMouseEvents(false);
windowNew.show(); windowNew.show();
windowNew.focus(); windowNew.focus();
windowNew.setAlwaysOnTop(true); windowNew.setAlwaysOnTop(true);
setTimeout(() => { setTimeout(() => {
windowNew.setAlwaysOnTop(false); windowNew.setAlwaysOnTop(false);
}, 1000); }, 1000);
const notification = new Notification({ const notification = new Notification({
title: 'Acción requerida - Poliedro', title: 'Acción requerida - Poliedro',
body: 'Ingresa el código de verificación. La ventana ya está habilitada para uso.', body: 'Ingresa el código de verificación. La ventana ya está habilitada para uso.',
icon: 'logo-claro.ico' icon: 'logo-claro.ico'
}); });
notification.show(); notification.show();
console.log('>> Interacción habilitada permanentemente para Poliedro'); console.log('>> Interacción habilitada permanentemente para Poliedro');
return; return;
} else { } else {
throw new Error('Contenido no coincide con mensaje de token'); throw new Error('Contenido no coincide con mensaje de token');
} }
} catch (tokenError) { } catch (tokenError) {
console.log('>> No se encontró mensaje de token, verificando login exitoso...'); console.log('>> No se encontró mensaje de token, verificando login exitoso...');
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
windowNew.setIgnoreMouseEvents(false); windowNew.setIgnoreMouseEvents(false);
windowNew.show(); windowNew.show();
windowNew.focus(); windowNew.focus();
console.log('>> Interacción habilitada para uso normal de Poliedro'); console.log('>> Interacción habilitada para uso normal de Poliedro');
} }
} catch (e) { } catch (e) {
console.log('>> Error en Poliedro, habilitando interacción manual: ' + e); console.log('>> Error en Poliedro, habilitando interacción manual: ' + e);
windowNew.setIgnoreMouseEvents(false); windowNew.setIgnoreMouseEvents(false);
windowNew.show(); windowNew.show();
windowNew.focus(); windowNew.focus();
@@ -1912,7 +1471,7 @@ async function rpa(data_code) {
setTimeout(() => { setTimeout(() => {
windowNew.setAlwaysOnTop(false); windowNew.setAlwaysOnTop(false);
}, 1000); }, 1000);
const notification = new Notification({ const notification = new Notification({
title: 'Atención - Poliedro', title: 'Atención - Poliedro',
body: 'Complete el proceso manualmente. La ventana está habilitada.', body: 'Complete el proceso manualmente. La ventana está habilitada.',
@@ -1920,7 +1479,7 @@ async function rpa(data_code) {
}); });
notification.show(); notification.show();
} }
return; return;
} else { } else {
const checkAndClose = async (message, text, xpath) => { const checkAndClose = async (message, text, xpath) => {
@@ -1936,11 +1495,10 @@ async function rpa(data_code) {
if (elementHandles && elementHandles.length > 0) { if (elementHandles && elementHandles.length > 0) {
if (data_code == 'VIM059' && elementHandles.length <= 2) { if (data_code == 'VIM059' && elementHandles.length <= 2) {
// No hace nada para VIM059 con 2 elementos o menos // No hace nada para VIM059 con 2 elementos o menos
} else if (data_code == 'DIM072' && elementHandles.length <= 1) { } else if (data_code == 'DIM072') {
// No hace nada para DIM072 con 1 elemento o menos // DIM072 will now follow general error handling.
} else if (data_code == '') { } else if (data_code == 'TUN065') {
// No hacer nada para TUN065 - permitir que continúe normalmente // TUN065 will now follow general error handling.
console.log(`>> IDV033: Se encontró texto "${text}" pero se permite continuar`);
} else if (data_code == 'ASC069') { } else if (data_code == 'ASC069') {
// No hace nada para ASC069 // No hace nada para ASC069
console.log(`>> ASC069: Se encontró texto "${text}" pero se permite continuar`); console.log(`>> ASC069: Se encontró texto "${text}" pero se permite continuar`);
@@ -1964,7 +1522,7 @@ async function rpa(data_code) {
await checkAndClose('Could not log', 'could not log', false) || await checkAndClose('Could not log', 'could not log', false) ||
await checkAndClose('Form', xpath_username, true); await checkAndClose('Form', xpath_username, true);
} }
}
windowNew.setIgnoreMouseEvents(false); windowNew.setIgnoreMouseEvents(false);
// windowNew.setOpacity(1); // windowNew.setOpacity(1);
// windowNew.maximize(); // windowNew.maximize();
+2101
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,13 +1,13 @@
{ {
"name": "rpa-claro", "name": "rpa-claro",
"productName": "RpaClaro", "productName": "RpaClaro",
"version": "4.1.5", "version": "4.1.6",
"description": "RPA Claro", "description": "RPA Claro",
"author": "TARS", "author": "TARS",
"license": "MIT", "license": "MIT",
"main": "entry.js", "main": "entry2.js",
"scripts": { "scripts": {
"start": "electron . --user='46286506' --dev --log --code=POL911", "start": "electron . --user='45957768' --dev --log --code=TYD075",
"postinstall": "electron-builder install-app-deps", "postinstall": "electron-builder install-app-deps",
"pack": "electron-builder --dir", "pack": "electron-builder --dir",
"build": "electron-builder --win && node copy-deps.js", "build": "electron-builder --win && node copy-deps.js",