refactor: improve reliability of UI interactions with robust datepicker month-nav, AJAX Select2 normalization, and fallback fill logic

This commit is contained in:
2026-08-09 22:06:50 -04:00
parent 2fcbdcb4db
commit e74eaaaf50

View File

@@ -431,22 +431,26 @@ class SigaDespesasAutomation:
mouse = self.mouse mouse = self.mouse
logger.info(f"📅 Verificando Mês de Trabalho (Alvo: {target_month_str})...") 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(): await month_dropdown.wait_for(state="visible", timeout=15000)
current_text = await month_dropdown.inner_text() current_text = await month_dropdown.inner_text()
if target_month_str in current_text: if target_month_str in current_text:
logger.info(f"✅ Mês de trabalho já está em {target_month_str}.") logger.info(f"✅ Mês de trabalho já está ajustado para {target_month_str}.")
return return
logger.info(f"🔄 Alterando Mês de Trabalho (Atual: '{current_text.strip()}') para '{target_month_str}'...")
await mouse.click_element(month_dropdown) await mouse.click_element(month_dropdown)
await human_delay(500, 900) await human_delay(600, 1200)
month_option = page.get_by_role("link", name=f"Mês de Trabalho {target_month_str}") # Seleciona a opção exata a.f_competencia_master com a competência alvo (ex: 07/2026)
if await month_option.is_visible(): 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 mouse.click_element(month_option)
await page.wait_for_load_state("networkidle", timeout=10000)
await human_delay(1500, 2500) await human_delay(1500, 2500)
logger.info(f"✅ Mês de trabalho alterado para {target_month_str}.") logger.info(f"✅ Mês de trabalho alterado com sucesso para {target_month_str}.")
async def navigate_to_caixas_e_bancos(self): async def navigate_to_caixas_e_bancos(self):
"""Navega pelo menu lateral: Tesouraria >> Caixas e Bancos.""" """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): async def _select_date_in_datepicker(self, input_locator, target_date: date):
""" """
Interage com o Datepicker Bootstrap do SIGA: 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. e clica na célula td.day referente ao dia.
""" """
page = self.page page = self.page
mouse = self.mouse 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 input_locator.scroll_into_view_if_needed()
await mouse.click_element(input_locator) await mouse.click_element(input_locator)
await human_delay(400, 800) await human_delay(400, 800)
dp = page.locator(".datepicker-days").first dp = page.locator(".datepicker-days, .datepicker").first
try: try:
await dp.wait_for(state="visible", timeout=5000) await dp.wait_for(state="visible", timeout=4000)
except PlaywrightTimeout: except PlaywrightTimeout:
logger.warning("⚠️ Popover do Datepicker não visível, tentando clicar novamente...") logger.warning("⚠️ Popover do Datepicker não visível no primeiro clique, tentando novamente...")
await mouse.click_element(input_locator) await input_locator.click()
await dp.wait_for(state="visible", timeout=5000)
# 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) await human_delay(400, 800)
await dp.wait_for(state="visible", timeout=4000)
# 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) # 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() count = await cells.count()
day_str = str(target_date.day) day_str = str(target_date.day)
for i in range(count): for i in range(count):
cell = cells.nth(i) cell = cells.nth(i)
if (await cell.inner_text()).strip() == day_str: if (await cell.inner_text()).strip() == day_str:
await mouse.click_element(cell) try:
logger.info(f"📅 Data selecionada: {target_date.strftime('%d/%m/%Y')}") await cell.click(timeout=3000)
logger.info(f"📅 Data selecionada no datepicker: {target_date.strftime('%d/%m/%Y')}")
await human_delay(400, 700) await human_delay(400, 700)
return 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( async def _select_select2_option(
self, self,
@@ -548,24 +574,24 @@ class SigaDespesasAutomation:
mouse = self.mouse mouse = self.mouse
container = page.locator(container_selector).first container = page.locator(container_selector).first
await container.scroll_into_view_if_needed() await mouse.click_element(container)
choice_link = container.locator("a.select2-choice").first
await mouse.click_element(choice_link)
await human_delay(400, 800) await human_delay(400, 800)
search_input = page.locator("#select2-drop .select2-input").first search_input = page.locator("#select2-drop .select2-input").first
await search_input.wait_for(state="visible", timeout=5000) 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: 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 page.keyboard.press("Enter")
await human_delay(1500, 2500) await human_delay(1500, 2500)
else: else:
await human_delay(500, 1000) 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") results = page.locator("#select2-drop .select2-results li")
count = await results.count() count = await results.count()
target_norm = normalize_text(target_option_text) target_norm = normalize_text(target_option_text)
@@ -573,14 +599,15 @@ class SigaDespesasAutomation:
for i in range(count): for i in range(count):
item = results.nth(i) item = results.nth(i)
item_text = await item.inner_text() 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) 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) await human_delay(400, 800)
return return
# Fallback: pressiona Enter se o primeiro item for o desejado # Fallback: pressiona Enter se o primeiro item resultante for o desejado
logger.warning(f"⚠️ Seleção exata por texto não casou, tentando confirmar via Enter...") 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 page.keyboard.press("Enter")
await human_delay(500, 900) await human_delay(500, 900)
@@ -601,11 +628,11 @@ class SigaDespesasAutomation:
data_doc_input = page.locator("#f_data").first data_doc_input = page.locator("#f_data").first
await self._select_date_in_datepicker(data_doc_input, expense.data_documento) 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}'...") logger.info(f"2️⃣ Selecionando Tipo Documento: '{expense.tipo_documento}'...")
await self._select_select2_option( await self._select_select2_option(
container_selector="#s2id_f_id_tipo_documento, #s2id_f_tipo_documento", 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, 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 # B. Preenche todos os campos da despesa a partir do registro do CSV
await automation.process_expense(rec) await automation.process_expense(rec)
# C. Clica em Salvar (redireciona para TES01701.aspx ao finalizar) # C. Clica em Salvar (Modo Simulação: MANTIDO click_save=False para NUNCA submeter em produção)
await automation.save_form(click_save=True) await automation.save_form(click_save=False)
success_count += 1 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}") logger.info(f"🎉 [{idx}/{total_records}] SUCESSO: Data {rec.data_documento.strftime('%d/%m/%Y')} | Doc {rec.numero_documento} | R$ {rec.valor_documento:.2f}")