feat: implement RPA scripts for automated expense entry in SIGA with human-like mouse simulation

This commit is contained in:
2026-08-09 17:41:45 -04:00
parent 43d37f0f0a
commit 735703a600
2 changed files with 824 additions and 0 deletions

272
banco_despesas_rpa.py Normal file
View 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())