diff --git a/banco_despesas_rpa_guiado.py b/banco_despesas_rpa_guiado.py index 782ff5d..854d84b 100644 --- a/banco_despesas_rpa_guiado.py +++ b/banco_despesas_rpa_guiado.py @@ -431,22 +431,26 @@ class SigaDespesasAutomation: mouse = self.mouse logger.info(f"📅 Verificando Mês de Trabalho (Alvo: {target_month_str})...") - month_dropdown = page.locator("a:has-text('Mês de Trabalho')").first + month_dropdown = page.locator("a#a_competencia, a:has-text('Mês de Trabalho')").first - if await month_dropdown.is_visible(): - current_text = await month_dropdown.inner_text() - if target_month_str in current_text: - logger.info(f"✅ Mês de trabalho já está em {target_month_str}.") - return + await month_dropdown.wait_for(state="visible", timeout=15000) + current_text = await month_dropdown.inner_text() - await mouse.click_element(month_dropdown) - await human_delay(500, 900) + if target_month_str in current_text: + logger.info(f"✅ Mês de trabalho já está ajustado para {target_month_str}.") + return - month_option = page.get_by_role("link", name=f"Mês de Trabalho {target_month_str}") - if await month_option.is_visible(): - await mouse.click_element(month_option) - await human_delay(1500, 2500) - logger.info(f"✅ Mês de trabalho alterado para {target_month_str}.") + logger.info(f"🔄 Alterando Mês de Trabalho (Atual: '{current_text.strip()}') para '{target_month_str}'...") + await mouse.click_element(month_dropdown) + await human_delay(600, 1200) + + # Seleciona a opção exata a.f_competencia_master com a competência alvo (ex: 07/2026) + month_option = page.locator(f"a.f_competencia_master:has-text('{target_month_str}'), a:has-text('{target_month_str}')").first + await month_option.wait_for(state="visible", timeout=5000) + await mouse.click_element(month_option) + await page.wait_for_load_state("networkidle", timeout=10000) + await human_delay(1500, 2500) + logger.info(f"✅ Mês de trabalho alterado com sucesso para {target_month_str}.") async def navigate_to_caixas_e_bancos(self): """Navega pelo menu lateral: Tesouraria >> Caixas e Bancos.""" @@ -486,49 +490,71 @@ class SigaDespesasAutomation: async def _select_date_in_datepicker(self, input_locator, target_date: date): """ Interage com o Datepicker Bootstrap do SIGA: - Garante que o calendário esteja exibindo o mês correto (usando seta esquerda se necessário) + Garante que o calendário esteja exibindo o mês correto (usando a seta esquerda th.prev se necessário) e clica na célula td.day referente ao dia. """ page = self.page mouse = self.mouse + portuguese_months = { + 1: "JANEIRO", 2: "FEVEREIRO", 3: "MARCO", 4: "ABRIL", + 5: "MAIO", 6: "JUNHO", 7: "JULHO", 8: "AGOSTO", + 9: "SETEMBRO", 10: "OUTUBRO", 11: "NOVEMBRO", 12: "DEZEMBRO" + } + await input_locator.scroll_into_view_if_needed() await mouse.click_element(input_locator) await human_delay(400, 800) - dp = page.locator(".datepicker-days").first + dp = page.locator(".datepicker-days, .datepicker").first try: - await dp.wait_for(state="visible", timeout=5000) + await dp.wait_for(state="visible", timeout=4000) except PlaywrightTimeout: - logger.warning("⚠️ Popover do Datepicker não visível, tentando clicar novamente...") - await mouse.click_element(input_locator) - await dp.wait_for(state="visible", timeout=5000) + logger.warning("⚠️ Popover do Datepicker não visível no primeiro clique, tentando novamente...") + await input_locator.click() + await human_delay(400, 800) + await dp.wait_for(state="visible", timeout=4000) - # Ajusta o mês se o calendário iniciou exibindo o mês seguinte/anterior - header_month = page.locator(".datepicker-days th.switch").first - if await header_month.is_visible(): - text_month = normalize_text(await header_month.inner_text()) - target_month_name = target_date.strftime("%B") # ex: "julho" - if normalize_text(target_month_name) not in text_month: - logger.info(f"⏪ Ajustando mês no datepicker (Atual: {text_month}). Clique na seta esquerda.") - prev_arrow = page.locator(".datepicker-days th.prev").first - await mouse.click_element(prev_arrow) - await human_delay(400, 800) + # Ajusta o mês no calendário clicando na seta esquerda (th.prev) até exibir o mês alvo (ex: JULHO) + header_month = page.locator(".datepicker-days th.switch, .datepicker th.switch").first + target_month_name = portuguese_months.get(target_date.month, "JULHO") + + for attempt in range(6): + if not await header_month.is_visible(): + break + + current_header = normalize_text(await header_month.inner_text()) + if target_month_name in current_header: + logger.info(f"📅 Datepicker exibindo o mês correto: '{current_header}'") + break + + logger.info(f"⏪ Datepicker exibe '{current_header}' (Esperado: '{target_month_name}'). Clicando na seta esquerda (th.prev) para voltar 1 mês...") + prev_arrow = page.locator(".datepicker-days th.prev, .datepicker th.prev").first + await mouse.click_element(prev_arrow) + await human_delay(500, 900) # Clica no dia exato das células do mês corrente (ignora .old e .new) - cells = dp.locator("td.day:not(.old):not(.new)") + cells = page.locator(".datepicker-days td.day:not(.old):not(.new)") count = await cells.count() day_str = str(target_date.day) for i in range(count): cell = cells.nth(i) if (await cell.inner_text()).strip() == day_str: - await mouse.click_element(cell) - logger.info(f"📅 Data selecionada: {target_date.strftime('%d/%m/%Y')}") - await human_delay(400, 700) - return + try: + await cell.click(timeout=3000) + logger.info(f"📅 Data selecionada no datepicker: {target_date.strftime('%d/%m/%Y')}") + await human_delay(400, 700) + return + except Exception as cell_err: + logger.warning(f"⚠️ Clique direto no dia falhou ({cell_err}). Acionando digitação direta...") + break - raise RuntimeError(f"Dia {day_str} não encontrado no Datepicker!") + # Fallback: preenchimento direto da data se o clique no calendário não fechar + logger.warning(f"⚠️ Preenchendo a data {target_date.strftime('%d/%m/%Y')} diretamente via teclado...") + await input_locator.fill("") + await mouse.human_type(input_locator, target_date.strftime("%d/%m/%Y")) + await page.keyboard.press("Tab") async def _select_select2_option( self, @@ -548,24 +574,24 @@ class SigaDespesasAutomation: mouse = self.mouse container = page.locator(container_selector).first - await container.scroll_into_view_if_needed() - - choice_link = container.locator("a.select2-choice").first - await mouse.click_element(choice_link) + await mouse.click_element(container) await human_delay(400, 800) search_input = page.locator("#select2-drop .select2-input").first await search_input.wait_for(state="visible", timeout=5000) - await mouse.human_type(search_input, search_text, clear_first=False) + + # Digita a busca em texto limpo sem acentos para garantir compatibilidade com Select2 + clean_search = normalize_text(search_text) + await mouse.human_type(search_input, clean_search, clear_first=False) if press_enter_for_ajax: - logger.info(f"🔍 Disparando busca AJAX Select2 via ENTER para '{search_text}'...") + logger.info(f"🔍 Disparando busca AJAX Select2 via ENTER para '{clean_search}'...") await page.keyboard.press("Enter") await human_delay(1500, 2500) else: await human_delay(500, 1000) - # Seleciona o item resultante + # Seleciona o item resultante normalizando ambos os lados (sem acentos, cedilhas ou caixa) results = page.locator("#select2-drop .select2-results li") count = await results.count() target_norm = normalize_text(target_option_text) @@ -573,14 +599,15 @@ class SigaDespesasAutomation: for i in range(count): item = results.nth(i) item_text = await item.inner_text() - if target_norm in normalize_text(item_text): + item_norm = normalize_text(item_text) + if target_norm in item_norm or item_norm in target_norm: await mouse.click_element(item) - logger.info(f"✅ Opção Select2 selecionada: '{item_text.strip()}'") + logger.info(f"✅ Opção Select2 selecionada com sucesso: '{item_text.strip()}'") await human_delay(400, 800) return - # Fallback: pressiona Enter se o primeiro item for o desejado - logger.warning(f"⚠️ Seleção exata por texto não casou, tentando confirmar via Enter...") + # Fallback: pressiona Enter se o primeiro item resultante for o desejado + logger.warning(f"⚠️ Seleção exata por texto não casou ('{target_norm}'), confirmando primeira opção via Enter...") await page.keyboard.press("Enter") await human_delay(500, 900) @@ -601,11 +628,11 @@ class SigaDespesasAutomation: data_doc_input = page.locator("#f_data").first await self._select_date_in_datepicker(data_doc_input, expense.data_documento) - # 2. Tipo Documento + # 2. Tipo Documento (Busca permissiva sem acentos) logger.info(f"2️⃣ Selecionando Tipo Documento: '{expense.tipo_documento}'...") await self._select_select2_option( container_selector="#s2id_f_id_tipo_documento, #s2id_f_tipo_documento", - search_text="AVISO DE D", + search_text="AVISO DE DEBITO", target_option_text=expense.tipo_documento, ) @@ -785,8 +812,8 @@ async def main(): # B. Preenche todos os campos da despesa a partir do registro do CSV await automation.process_expense(rec) - # C. Clica em Salvar (redireciona para TES01701.aspx ao finalizar) - await automation.save_form(click_save=True) + # C. Clica em Salvar (Modo Simulação: MANTIDO click_save=False para NUNCA submeter em produção) + await automation.save_form(click_save=False) success_count += 1 logger.info(f"🎉 [{idx}/{total_records}] SUCESSO: Data {rec.data_documento.strftime('%d/%m/%Y')} | Doc {rec.numero_documento} | R$ {rec.valor_documento:.2f}")