feat: add fail-fast mechanism with user inspection pause on critical launch errors
This commit is contained in:
@@ -710,6 +710,28 @@ class SigaDespesasAutomation:
|
||||
logger.info("ℹ️ Modo de simulação: formulário preenchido sem submeter (Salvar não clicado).")
|
||||
|
||||
|
||||
async def wait_for_user_or_timeout(timeout_seconds: int = 30):
|
||||
"""Pausa o encerramento do navegador por até timeout_seconds ou até o usuário pressionar ENTER."""
|
||||
print("\n" + "🛑 " * 15)
|
||||
print(" FALHA CRÍTICA DETECTADA NO LANÇAMENTO!")
|
||||
print(f" O navegador permanecerá aberto por até {timeout_seconds} segundos")
|
||||
print(" (ou até você pressionar a tecla ENTER no terminal) para inspeção.")
|
||||
print("🛑 " * 15 + "\n")
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
async def wait_key():
|
||||
try:
|
||||
await loop.run_in_executor(None, input, "Pressione ENTER no terminal para encerrar o navegador e abortar...")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(wait_key(), timeout=timeout_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
logger.info(f"⏳ Tempo limite de {timeout_seconds}s para inspeção concluído.")
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# ENTRYPOINT PRINCIPAL (FLUXO EM LOTE VIA CSV)
|
||||
# ==============================================================================
|
||||
@@ -752,6 +774,7 @@ async def main():
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
|
||||
|
||||
# 7. Loop de lançamentos em lote (Redirecionamento ao Salvar)
|
||||
for idx, rec in enumerate(records, start=1):
|
||||
logger.info(f"\n🔄 [{idx}/{total_records}] Iniciando lançamento do registro...")
|
||||
@@ -770,22 +793,22 @@ async def main():
|
||||
|
||||
except Exception as item_err:
|
||||
failed_count += 1
|
||||
logger.error(f"❌ [{idx}/{total_records}] ERRO ao lançar registro (Doc {rec.numero_documento}): {item_err}", exc_info=True)
|
||||
logger.error(f"\n❌ [{idx}/{total_records}] ERRO AO PROCESSAR REGISTRO (Doc {rec.numero_documento}, Data {rec.data_documento.strftime('%d/%m/%Y')}): {item_err}", exc_info=True)
|
||||
|
||||
# Tenta retornar para a lista de Caixas e Bancos para não travar os próximos lançamentos
|
||||
try:
|
||||
await automation.navigate_to_caixas_e_bancos()
|
||||
except Exception:
|
||||
pass
|
||||
# Pausa para inspeção visual no navegador (30s ou tecla ENTER no terminal)
|
||||
await wait_for_user_or_timeout(30)
|
||||
|
||||
logger.error("🛑 POLÍTICA FAIL-FAST: Execução do lote abortada imediatamente. Nenhum outro registro será processado.")
|
||||
break
|
||||
|
||||
logger.info("\n" + "🏁 " * 15)
|
||||
logger.info(" PROCESSAMENTO EM LOTE CONCLUÍDO COM SUCESSO!")
|
||||
logger.info(" PROCESSAMENTO EM LOTE FINALIZADO!")
|
||||
logger.info(f" Total Solicitado: {total_records}")
|
||||
logger.info(f" Sucessos: {success_count}")
|
||||
logger.info(f" Falhas: {failed_count}")
|
||||
logger.info("🏁 " * 15 + "\n")
|
||||
|
||||
await asyncio.sleep(5)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
finally:
|
||||
await automation.close()
|
||||
|
||||
Reference in New Issue
Block a user