diff --git a/banco_despesas_rpa_guiado.py b/banco_despesas_rpa_guiado.py index 61f680c..31fe679 100644 --- a/banco_despesas_rpa_guiado.py +++ b/banco_despesas_rpa_guiado.py @@ -324,8 +324,9 @@ class HumanMouse: await self.page.mouse.up(button=button) await asyncio.sleep(random.uniform(0.08, 0.25)) - async def click_element(self, locator, offset_x: float = 0, offset_y: float = 0): - await locator.scroll_into_view_if_needed() + async def click_element(self, locator, offset_x: float = 0, offset_y: float = 0, timeout: float = 5000): + await locator.wait_for(state="visible", timeout=timeout) + await locator.scroll_into_view_if_needed(timeout=timeout) box = await locator.bounding_box() if box is None: raise RuntimeError(f"Elemento não visível para clique: {locator}") @@ -351,6 +352,24 @@ class HumanMouse: else: await asyncio.sleep(random.uniform(0.04, 0.13)) + async def human_type2(self, locator, text: str, clear_first: bool = True): + if clear_first: + #await self.click_element2(locator) + await asyncio.sleep(random.uniform(0.1, 0.2)) + await self.page.keyboard.press("Control+a") + await asyncio.sleep(random.uniform(0.05, 0.1)) + await self.page.keyboard.press("Delete") + await asyncio.sleep(random.uniform(0.05, 0.15)) + + for i, char in enumerate(text): + await locator.type(char, delay=0) + if char == " ": + await asyncio.sleep(random.uniform(0.08, 0.18)) + elif i > 0 and random.random() < 0.04: + await asyncio.sleep(random.uniform(0.3, 0.7)) + else: + await asyncio.sleep(random.uniform(0.04, 0.13)) + async def human_delay(min_ms: int = 400, max_ms: int = 1000): await asyncio.sleep(random.uniform(min_ms, max_ms) / 1000) @@ -392,6 +411,9 @@ class SigaDespesasAutomation: self.page.set_default_timeout(Config.DEFAULT_TIMEOUT) self.mouse = HumanMouse(self.page) + # Handler para dialogs nativos de alert/confirm + self.page.on("dialog", lambda dialog: asyncio.create_task(dialog.accept())) + # Anti-bot: limpa flag webdriver await self.page.add_init_script( "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})" @@ -574,24 +596,35 @@ class SigaDespesasAutomation: mouse = self.mouse container = page.locator(container_selector).first + await human_delay(400, 800) try: choice_btn = container.locator("a.select2-choice").first - if await choice_btn.is_visible(timeout=2000): + logger.info("Select2: Verificando se o botão de escolha 'a.select2-choice' está visível...") + # is_visible() does not support timeout in standard Playwright, we do a quick check + if await choice_btn.is_visible(): + logger.info("Select2: Botão de escolha visível. Clicando...") await mouse.click_element(choice_btn) else: + logger.info("Select2: Botão de escolha não visível. Clicando no container principal...") await mouse.click_element(container) - except Exception: - # await mouse.click_element(container) - logger.warning("Clique nao foi possivel") + except Exception as e: + logger.warning(f"⚠️ Clique não foi possível no select2 choice/container: {e}") await human_delay(400, 800) - await human_delay(400, 800) + #await human_delay(400, 800) search_input = page.locator("#select2-drop input.select2-input").first - await search_input.wait_for(state="visible", timeout=5000) + logger.info("Select2: Aguardando campo de busca '#select2-drop input.select2-input' ficar visível (timeout 5s)...") + try: + await search_input.wait_for(state="visible", timeout=5000) + except PlaywrightTimeout as e: + logger.info("❌ Timeout: Campo de busca do select2 não ficou visível dentro de 5s.") + raise e # 2. Clica no campo de busca e preenche com fill + press ("Enter") se for AJAX ou seleciona da li clean_search = normalize_text(search_text) - await mouse.click_element(search_input) + logger.info("Select2: Clicando no campo de busca...") + #await mouse.click_element(search_input) + logger.info(f"Select2: Preenchendo campo de busca com '{clean_search}'...") await search_input.fill(clean_search) await search_input.dispatch_event("input") await human_delay(300, 600) @@ -607,14 +640,24 @@ class SigaDespesasAutomation: # 3. Localiza e clica no item da lista (#select2-drop .select2-results li) results = page.locator("#select2-drop .select2-results li.select2-result-selectable") + logger.info("Select2: Aguardando resultados da busca (timeout 5s)...") + try: + await results.first.wait_for(state="attached", timeout=5000) + except PlaywrightTimeout as e: + logger.info("❌ Timeout: Nenhum resultado select2-result-selectable ficou anexado ao DOM dentro de 5s.") + raise e + count = await results.count() + logger.info(f"Select2: Encontrados {count} itens de resultado.") target_norm = normalize_text(target_option_text) for i in range(count): item = results.nth(i) + logger.info(f"Select2: Obtendo texto do item {i+1}/{count}...") item_text = await item.inner_text() item_norm = normalize_text(item_text) if target_norm in item_norm or item_norm in target_norm: + logger.info(f"Select2: Item correspondente encontrado ('{item_text.strip()}'). Clicando...") await mouse.click_element(item) logger.info(f"✅ Opção Select2 selecionada com sucesso: '{item_text.strip()}'") await human_delay(400, 800) @@ -687,15 +730,20 @@ class SigaDespesasAutomation: ) # 7. Validação do Histórico (Rateio) - historico_rateio = page.locator("#s2id_f_id_historico_rateio, #s2id_f_historico_rateio").first - if await historico_rateio.is_visible(): - hist_text = await historico_rateio.inner_text() - logger.info(f"7️⃣ Validando Histórico de Rateio: '{hist_text.strip()}'") + logger.info(f"7️⃣ Validando Histórico...") + historico_select = page.locator("#f_historico_debito").first + if await historico_select.is_visible(): + selected_option = page.locator("#f_historico_debito option:selected").first + hist_text = await selected_option.text_content() or "" + if "12 - DESP.BANC" in hist_text: + logger.info(f"7️⃣ Histórico de Rateio Validado: '{hist_text.strip()}'") # 8. Complemento (Rateio) logger.info(f"8️⃣ Preenchendo Complemento (Rateio): '{expense.complemento}'...") complemento_input = page.locator("#f_complemento2").first - await mouse.human_type(complemento_input, expense.complemento) + await human_delay(300, 600) + await complemento_input.click() + await mouse.human_type2(complemento_input, expense.complemento) await human_delay(300, 600) # 9. Data Pagamento @@ -740,18 +788,44 @@ class SigaDespesasAutomation: logger.info("✨ Todos os campos da despesa foram preenchidos e validados com sucesso!") async def save_form(self, click_save: bool = True): - """Clica no botão 'Salvar' (button.btn-salvar) ao final do formulário e aguarda o redirecionamento para TES01701.aspx.""" + """Clica no botão 'Salvar' (button.btn-salvar), confirma os diálogos/modais ('Sim' e depois 'OK') e aguarda o retorno para TES01701.aspx.""" page = self.page if click_save: logger.info("💾 Clicando no botão 'Salvar' (button.btn-salvar)...") salvar_btn = page.locator("button.btn-salvar, button[data-comando='F']").first await salvar_btn.scroll_into_view_if_needed() await self.mouse.click_element(salvar_btn) - - # Aguarda o processamento e o redirecionamento de volta para a lista de Caixas e Bancos - await page.wait_for_url("**/TES01701.aspx**", timeout=20000) - await human_delay(1500, 2500) - logger.info("✅ Lançamento de despesa salvo no SIGA! Redirecionado para a lista de Caixas e Bancos.") + await human_delay(1000, 1500) + + # 1. Confirmação do modal ("Sim") + sim_btn = page.locator("button:has-text('Sim'), button.btn-primary:has-text('Sim'), button[data-bb-handler='confirm'], .modal-footer button:has-text('Sim')").first + try: + await sim_btn.wait_for(state="visible", timeout=6000) + logger.info("❓ Modal de confirmação detectada. Clicando em 'Sim'...") + await self.mouse.click_element(sim_btn) + await human_delay(1000, 1800) + except PlaywrightTimeout: + logger.info("ℹ️ Modal 'Sim' não foi solicitada ou fechou automaticamente.") + + # 2. Confirmação de mensagem de sucesso ("OK") + ok_btn = page.locator("button:has-text('OK'), button.btn-primary:has-text('OK'), button[data-bb-handler='ok'], .modal-footer button:has-text('OK')").first + try: + await ok_btn.wait_for(state="visible", timeout=6000) + logger.info("ℹ️ Modal de sucesso detectada. Clicando em 'OK'...") + await self.mouse.click_element(ok_btn) + await human_delay(1000, 1800) + except PlaywrightTimeout: + logger.info("ℹ️ Modal 'OK' não foi solicitada ou fechou automaticamente.") + + # 3. Aguarda o processamento e o redirecionamento de volta para a lista de Caixas e Bancos + try: + await page.wait_for_url("**/TES01701.aspx**", timeout=15000) + except PlaywrightTimeout: + logger.warning("⚠️ Redirecionamento automático para TES01701.aspx não ocorreu em 15s. Redirecionando manualmente...") + await self.navigate_to_caixas_e_bancos() + + await human_delay(1000, 1800) + logger.info("✅ Lançamento de despesa salvo no SIGA com sucesso! Retornado para a lista de Caixas e Bancos.") else: logger.info("ℹ️ Modo de simulação: formulário preenchido sem submeter (Salvar não clicado).")