801 lines
35 KiB
Python
801 lines
35 KiB
Python
# -*- 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):
|
||
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"📝 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
|
||
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 (Rateio): '{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 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) ao final do formulário e aguarda o redirecionamento 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)
|
||
|
||
# Aguarda o processamento e o redirecionamento de volta para a lista de Caixas e Bancos
|
||
await page.wait_for_url("**/TES01701.aspx**", timeout=20000)
|
||
await human_delay(1500, 2500)
|
||
logger.info("✅ Lançamento de despesa salvo no SIGA! Redirecionado para a lista de Caixas e Bancos.")
|
||
else:
|
||
logger.info("ℹ️ Modo de simulação: formulário preenchido sem submeter (Salvar não clicado).")
|
||
|
||
|
||
# ==============================================================================
|
||
# 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 (redireciona para TES01701.aspx ao finalizar)
|
||
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"❌ [{idx}/{total_records}] ERRO ao lançar registro (Doc {rec.numero_documento}): {item_err}", exc_info=True)
|
||
|
||
# Tenta retornar para a lista de Caixas e Bancos para não travar os próximos lançamentos
|
||
try:
|
||
await automation.navigate_to_caixas_e_bancos()
|
||
except Exception:
|
||
pass
|
||
|
||
logger.info("\n" + "🏁 " * 15)
|
||
logger.info(" PROCESSAMENTO EM LOTE CONCLUÍDO COM SUCESSO!")
|
||
logger.info(f" Total Solicitado: {total_records}")
|
||
logger.info(f" Sucessos: {success_count}")
|
||
logger.info(f" Falhas: {failed_count}")
|
||
logger.info("🏁 " * 15 + "\n")
|
||
|
||
await asyncio.sleep(5)
|
||
|
||
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())
|