574 lines
24 KiB
Python
574 lines
24 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
Banco Despesas RPA (Guiado) - Automação de Lançamento de Despesa no SIGA
|
||
========================================================================
|
||
Este script executa o fluxo completo de lançamento de Despesa em Caixas e Bancos no SIGA via Playwright.
|
||
|
||
Funcionalidades:
|
||
- Inicialização de navegador Chromium com perfil persistente e evasaõ de detecção anti-bot (HumanMouse).
|
||
- Autenticação e aguardo de login manual/reCAPTCHA.
|
||
- Seleção/validação do Mês de Trabalho (ex: 07/2026).
|
||
- Navegação via menu lateral: Tesouraria >> Caixas e Bancos >> + Novo >> Despesa (TES01702.aspx).
|
||
- Preenchimento inteligente dos campos:
|
||
* Data Documento (Datepicker Bootstrap td.day:not(.old):not(.new))
|
||
* Tipo Documento (Select2 com filtro tolerante a acentos)
|
||
* N° Documento (Documento e Pagamento)
|
||
* Valor Documento (Cálculo automático de rateio e total)
|
||
* Despesa (Select2 3030 - DESPESAS BANCARIAS)
|
||
* Fornecedor (Select2 AJAX com busca por 'BRADESCO' + Enter)
|
||
* Validação de Histórico (012 - DESP.BANCÁRIAS)
|
||
* Complemento (Rateio)
|
||
* Data Pagamento (Datepicker)
|
||
* Forma Pagamento (Select2 DÉBITO AUTOMÁTICO com auto-preenchimento de Conta)
|
||
"""
|
||
|
||
import asyncio
|
||
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
|
||
|
||
# ==============================================================================
|
||
# 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"
|
||
|
||
|
||
# ==============================================================================
|
||
# 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):
|
||
await locator.scroll_into_view_if_needed()
|
||
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 locator.click()
|
||
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"],
|
||
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)
|
||
|
||
# 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: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 mouse.click_element(month_dropdown)
|
||
await human_delay(500, 900)
|
||
|
||
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}.")
|
||
|
||
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 seta esquerda se necessário)
|
||
e clica na célula td.day referente ao dia.
|
||
"""
|
||
page = self.page
|
||
mouse = self.mouse
|
||
|
||
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
|
||
try:
|
||
await dp.wait_for(state="visible", timeout=5000)
|
||
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)
|
||
|
||
# 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)
|
||
|
||
# Clica no dia exato das células do mês corrente (ignora .old e .new)
|
||
cells = dp.locator("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
|
||
|
||
raise RuntimeError(f"Dia {day_str} não encontrado no Datepicker!")
|
||
|
||
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 container.scroll_into_view_if_needed()
|
||
|
||
choice_link = container.locator("a.select2-choice").first
|
||
await mouse.click_element(choice_link)
|
||
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)
|
||
|
||
if press_enter_for_ajax:
|
||
logger.info(f"🔍 Disparando busca AJAX Select2 via ENTER para '{search_text}'...")
|
||
await page.keyboard.press("Enter")
|
||
await human_delay(1500, 2500)
|
||
else:
|
||
await human_delay(500, 1000)
|
||
|
||
# Seleciona o item resultante
|
||
results = page.locator("#select2-drop .select2-results li")
|
||
count = await results.count()
|
||
target_norm = normalize_text(target_option_text)
|
||
|
||
for i in range(count):
|
||
item = results.nth(i)
|
||
item_text = await item.inner_text()
|
||
if target_norm in normalize_text(item_text):
|
||
await mouse.click_element(item)
|
||
logger.info(f"✅ Opção Select2 selecionada: '{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...")
|
||
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"📝 INICIANDO LANÇAMENTO DE DESPESA: 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
|
||
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",
|
||
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,
|
||
)
|
||
|
||
# 7. Validação do Histórico (Rateio)
|
||
historico_rateio = page.locator("#s2id_f_id_historico_rateio, #s2id_f_historico_rateio").first
|
||
if await historico_rateio.is_visible():
|
||
hist_text = await historico_rateio.inner_text()
|
||
logger.info(f"7️⃣ Validando Histórico de Rateio: '{hist_text.strip()}'")
|
||
|
||
# 8. Complemento (Rateio)
|
||
logger.info(f"8️⃣ Preenchendo Complemento: '{expense.complemento}'...")
|
||
complemento_input = page.locator("#f_complemento2").first
|
||
await mouse.human_type(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,
|
||
)
|
||
|
||
# 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 foram preenchidos e validados com sucesso!")
|
||
|
||
async def save_form(self, click_save: bool = True):
|
||
"""Clica no botão 'Salvar' (button.btn-salvar) ao final do formulário."""
|
||
if click_save:
|
||
logger.info("💾 Clicando no botão 'Salvar' (button.btn-salvar)...")
|
||
salvar_btn = self.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(2500, 4000)
|
||
logger.info("✅ Lançamento de despesa salvo no SIGA com sucesso!")
|
||
else:
|
||
logger.info("ℹ️ Modo de simulação: formulário preenchido sem submeter (Salvar não clicado).")
|
||
|
||
|
||
# ==============================================================================
|
||
# ENTRYPOINT PRINCIPAL
|
||
# ==============================================================================
|
||
async def main():
|
||
Config.load()
|
||
automation = SigaDespesasAutomation()
|
||
|
||
# Registro de exemplo baseado na sessão gravada
|
||
exemplo_despesa = ExpenseRecord(
|
||
data_documento=date(2026, 7, 1),
|
||
tipo_documento="AVISO DE DÉBITO",
|
||
numero_documento="1",
|
||
valor_documento=0.90,
|
||
codigo_despesa="3030",
|
||
fornecedor_busca="BRADESCO",
|
||
fornecedor_alvo="BANCO BRADESCO S.A",
|
||
complemento="TARIFA BANCARIA LIQUIDACAO QRCODE PIX",
|
||
data_pagamento=date(2026, 7, 1),
|
||
forma_pagamento="DÉBITO AUTOMÁTICO",
|
||
numero_doc_pagamento="1",
|
||
)
|
||
|
||
try:
|
||
await automation.launch()
|
||
await automation.navigate_and_wait_auth()
|
||
await automation.set_work_month("07/2026")
|
||
await automation.navigate_to_caixas_e_bancos()
|
||
await automation.open_novo_despesa()
|
||
|
||
await automation.process_expense(exemplo_despesa)
|
||
await automation.save_form(click_save=False)
|
||
|
||
logger.info("🎉 RPA concluído com sucesso!")
|
||
await asyncio.sleep(5)
|
||
|
||
except Exception as e:
|
||
logger.error(f"❌ Erro na execução do RPA: {e}", exc_info=True)
|
||
finally:
|
||
await automation.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
asyncio.run(main())
|