Compare commits
13 Commits
43d37f0f0a
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| fc90d776e7 | |||
| 4ef4220bc6 | |||
| 437d70ac1c | |||
| 4c8ea6dce8 | |||
| 39ac5340dc | |||
| cf12715727 | |||
| e74eaaaf50 | |||
| 2fcbdcb4db | |||
| 1750a08d9a | |||
| b9ef1178b5 | |||
| 712cbe5a2a | |||
| 3186bd5ee1 | |||
| 735703a600 |
15
Extrato_Bradesco_Julho_2026_v3.xlsx - despesas.csv
Normal file
15
Extrato_Bradesco_Julho_2026_v3.xlsx - despesas.csv
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
Data,Lançamento,Documento,Débito (R$)
|
||||||
|
08/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"0,90"
|
||||||
|
08/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,3,"3,08"
|
||||||
|
09/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,3,"3,45"
|
||||||
|
14/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"0,90"
|
||||||
|
15/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,3,"2,70"
|
||||||
|
15/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,9,"8,10"
|
||||||
|
16/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"1,19"
|
||||||
|
22/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,2,"1,80"
|
||||||
|
22/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,3,"2,70"
|
||||||
|
23/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,2,"1,80"
|
||||||
|
27/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"0,90"
|
||||||
|
28/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"0,90"
|
||||||
|
29/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,1,"0,90"
|
||||||
|
29/07/2026,TARIFA BANCARIA LIQUIDACAO QRCODE PIX,8,"7,56"
|
||||||
|
272
banco_despesas_rpa.py
Normal file
272
banco_despesas_rpa.py
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
SIGA RPA - Banco / Despesas
|
||||||
|
Automação de Lançamentos de Despesas no SIGA via Playwright.
|
||||||
|
|
||||||
|
Estratégia:
|
||||||
|
1. Inicia navegador e aguarda autenticação manual no SIGA.
|
||||||
|
2. Navega para Tesouraria >> Caixas e Bancos.
|
||||||
|
3. Clica em Novo >> Despesa.
|
||||||
|
4. Aguarda 30s para verificação e encerra o script sem realizar lançamentos.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from playwright.async_api import async_playwright, Page, TimeoutError as PlaywrightTimeout
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# CONFIGURAÇÃO
|
||||||
|
# ==============================================================================
|
||||||
|
class Config:
|
||||||
|
"""Centraliza configurações do RPA."""
|
||||||
|
|
||||||
|
SIGA_URL = "https://siga.congregacao.org.br/index.aspx"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(cls):
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# MÓDULO ANTI-BOT — Movimentos humanos de mouse
|
||||||
|
# ==============================================================================
|
||||||
|
class HumanMouse:
|
||||||
|
"""
|
||||||
|
Simula comportamento humano de mouse:
|
||||||
|
- Trajetória curva (Bézier quadrática)
|
||||||
|
- Microtremores (jitter)
|
||||||
|
- Velocidade variável (ease-in-out)
|
||||||
|
- Pausas aleatórias antes/depois do clique
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, page: Page):
|
||||||
|
self.page = page
|
||||||
|
self._x = 640.0
|
||||||
|
self._y = 400.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _ease_in_out(t: float) -> float:
|
||||||
|
return t * t * (3.0 - 2.0 * t)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _bezier(t: float, p0: tuple, p1: tuple, p2: tuple) -> tuple:
|
||||||
|
x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t ** 2 * p2[0]
|
||||||
|
y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t ** 2 * p2[1]
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _random_control_point(start: tuple, end: tuple) -> tuple:
|
||||||
|
mx = (start[0] + end[0]) / 2
|
||||||
|
my = (start[1] + end[1]) / 2
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1]) or 1
|
||||||
|
perp_x = -(end[1] - start[1]) / dist
|
||||||
|
perp_y = (end[0] - start[0]) / dist
|
||||||
|
offset = random.uniform(0.10, 0.30) * dist * random.choice([-1, 1])
|
||||||
|
return mx + perp_x * offset, my + perp_y * offset
|
||||||
|
|
||||||
|
async def move_to(self, x: float, y: float, steps: int = 0):
|
||||||
|
start = (self._x, self._y)
|
||||||
|
end = (x + random.uniform(-2, 2), y + random.uniform(-2, 2))
|
||||||
|
ctrl = self._random_control_point(start, end)
|
||||||
|
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1])
|
||||||
|
n = steps or max(8, int(dist / 12))
|
||||||
|
|
||||||
|
for i in range(1, n + 1):
|
||||||
|
t_raw = i / n
|
||||||
|
t = self._ease_in_out(t_raw)
|
||||||
|
px, py = self._bezier(t, start, ctrl, end)
|
||||||
|
|
||||||
|
jitter_scale = max(0.5, 2.5 * math.sin(math.pi * t_raw))
|
||||||
|
px += random.gauss(0, jitter_scale)
|
||||||
|
py += random.gauss(0, jitter_scale)
|
||||||
|
|
||||||
|
await self.page.mouse.move(px, py)
|
||||||
|
|
||||||
|
speed_factor = 0.4 + 0.6 * math.sin(math.pi * t_raw)
|
||||||
|
await asyncio.sleep(random.uniform(0.005, 0.022) / speed_factor)
|
||||||
|
|
||||||
|
self._x, self._y = end
|
||||||
|
|
||||||
|
async def click(self, x: float, y: float, button: str = "left"):
|
||||||
|
await self.move_to(x, y)
|
||||||
|
await asyncio.sleep(random.uniform(0.05, 0.18))
|
||||||
|
await self.page.mouse.down(button=button)
|
||||||
|
await asyncio.sleep(random.uniform(0.04, 0.12))
|
||||||
|
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()
|
||||||
|
box = await locator.bounding_box()
|
||||||
|
if box is None:
|
||||||
|
raise RuntimeError(f"Elemento sem bounding box visível: {locator}")
|
||||||
|
|
||||||
|
cx = box["x"] + box["width"] / 2 + offset_x + random.uniform(-3, 3)
|
||||||
|
cy = box["y"] + box["height"] / 2 + offset_y + random.uniform(-2, 2)
|
||||||
|
await self.click(cx, cy)
|
||||||
|
|
||||||
|
|
||||||
|
async def human_delay(min_ms: int = 300, max_ms: int = 900):
|
||||||
|
await asyncio.sleep(random.uniform(min_ms, max_ms) / 1000)
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# AUTOMAÇÃO SIGA
|
||||||
|
# ==============================================================================
|
||||||
|
class SigaAutomation:
|
||||||
|
"""Automação do sistema SIGA via Playwright."""
|
||||||
|
|
||||||
|
TIMEOUT = 30_000
|
||||||
|
AUTH_TIMEOUT = 3_600_000 # 1 hora
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.playwright = None
|
||||||
|
self.context = None
|
||||||
|
self.page: Optional[Page] = None
|
||||||
|
self.mouse: Optional[HumanMouse] = None
|
||||||
|
|
||||||
|
async def launch(self):
|
||||||
|
self.playwright = await async_playwright().start()
|
||||||
|
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
user_data_dir = os.path.join(project_root, "perfil_chromium")
|
||||||
|
|
||||||
|
self.context = await self.playwright.chromium.launch_persistent_context(
|
||||||
|
user_data_dir=user_data_dir,
|
||||||
|
headless=False,
|
||||||
|
user_agent=(
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||||
|
"Chrome/124.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
args=["--disable-blink-features=AutomationControlled"],
|
||||||
|
ignore_default_args=["--enable-automation"],
|
||||||
|
viewport={"width": 1366, "height": 768},
|
||||||
|
locale="pt-BR",
|
||||||
|
timezone_id="America/Cuiaba",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
|
||||||
|
self.page.set_default_timeout(self.TIMEOUT)
|
||||||
|
self.mouse = HumanMouse(self.page)
|
||||||
|
|
||||||
|
await self.page.add_init_script(
|
||||||
|
"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"🌐 Navegador iniciado com perfil: {user_data_dir}")
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.context:
|
||||||
|
await self.context.close()
|
||||||
|
if self.playwright:
|
||||||
|
await self.playwright.stop()
|
||||||
|
logger.info("🌐 Navegador fechado.")
|
||||||
|
|
||||||
|
# ---------- AUTENTICAÇÃO ----------
|
||||||
|
|
||||||
|
async def navigate_and_wait_auth(self):
|
||||||
|
page = self.page
|
||||||
|
await page.goto(Config.SIGA_URL)
|
||||||
|
logger.info("⏳ Aguardando login manual + reCAPTCHA...")
|
||||||
|
|
||||||
|
await page.locator(
|
||||||
|
"a:has-text('PRIMAVERA DO LESTE DL -'), "
|
||||||
|
"a:has-text('BR 09-0231 - PRIMAVERA DO')"
|
||||||
|
).first.wait_for(state="visible", timeout=self.AUTH_TIMEOUT)
|
||||||
|
|
||||||
|
logger.info("✅ Login detectado!")
|
||||||
|
await human_delay(800, 1500)
|
||||||
|
|
||||||
|
# ---------- NAVEGAÇÃO ----------
|
||||||
|
|
||||||
|
async def navigate_to_caixas_e_bancos(self):
|
||||||
|
"""Navega no menu lateral para Tesouraria >> Caixas e Bancos."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info("📂 Navegando para Tesouraria >> Caixas e Bancos...")
|
||||||
|
|
||||||
|
# Verifica se 'Caixas e Bancos' já está visível ou expande 'Tesouraria'
|
||||||
|
caixas_link = page.locator("a:has-text('Caixas e Bancos')").first
|
||||||
|
|
||||||
|
if not await caixas_link.is_visible():
|
||||||
|
tesouraria_menu = page.locator("a:has-text('Tesouraria')").first
|
||||||
|
if await tesouraria_menu.is_visible():
|
||||||
|
await mouse.click_element(tesouraria_menu)
|
||||||
|
await human_delay(500, 1000)
|
||||||
|
|
||||||
|
await caixas_link.wait_for(state="visible", timeout=15000)
|
||||||
|
await mouse.click_element(caixas_link)
|
||||||
|
await human_delay(1000, 2000)
|
||||||
|
logger.info("✅ Navegado com sucesso para Caixas e Bancos.")
|
||||||
|
|
||||||
|
async def open_nova_despesa(self):
|
||||||
|
"""Clica no botão Novo e depois seleciona Despesa."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info("➕ Clicando no botão Novo...")
|
||||||
|
novo_btn = page.locator("a:has-text('Novo'), button:has-text('Novo')").first
|
||||||
|
await novo_btn.wait_for(state="visible", timeout=15000)
|
||||||
|
await mouse.click_element(novo_btn)
|
||||||
|
await human_delay(600, 1200)
|
||||||
|
|
||||||
|
logger.info("📝 Selecionando a opção Despesa...")
|
||||||
|
despesa_option = page.locator("a:has-text('Despesa')").filter(has_text="Despesa").first
|
||||||
|
await despesa_option.wait_for(state="visible", timeout=10000)
|
||||||
|
await mouse.click_element(despesa_option)
|
||||||
|
await human_delay(1500, 2500)
|
||||||
|
logger.info("✅ Tela de Nova Despesa aberta com sucesso!")
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# APLICAÇÃO
|
||||||
|
# ==============================================================================
|
||||||
|
class Application:
|
||||||
|
def __init__(self):
|
||||||
|
Config.load()
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
logger.info(f"\n{'='*60}")
|
||||||
|
logger.info("🚀 INICIANDO RPA - DESPESAS BANCÁRIAS (SIGA)")
|
||||||
|
logger.info(f"{'='*60}\n")
|
||||||
|
|
||||||
|
siga = SigaAutomation()
|
||||||
|
try:
|
||||||
|
await siga.launch()
|
||||||
|
await siga.navigate_and_wait_auth()
|
||||||
|
await siga.navigate_to_caixas_e_bancos()
|
||||||
|
await siga.open_nova_despesa()
|
||||||
|
|
||||||
|
logger.info("⏳ Aguardando 30 segundos conforme solicitado antes de encerrar...")
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
logger.info("✅ Tempo concluído. Encerrando script.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.critical(f"💥 Erro crítico durante a execução: {e}")
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
await siga.close()
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# MAIN
|
||||||
|
# ==============================================================================
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(Application().run())
|
||||||
959
banco_despesas_rpa_guiado.py
Normal file
959
banco_despesas_rpa_guiado.py
Normal file
@@ -0,0 +1,959 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Banco Despesas RPA (Guiado) - Automação de Lançamento de Despesa no SIGA
|
||||||
|
========================================================================
|
||||||
|
Este script executa o fluxo completo e automatizado de lançamento em lote
|
||||||
|
de Despesas em Caixas e Bancos no SIGA via Playwright a partir de um arquivo CSV.
|
||||||
|
|
||||||
|
Funcionalidades:
|
||||||
|
- Leitura interativa de arquivo CSV (suporta separador vírgula ',' e ponto-e-vírgula ';').
|
||||||
|
- Resumo formatado dos registros no terminal com confirmação do usuário antes de iniciar.
|
||||||
|
- Inicialização de navegador Chromium com perfil persistente e evasaõ de detecção anti-bot (HumanMouse).
|
||||||
|
- Autenticação e aguardo de login manual/reCAPTCHA com orientação em tela.
|
||||||
|
- Seleção/validação do Mês de Trabalho (ex: 07/2026).
|
||||||
|
- Loop de lançamentos em lote:
|
||||||
|
* Navegação para Tesouraria >> Caixas e Bancos >> + Novo >> Despesa (TES01702.aspx).
|
||||||
|
* Preenchimento de Data Documento (Datepicker Bootstrap).
|
||||||
|
* Seleção de Tipo Documento ('AVISO DE DÉBITO').
|
||||||
|
* N° Documento e Valor Documento (Cálculo automático de rateio e total).
|
||||||
|
* Seleção de Despesa ('3030 - DESPESAS BANCARIAS').
|
||||||
|
* Pesquisa AJAX de Fornecedor ('BRADESCO' -> 'BANCO BRADESCO S.A').
|
||||||
|
* Preenchimento de Histórico e Complemento (Rateio e Pagamento).
|
||||||
|
* Seleção de Data Pagamento (Datepicker) e Forma Pagamento ('DÉBITO AUTOMÁTICO').
|
||||||
|
* Clique no botão Salvar (button.btn-salvar), redirecionando para a lista e reiniciando o loop para o próximo registro.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import csv
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import unicodedata
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, date
|
||||||
|
from typing import Optional, List
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from playwright.async_api import async_playwright, Page, TimeoutError as PlaywrightTimeout
|
||||||
|
|
||||||
|
import sys
|
||||||
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
if hasattr(sys.stderr, "reconfigure"):
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# LOGGING & CONFIGURAÇÃO
|
||||||
|
# ==============================================================================
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("BancoDespesasRPA")
|
||||||
|
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
"""Centraliza as configurações da automação."""
|
||||||
|
SIGA_URL = "https://siga.congregacao.org.br/index.aspx"
|
||||||
|
AUTH_TIMEOUT = 3_600_000 # 1 hora para login manual + reCAPTCHA
|
||||||
|
DEFAULT_TIMEOUT = 30_000 # 30 segundos para ações do Playwright
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(cls):
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# ESTRUTURA DE DADOS DA DESPESA (DTO)
|
||||||
|
# ==============================================================================
|
||||||
|
@dataclass
|
||||||
|
class ExpenseRecord:
|
||||||
|
data_documento: date # Ex: date(2026, 7, 1)
|
||||||
|
tipo_documento: str # Ex: "AVISO DE DÉBITO"
|
||||||
|
numero_documento: str # Ex: "1"
|
||||||
|
valor_documento: float # Ex: 0.90
|
||||||
|
codigo_despesa: str # Ex: "3030"
|
||||||
|
fornecedor_busca: str # Ex: "BRADESCO"
|
||||||
|
fornecedor_alvo: str # Ex: "BANCO BRADESCO S.A"
|
||||||
|
complemento: str # Ex: "TARIFA BANCARIA LIQUIDACAO QRCODE PIX"
|
||||||
|
data_pagamento: date # Ex: date(2026, 7, 1)
|
||||||
|
forma_pagamento: str # Ex: "DÉBITO AUTOMÁTICO"
|
||||||
|
numero_doc_pagamento: str # Ex: "1"
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# SERVICE DE LEITURA E PARSING DE CSV
|
||||||
|
# ==============================================================================
|
||||||
|
class CSVReaderService:
|
||||||
|
"""Lê e parseia arquivos CSV de extrato de despesas com suporte a ',' e ';'."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def detect_delimiter(filepath: str) -> str:
|
||||||
|
"""Identifica se o CSV utiliza vírgula (',') ou ponto-e-vírgula (';') como separador."""
|
||||||
|
with open(filepath, "r", encoding="utf-8-sig", errors="replace") as f:
|
||||||
|
first_line = f.readline()
|
||||||
|
if ";" in first_line:
|
||||||
|
return ";"
|
||||||
|
return ","
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_expenses_from_csv(cls, filepath: str) -> List[ExpenseRecord]:
|
||||||
|
if not os.path.exists(filepath):
|
||||||
|
raise FileNotFoundError(f"Arquivo CSV não encontrado no caminho: {filepath}")
|
||||||
|
|
||||||
|
delimiter = cls.detect_delimiter(filepath)
|
||||||
|
logger.info(f"📖 Lendo arquivo CSV com separador '{delimiter}': {filepath}")
|
||||||
|
|
||||||
|
records: List[ExpenseRecord] = []
|
||||||
|
|
||||||
|
with open(filepath, "r", encoding="utf-8-sig", errors="replace") as f:
|
||||||
|
reader = csv.DictReader(f, delimiter=delimiter)
|
||||||
|
|
||||||
|
for row_idx, row in enumerate(reader, start=2):
|
||||||
|
try:
|
||||||
|
# Mapeia chaves normalizadas (sem acentos e maiúsculas) para os valores correspondentes
|
||||||
|
norm_row = {}
|
||||||
|
for k, v in row.items():
|
||||||
|
if k is not None:
|
||||||
|
key_norm = normalize_text(str(k))
|
||||||
|
norm_row[key_norm] = str(v).strip().strip('"')
|
||||||
|
|
||||||
|
data_str = ""
|
||||||
|
lancamento = ""
|
||||||
|
documento = "1"
|
||||||
|
debito_str = ""
|
||||||
|
|
||||||
|
for k_norm, val in norm_row.items():
|
||||||
|
if "DATA" in k_norm:
|
||||||
|
data_str = val
|
||||||
|
elif "LANCAMENTO" in k_norm or "DESCRICAO" in k_norm or "HISTORICO" in k_norm:
|
||||||
|
lancamento = val
|
||||||
|
elif "DOCUMENTO" in k_norm or "DOC" in k_norm:
|
||||||
|
documento = val
|
||||||
|
elif "DEBITO" in k_norm or "VALOR" in k_norm:
|
||||||
|
debito_str = val
|
||||||
|
|
||||||
|
if not data_str or not debito_str:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Parse da Data (DD/MM/YYYY)
|
||||||
|
dt_obj = datetime.strptime(data_str, "%d/%m/%Y").date()
|
||||||
|
|
||||||
|
# Parse do Valor Monetário (ex: "0,90" ou "6,22" -> float)
|
||||||
|
clean_val_str = debito_str.replace("R$", "").replace(".", "").replace(",", ".").strip()
|
||||||
|
valor_float = abs(float(clean_val_str))
|
||||||
|
|
||||||
|
if valor_float <= 0:
|
||||||
|
continue
|
||||||
|
|
||||||
|
rec = ExpenseRecord(
|
||||||
|
data_documento=dt_obj,
|
||||||
|
tipo_documento="AVISO DE DÉBITO",
|
||||||
|
numero_documento=documento,
|
||||||
|
valor_documento=valor_float,
|
||||||
|
codigo_despesa="3030",
|
||||||
|
fornecedor_busca="BRADESCO",
|
||||||
|
fornecedor_alvo="BANCO BRADESCO S.A",
|
||||||
|
complemento=lancamento,
|
||||||
|
data_pagamento=dt_obj,
|
||||||
|
forma_pagamento="DÉBITO AUTOMÁTICO",
|
||||||
|
numero_doc_pagamento=documento,
|
||||||
|
)
|
||||||
|
records.append(rec)
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
logger.warning(f"⚠️ Linha {row_idx} ignorada devido a erro de parse: {row} | Erro: {err}")
|
||||||
|
|
||||||
|
logger.info(f"✅ total de {len(records)} registro(s) válido(s) carregado(s) do CSV.")
|
||||||
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# INTERACTION & CONFIRMATION HELPER (CLI)
|
||||||
|
# ==============================================================================
|
||||||
|
def get_csv_filepath() -> str:
|
||||||
|
"""Abre uma janela nativa do Windows (filedialog) para seleção do arquivo CSV.
|
||||||
|
Caso seja cancelado ou indisponível, cai para a seleção via terminal."""
|
||||||
|
default_csv = "Extrato_Bradesco_Julho_2026_v3.xlsx - despesas.csv"
|
||||||
|
print("\n" + "=" * 75)
|
||||||
|
print(" 📊 AUTOMAÇÃO DE DESPESAS SIGA - SELEÇÃO DE ARQUIVO CSV")
|
||||||
|
print("=" * 75)
|
||||||
|
|
||||||
|
# 1. Tenta abrir a janela nativa de escolha de arquivos do Windows
|
||||||
|
try:
|
||||||
|
import tkinter as tk
|
||||||
|
from tkinter import filedialog
|
||||||
|
|
||||||
|
logger.info("🗔 Abrindo janela do Windows para seleção do arquivo CSV...")
|
||||||
|
root = tk.Tk()
|
||||||
|
root.withdraw()
|
||||||
|
root.attributes("-topmost", True)
|
||||||
|
|
||||||
|
selected_file = filedialog.askopenfilename(
|
||||||
|
title="Selecione o arquivo CSV de Despesas para o SIGA",
|
||||||
|
filetypes=[("Arquivos CSV (*.csv)", "*.csv"), ("Todos os arquivos (*.*)", "*.*")],
|
||||||
|
initialdir=os.getcwd(),
|
||||||
|
)
|
||||||
|
root.destroy()
|
||||||
|
|
||||||
|
if selected_file and os.path.exists(selected_file):
|
||||||
|
print(f" Arquivo selecionado na janela: '{selected_file}'")
|
||||||
|
return selected_file
|
||||||
|
except Exception as gui_err:
|
||||||
|
logger.debug(f"Interface gráfica tkinter não iniciada: {gui_err}")
|
||||||
|
|
||||||
|
# 2. Fallback para prompt de terminal
|
||||||
|
if os.path.exists(default_csv):
|
||||||
|
print(f" Arquivo padrão detectado no diretório: '{default_csv}'")
|
||||||
|
|
||||||
|
user_input = input(f"\nDigite o caminho do arquivo .csv [Pressione ENTER para usar '{default_csv}']: ").strip().strip('"').strip("'")
|
||||||
|
|
||||||
|
if not user_input:
|
||||||
|
user_input = default_csv
|
||||||
|
|
||||||
|
if not os.path.exists(user_input):
|
||||||
|
raise FileNotFoundError(f"Arquivo CSV não encontrado no caminho: '{user_input}'")
|
||||||
|
|
||||||
|
return user_input
|
||||||
|
|
||||||
|
|
||||||
|
def print_records_preview(records: List[ExpenseRecord], filepath: str):
|
||||||
|
"""Exibe um resumo tabular formatado dos registros lidos do CSV."""
|
||||||
|
print("\n" + "=" * 75)
|
||||||
|
print(f" 📋 REGISTROS CARREGADOS DO ARQUIVO: {os.path.basename(filepath)} ({len(records)} itens)")
|
||||||
|
print("=" * 75)
|
||||||
|
print(f"{'#':<4} | {'Data':<10} | {'Doc':<8} | {'Valor (R$)':<12} | {'Complemento / Lançamento'}")
|
||||||
|
print("-" * 75)
|
||||||
|
|
||||||
|
total_val = 0.0
|
||||||
|
for idx, rec in enumerate(records, start=1):
|
||||||
|
total_val += rec.valor_documento
|
||||||
|
val_fmt = f"{rec.valor_documento:,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
||||||
|
comp_trunc = rec.complemento[:32] + "..." if len(rec.complemento) > 32 else rec.complemento
|
||||||
|
print(f"{idx:<4} | {rec.data_documento.strftime('%d/%m/%Y'):<10} | {rec.numero_documento:<8} | R$ {val_fmt:<9} | {comp_trunc}")
|
||||||
|
|
||||||
|
print("-" * 75)
|
||||||
|
total_val_fmt = f"{total_val:,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
||||||
|
print(f" TOTAL: {len(records)} registros | Soma dos Débitos: R$ {total_val_fmt}")
|
||||||
|
print("=" * 75)
|
||||||
|
|
||||||
|
|
||||||
|
def prompt_user_confirmation() -> bool:
|
||||||
|
"""Exibe aviso sobre login/senha no SIGA e solicita confirmação explícita."""
|
||||||
|
print("\n" + "⚠️ " * 15)
|
||||||
|
print(" INSTRUÇÃO IMPORTANTE DE AUTENTICAÇÃO NO SIGA:")
|
||||||
|
print(" Ao iniciar a automação, a janela do navegador Chromium será exibida.")
|
||||||
|
print(" Por favor, digite seu NOME DE USUÁRIO e SENHA no sistema SIGA")
|
||||||
|
print(" e resolva a verificação do reCAPTCHA ('Não sou um robô') se solicitado.")
|
||||||
|
print("⚠️ " * 15 + "\n")
|
||||||
|
|
||||||
|
confirm = input("Deseja iniciar o processamento em lote no SIGA agora? (S/n): ").strip().upper()
|
||||||
|
return confirm in ["S", "SIM", "Y", "YES", ""]
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# HELPER DE NORMALIZAÇÃO DE TEXTO
|
||||||
|
# ==============================================================================
|
||||||
|
def normalize_text(text: str) -> str:
|
||||||
|
"""Remove acentos e converte para maiúsculas para comparações permissivas."""
|
||||||
|
if not text:
|
||||||
|
return ""
|
||||||
|
nfkd = unicodedata.normalize("NFKD", text)
|
||||||
|
unaccented = "".join([c for c in nfkd if not unicodedata.combining(c)])
|
||||||
|
return unaccented.strip().upper()
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# MÓDULO ANTI-BOT — MOVIMENTOS HUMANOS DE MOUSE E TECLADO
|
||||||
|
# ==============================================================================
|
||||||
|
class HumanMouse:
|
||||||
|
"""Simula comportamento humano com curva de Bézier, jitter e delays imperfeitos."""
|
||||||
|
|
||||||
|
def __init__(self, page: Page):
|
||||||
|
self.page = page
|
||||||
|
self._x = 640.0
|
||||||
|
self._y = 400.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _ease_in_out(t: float) -> float:
|
||||||
|
return t * t * (3.0 - 2.0 * t)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _bezier(t: float, p0: tuple, p1: tuple, p2: tuple) -> tuple:
|
||||||
|
x = (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t ** 2 * p2[0]
|
||||||
|
y = (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t ** 2 * p2[1]
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _random_control_point(start: tuple, end: tuple) -> tuple:
|
||||||
|
mx = (start[0] + end[0]) / 2
|
||||||
|
my = (start[1] + end[1]) / 2
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1]) or 1
|
||||||
|
perp_x = -(end[1] - start[1]) / dist
|
||||||
|
perp_y = (end[0] - start[0]) / dist
|
||||||
|
offset = random.uniform(0.10, 0.30) * dist * random.choice([-1, 1])
|
||||||
|
return mx + perp_x * offset, my + perp_y * offset
|
||||||
|
|
||||||
|
async def move_to(self, x: float, y: float, steps: int = 0):
|
||||||
|
start = (self._x, self._y)
|
||||||
|
end = (x + random.uniform(-2, 2), y + random.uniform(-2, 2))
|
||||||
|
ctrl = self._random_control_point(start, end)
|
||||||
|
dist = math.hypot(end[0] - start[0], end[1] - start[1])
|
||||||
|
n = steps or max(8, int(dist / 12))
|
||||||
|
|
||||||
|
for i in range(1, n + 1):
|
||||||
|
t_raw = i / n
|
||||||
|
t = self._ease_in_out(t_raw)
|
||||||
|
px, py = self._bezier(t, start, ctrl, end)
|
||||||
|
jitter_scale = max(0.5, 2.5 * math.sin(math.pi * t_raw))
|
||||||
|
px += random.gauss(0, jitter_scale)
|
||||||
|
py += random.gauss(0, jitter_scale)
|
||||||
|
|
||||||
|
await self.page.mouse.move(px, py)
|
||||||
|
speed_factor = 0.4 + 0.6 * math.sin(math.pi * t_raw)
|
||||||
|
await asyncio.sleep(random.uniform(0.005, 0.022) / speed_factor)
|
||||||
|
|
||||||
|
self._x, self._y = end
|
||||||
|
|
||||||
|
async def click(self, x: float, y: float, button: str = "left"):
|
||||||
|
await self.move_to(x, y)
|
||||||
|
await asyncio.sleep(random.uniform(0.05, 0.18))
|
||||||
|
await self.page.mouse.down(button=button)
|
||||||
|
await asyncio.sleep(random.uniform(0.04, 0.12))
|
||||||
|
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, 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}")
|
||||||
|
cx = box["x"] + box["width"] / 2 + offset_x + random.uniform(-3, 3)
|
||||||
|
cy = box["y"] + box["height"] / 2 + offset_y + random.uniform(-2, 2)
|
||||||
|
await self.click(cx, cy)
|
||||||
|
|
||||||
|
async def human_type(self, locator, text: str, clear_first: bool = True):
|
||||||
|
if clear_first:
|
||||||
|
await self.click_element(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_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)
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# AUTOMAÇÃO DE BANCO E DESPESAS (SIGA)
|
||||||
|
# ==============================================================================
|
||||||
|
class SigaDespesasAutomation:
|
||||||
|
"""Gerencia a navegação e o preenchimento guiado do formulário de Despesa no SIGA."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.playwright = None
|
||||||
|
self.context = None
|
||||||
|
self.page: Optional[Page] = None
|
||||||
|
self.mouse: Optional[HumanMouse] = None
|
||||||
|
|
||||||
|
async def launch(self):
|
||||||
|
self.playwright = await async_playwright().start()
|
||||||
|
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
user_data_dir = os.path.join(project_root, "perfil_chromium")
|
||||||
|
|
||||||
|
self.context = await self.playwright.chromium.launch_persistent_context(
|
||||||
|
user_data_dir=user_data_dir,
|
||||||
|
headless=False,
|
||||||
|
user_agent=(
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||||
|
"Chrome/124.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
args=["--disable-blink-features=AutomationControlled", "--start-maximized"],
|
||||||
|
ignore_default_args=["--enable-automation"],
|
||||||
|
#viewport={"width": 1366, "height": 768},
|
||||||
|
locale="pt-BR",
|
||||||
|
timezone_id="America/Cuiaba",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.page = self.context.pages[0] if self.context.pages else await self.context.new_page()
|
||||||
|
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})"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"🌐 Navegador iniciado com perfil: {user_data_dir}")
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.context:
|
||||||
|
await self.context.close()
|
||||||
|
if self.playwright:
|
||||||
|
await self.playwright.stop()
|
||||||
|
logger.info("🌐 Navegador encerrado.")
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# 1. LOGIN E NAVEGAÇÃO INICIAL
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
async def navigate_and_wait_auth(self):
|
||||||
|
page = self.page
|
||||||
|
logger.info(f"🔗 Acessando URL: {Config.SIGA_URL}")
|
||||||
|
await page.goto(Config.SIGA_URL)
|
||||||
|
logger.info("⏳ Aguardando login manual do usuário e reCAPTCHA...")
|
||||||
|
|
||||||
|
# Aguarda indicador da sessão ativa na barra superior
|
||||||
|
await page.locator(
|
||||||
|
"a:has-text('PRIMAVERA DO LESTE DL -'), "
|
||||||
|
"a:has-text('BR 09-0231 - PRIMAVERA DO'), "
|
||||||
|
"a:has-text('Mês de Trabalho')"
|
||||||
|
).first.wait_for(state="visible", timeout=Config.AUTH_TIMEOUT)
|
||||||
|
|
||||||
|
logger.info("✅ Login detectado com sucesso!")
|
||||||
|
await human_delay(1000, 2000)
|
||||||
|
|
||||||
|
async def set_work_month(self, target_month_str: str = "07/2026"):
|
||||||
|
"""Garante que o Mês de Trabalho no menu superior seja o mês desejado."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info(f"📅 Verificando Mês de Trabalho (Alvo: {target_month_str})...")
|
||||||
|
month_dropdown = page.locator("a#a_competencia, a:has-text('Mês de Trabalho')").first
|
||||||
|
|
||||||
|
await month_dropdown.wait_for(state="visible", timeout=15000)
|
||||||
|
current_text = await month_dropdown.inner_text()
|
||||||
|
|
||||||
|
if target_month_str in current_text:
|
||||||
|
logger.info(f"✅ Mês de trabalho já está ajustado para {target_month_str}.")
|
||||||
|
return
|
||||||
|
|
||||||
|
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."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info("📂 Navegando para Tesouraria >> Caixas e Bancos...")
|
||||||
|
tesouraria_menu = page.locator("a:has-text('Tesouraria')").first
|
||||||
|
await mouse.click_element(tesouraria_menu)
|
||||||
|
await human_delay(500, 1000)
|
||||||
|
|
||||||
|
caixas_bancos_link = page.get_by_role("link", name="Caixas e Bancos").first
|
||||||
|
await mouse.click_element(caixas_bancos_link)
|
||||||
|
await human_delay(1200, 2000)
|
||||||
|
logger.info("✅ Página Caixas e Bancos carregada.")
|
||||||
|
|
||||||
|
async def open_novo_despesa(self):
|
||||||
|
"""Clica no botão '+ Novo' e seleciona a opção 'Despesa'."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info("➕ Clicando no botão '+ Novo' >> 'Despesa'...")
|
||||||
|
novo_btn = page.get_by_role("button", name=" Novo ").first
|
||||||
|
await mouse.click_element(novo_btn)
|
||||||
|
await human_delay(400, 800)
|
||||||
|
|
||||||
|
despesa_option = page.get_by_role("link", name="Despesa").first
|
||||||
|
await mouse.click_element(despesa_option)
|
||||||
|
await human_delay(1500, 2500)
|
||||||
|
|
||||||
|
await page.wait_for_url("**/TES01702.aspx**", timeout=15000)
|
||||||
|
logger.info("✅ Formulário de Despesa (TES01702.aspx) aberto.")
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# 2. HELPERS DE INTERAÇÃO COM COMPONENTES SIGA
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
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 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, .datepicker").first
|
||||||
|
try:
|
||||||
|
await dp.wait_for(state="visible", timeout=4000)
|
||||||
|
except PlaywrightTimeout:
|
||||||
|
logger.warning("⚠️ Popover do Datepicker não visível no primeiro clique, tentando novamente...")
|
||||||
|
await mouse.click_element(input_locator)
|
||||||
|
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)
|
||||||
|
# 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:
|
||||||
|
# try:
|
||||||
|
# await mouse.click_element(cell)
|
||||||
|
# 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
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
container_selector: str,
|
||||||
|
search_text: str,
|
||||||
|
target_option_text: str,
|
||||||
|
press_enter_for_ajax: bool = False,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Preenche dropdowns pesquisáveis baseados em Select2:
|
||||||
|
1. Clica na âncora a.select2-choice dentro do container especificado.
|
||||||
|
2. Digita o texto de pesquisa na caixa #select2-drop .select2-input.
|
||||||
|
3. Pressiona Enter se for busca AJAX (ex: Fornecedor).
|
||||||
|
4. Localiza e clica na opção correspondente de forma permissiva.
|
||||||
|
"""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
container = page.locator(container_selector).first
|
||||||
|
await human_delay(400, 800)
|
||||||
|
try:
|
||||||
|
choice_btn = container.locator("a.select2-choice").first
|
||||||
|
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 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)
|
||||||
|
|
||||||
|
search_input = page.locator("#select2-drop input.select2-input").first
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
|
||||||
|
if press_enter_for_ajax:
|
||||||
|
logger.info(f"🔍 Disparando busca AJAX Select2 via ENTER para '{clean_search}'...")
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
await human_delay(7500, 9500)
|
||||||
|
else:
|
||||||
|
await human_delay(400, 800)
|
||||||
|
|
||||||
|
#Jhony todo: Adicione a verificação se realmente o item clean_search foi encontrado com caracteres permissivos.
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
return
|
||||||
|
|
||||||
|
# # Fallback: se houver opção destacada ou primeira opção clicável
|
||||||
|
# logger.warning(f"⚠️ Seleção exata por texto não casou ('{target_norm}'), clicando na primeira opção visível...")
|
||||||
|
# first_opt = results.first
|
||||||
|
# if await first_opt.is_visible():
|
||||||
|
# await mouse.click_element(first_opt)
|
||||||
|
# else:
|
||||||
|
# await page.keyboard.press("Enter")
|
||||||
|
# await human_delay(500, 900)
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# 3. PREENCHIMENTO COMPLETO DO FORMULÁRIO DE DESPESA
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
async def process_expense(self, expense: ExpenseRecord):
|
||||||
|
"""Executa todos os passos de preenchimento gravados no formulário TES01702."""
|
||||||
|
page = self.page
|
||||||
|
mouse = self.mouse
|
||||||
|
|
||||||
|
logger.info("\n" + "=" * 60)
|
||||||
|
logger.info(f"📝 PREENCHENDO DESPESA: Data {expense.data_documento.strftime('%d/%m/%Y')} | N° {expense.numero_documento} | R$ {expense.valor_documento:.2f}")
|
||||||
|
logger.info("=" * 60)
|
||||||
|
|
||||||
|
# 1. Data Documento
|
||||||
|
logger.info("1️⃣ Preenchendo Data Documento...")
|
||||||
|
data_doc_input = page.locator("#f_data").first
|
||||||
|
await self._select_date_in_datepicker(data_doc_input, expense.data_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 DEBITO",
|
||||||
|
target_option_text=expense.tipo_documento,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. N° Documento (Dados do Documento)
|
||||||
|
logger.info(f"3️⃣ Preenchendo N° Documento: '{expense.numero_documento}'...")
|
||||||
|
num_doc_input = page.locator("#f_documento").first
|
||||||
|
await mouse.human_type(num_doc_input, expense.numero_documento)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
|
||||||
|
# 4. Valor Documento
|
||||||
|
valor_str = f"{expense.valor_documento:.2f}".replace(".", ",")
|
||||||
|
logger.info(f"4️⃣ Preenchendo Valor Documento: '{valor_str}'...")
|
||||||
|
valor_input = page.locator("#f_valor").first
|
||||||
|
await mouse.human_type(valor_input, valor_str)
|
||||||
|
await page.keyboard.press("Tab")
|
||||||
|
await human_delay(600, 1200)
|
||||||
|
|
||||||
|
# 5. Despesa (Rateio)
|
||||||
|
logger.info(f"5️⃣ Selecionando Despesa: '{expense.codigo_despesa}'...")
|
||||||
|
await self._select_select2_option(
|
||||||
|
container_selector="#s2id_f_id_despesa, #s2id_f_despesa",
|
||||||
|
search_text=expense.codigo_despesa,
|
||||||
|
target_option_text="3030 - DESPESAS BANCARIAS",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. Fornecedor (AJAX)
|
||||||
|
logger.info(f"6️⃣ Pesquisando e selecionando Fornecedor: '{expense.fornecedor_alvo}'...")
|
||||||
|
await self._select_select2_option(
|
||||||
|
container_selector="#s2id_f_id_fornecedor, #s2id_f_fornecedor",
|
||||||
|
search_text=expense.fornecedor_busca,
|
||||||
|
target_option_text=expense.fornecedor_alvo,
|
||||||
|
press_enter_for_ajax=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Faça com que seja apertado a tecla ESC
|
||||||
|
await page.keyboard.press("Escape", delay=400)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
await page.keyboard.press("Escape", delay=500)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
|
||||||
|
# 7. Validação do Histórico (Rateio)
|
||||||
|
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()}'")
|
||||||
|
|
||||||
|
# Faça com que seja apertado a tecla ESC
|
||||||
|
await page.keyboard.press("Escape", delay=400)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
await page.keyboard.press("Escape", delay=500)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
|
||||||
|
# 8. Complemento (Rateio)
|
||||||
|
logger.info(f"8️⃣ Preenchendo Complemento (Rateio): '{expense.complemento}'...")
|
||||||
|
complemento_input = page.locator("#f_complemento2").first
|
||||||
|
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
|
||||||
|
logger.info("9️⃣ Preenchendo Data Pagamento...")
|
||||||
|
data_pagamento_input = page.locator("#f_datapagamento").first
|
||||||
|
await self._select_date_in_datepicker(data_pagamento_input, expense.data_pagamento)
|
||||||
|
|
||||||
|
# 10. Forma Pagamento
|
||||||
|
logger.info(f"🔟 Selecionando Forma Pagamento: '{expense.forma_pagamento}'...")
|
||||||
|
await self._select_select2_option(
|
||||||
|
container_selector="#s2id_f_formapagamento, #s2id_f_id_forma_pagamento",
|
||||||
|
search_text="DEBITO AUTO",
|
||||||
|
target_option_text=expense.forma_pagamento,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Faça scroll to bottom
|
||||||
|
await page.mouse.wheel(0, 10000)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
|
||||||
|
# 10.1 Validação do Campo Conta (Auto-preenchido pelo SIGA ao escolher DÉBITO AUTOMÁTICO)
|
||||||
|
conta_field = page.locator("#s2id_f_conta .select2-chosen, #s2id_f_id_conta .select2-chosen").first
|
||||||
|
if await conta_field.is_visible():
|
||||||
|
conta_text = await conta_field.inner_text()
|
||||||
|
logger.info(f"🏦 Validando Campo Conta: '{conta_text.strip()}' (Esperado: 10130 - BRADESCO...)")
|
||||||
|
|
||||||
|
# 11. N° Documento (Pagamento)
|
||||||
|
logger.info(f"1️⃣1️⃣ Preenchendo N° Documento (Pagamento): '{expense.numero_doc_pagamento}'...")
|
||||||
|
num_doc_pag_input = page.locator("#f_documento2").first
|
||||||
|
await mouse.human_type(num_doc_pag_input, expense.numero_doc_pagamento)
|
||||||
|
await human_delay(300, 600)
|
||||||
|
|
||||||
|
# 12. Histórico (Pagamento)
|
||||||
|
logger.info("1️⃣2️⃣ Selecionando Histórico (Pagamento)...")
|
||||||
|
await self._select_select2_option(
|
||||||
|
container_selector="#s2id_f_historico",
|
||||||
|
search_text="012",
|
||||||
|
target_option_text="012 - DESP.BANCÁRIAS",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 13. Complemento (Pagamento)
|
||||||
|
logger.info(f"1️⃣3️⃣ Preenchendo Complemento (Pagamento): '{expense.complemento}'...")
|
||||||
|
complemento_pag_input = page.locator("#f_complemento").first
|
||||||
|
await mouse.human_type(complemento_pag_input, expense.complemento)
|
||||||
|
await human_delay(500, 1000)
|
||||||
|
|
||||||
|
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), 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)
|
||||||
|
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='botao'], .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).")
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
# ==============================================================================
|
||||||
|
async def main():
|
||||||
|
Config.load()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Solicita e lê o arquivo CSV
|
||||||
|
csv_file = get_csv_filepath()
|
||||||
|
records = CSVReaderService.load_expenses_from_csv(csv_file)
|
||||||
|
|
||||||
|
if not records:
|
||||||
|
logger.error("❌ Nenhum registro válido encontrado no CSV para processamento.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 2. Exibe a prévia no terminal
|
||||||
|
print_records_preview(records, csv_file)
|
||||||
|
|
||||||
|
# 3. Solicita confirmação explícita e orienta sobre login/senha
|
||||||
|
if not prompt_user_confirmation():
|
||||||
|
logger.info("🛑 Execução cancelada pelo usuário.")
|
||||||
|
return
|
||||||
|
|
||||||
|
automation = SigaDespesasAutomation()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 4. Inicia o navegador e aguarda login manual + reCAPTCHA
|
||||||
|
await automation.launch()
|
||||||
|
await automation.navigate_and_wait_auth()
|
||||||
|
|
||||||
|
# 5. Define o Mês de Trabalho com base na data do primeiro registro
|
||||||
|
first_date = records[0].data_documento
|
||||||
|
target_month_str = f"{first_date.month:02d}/{first_date.year}"
|
||||||
|
await automation.set_work_month(target_month_str)
|
||||||
|
|
||||||
|
# 6. Navega para a lista inicial de Caixas e Bancos (TES01701.aspx)
|
||||||
|
await automation.navigate_to_caixas_e_bancos()
|
||||||
|
|
||||||
|
total_records = len(records)
|
||||||
|
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...")
|
||||||
|
try:
|
||||||
|
# A. Clica em '+ Novo' >> 'Despesa' para abrir um formulário limpo (TES01702.aspx)
|
||||||
|
await automation.open_novo_despesa()
|
||||||
|
|
||||||
|
# B. Preenche todos os campos da despesa a partir do registro do CSV
|
||||||
|
await automation.process_expense(rec)
|
||||||
|
|
||||||
|
# C. Clica em Salvar (Modo Simulação: MANTIDO click_save=False para NUNCA submeter em produção)
|
||||||
|
await automation.save_form(click_save=True)
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
except Exception as item_err:
|
||||||
|
failed_count += 1
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 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 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(2)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await automation.close()
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.warning("\n🛑 Execução interrompida pelo usuário via terminal.")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Erro fatal na execução do RPA: {e}", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
Reference in New Issue
Block a user