Files
fundobiblico_rpa/fundo_biblico_rpa.py

830 lines
30 KiB
Python

# -- coding: utf-8 --
"""
Fundo Bíblico RPA - Automação de Lançamentos no SIGA
Lê vendas do Google Sheets, agrupa por dia+meio de pagamento,
e lança como SAÍDAs no sistema SIGA via Playwright.
Anti-bot: movimentos humanos de mouse, delays variáveis, jitter.
"""
import asyncio
import logging
import math
import os
import random
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, date, timedelta
from typing import List, Set, Optional
from dotenv import load_dotenv
import gspread
from google.oauth2.service_account import Credentials
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 e variáveis de ambiente."""
SIGA_URL = "https://siga.congregacao.org.br/index.aspx"
SPREADSHEET_ID = "1tuOfcMhiUa-VKT1COWtUV4QB6DgUOxzyOx-LJGIHH1A"
VENDAS_TAB = "Vendas"
LANCAMENTOS_TAB = "SIGA"
GOOGLE_CREDENTIALS_FILE: str = ""
SIGA_ORIGIN_CODE: str = "0231"
SIGA_DEST_CODE: str = "0231"
@classmethod
def load(cls):
load_dotenv()
cls.GOOGLE_CREDENTIALS_FILE = os.getenv("GOOGLE_CREDENTIALS_FILE", "credentials.json")
cls.SIGA_ORIGIN_CODE = os.getenv("SIGA_ORIGIN_CODE", "0231")
cls.SIGA_DEST_CODE = os.getenv("SIGA_DEST_CODE", "0231")
if not os.path.exists(cls.GOOGLE_CREDENTIALS_FILE):
raise FileNotFoundError(
f"Arquivo de credenciais não encontrado: {cls.GOOGLE_CREDENTIALS_FILE}\n"
"Configure GOOGLE_CREDENTIALS_FILE no .env"
)
# ==============================================================================
# DTOs
# ==============================================================================
@dataclass
class SaleItem:
id: int
data_venda: date
item_code: str
quantidade: int
valor_final: float
meio_pag: str
@dataclass
class AggregatedProduct:
code: str
total_qty: int
total_valor: float
sale_ids: List[int]
@dataclass
class SaleGroup:
data_venda: date
meio_pag: str
items: List[SaleItem] = field(default_factory=list)
@property
def total_valor(self) -> float:
return sum(i.valor_final for i in self.items)
@property
def all_ids(self) -> List[int]:
return [i.id for i in self.items]
def get_aggregated_products(self) -> List[AggregatedProduct]:
agg: dict[str, AggregatedProduct] = {}
for item in self.items:
if item.item_code not in agg:
agg[item.item_code] = AggregatedProduct(
code=item.item_code, total_qty=0, total_valor=0.0, sale_ids=[]
)
agg[item.item_code].total_qty += item.quantidade
agg[item.item_code].total_valor += item.valor_final
agg[item.item_code].sale_ids.append(item.id)
return list(agg.values())
# ==============================================================================
# UTILITÁRIOS
# ==============================================================================
def parse_date(date_val) -> Optional[date]:
if date_val is None:
return None
if isinstance(date_val, (int, float)):
return (datetime(1899, 12, 30) + timedelta(days=int(date_val))).date()
date_str = str(date_val).strip()
if not date_str:
return None
for fmt in (
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d",
"%d/%m/%Y",
"%m/%d/%Y",
"%d/%m/%Y %H:%M:%S",
"%m/%d/%Y %H:%M:%S",
):
try:
return datetime.strptime(date_str.split(".")[0], fmt).date()
except ValueError:
continue
return None
# ==============================================================================
# GOOGLE SHEETS SERVICE
# ==============================================================================
class GoogleSheetsService:
def __init__(self, credentials_file: str, spreadsheet_id: str):
scopes = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.readonly",
]
creds = Credentials.from_service_account_file(credentials_file, scopes=scopes)
gc = gspread.authorize(creds)
self.spreadsheet = gc.open_by_key(spreadsheet_id)
self.vendas_ws = self.spreadsheet.worksheet(Config.VENDAS_TAB)
self.lancamentos_ws = self.spreadsheet.worksheet(Config.LANCAMENTOS_TAB)
logger.info("✅ Conectado ao Google Sheets.")
def read_vendas(self, target_month: int, target_year: int) -> List[SaleItem]:
records = self.vendas_ws.get_all_records()
sales: List[SaleItem] = []
for rec in records:
try:
dt = parse_date(rec.get("DataVenda"))
if dt is None or dt.month != target_month or dt.year != target_year:
continue
sales.append(
SaleItem(
id=int(rec["ID"]),
data_venda=dt,
item_code=str(rec["Item"]).strip(),
quantidade=int(rec["Qtd"]),
valor_final=float(rec["ValorFinal"]),
meio_pag=str(rec["MeioPag"]).strip().upper(),
)
)
except Exception as e:
logger.warning(f"Erro ao parsear registro: {rec} → {e}")
logger.info(f"📊 {len(sales)} vendas do mês {target_month:02d}/{target_year}.")
return sales
def read_lancamentos(self) -> Set[int]:
records = self.lancamentos_ws.get_all_records()
launched = {
int(r["ID"])
for r in records
if str(r.get("LancadoSiga", "")).upper() == "SIM"
}
logger.info(f"📋 {len(launched)} IDs já lançados.")
return launched
def mark_as_launched(self, ids: List[int]):
timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
rows = [[id_val, "SIM", timestamp] for id_val in ids]
self.lancamentos_ws.append_rows(rows, value_input_option="USER_ENTERED")
logger.info(f"✅ Marcados como lançados: {ids}")
# ==============================================================================
# AGRUPAMENTO
# ==============================================================================
def group_sales(sales: List[SaleItem], launched_ids: Set[int]) -> List[SaleGroup]:
pending = [s for s in sales if s.id not in launched_ids]
if not pending:
logger.info("✅ Todas as vendas já foram lançadas!")
return []
logger.info(f"📦 {len(pending)} vendas pendentes.")
groups_dict: dict[tuple, list] = defaultdict(list)
for sale in pending:
groups_dict[(sale.data_venda, sale.meio_pag)].append(sale)
groups = [
SaleGroup(data_venda=k[0], meio_pag=k[1], items=v)
for k, v in sorted(groups_dict.items())
]
for g in groups:
prods = ", ".join(f"{p.code}x{p.total_qty}" for p in g.get_aggregated_products())
logger.info(f" 📅 {g.data_venda} | {g.meio_pag} | {prods} | R${g.total_valor:.2f}")
return groups
# ==============================================================================
# MÓDULO ANTI-BOT — Movimentos humanos de mouse
# ==============================================================================
class HumanMouse:
"""
Simula comportamento humano de mouse:
- Trajetória curva (Bézier quadrática) entre dois pontos
- Microtremores (jitter) ao longo do caminho
- Velocidade variável com aceleração/desaceleração (ease-in-out)
- Pausas aleatórias antes/depois do clique
"""
def __init__(self, page: Page):
self.page = page
# Posição corrente estimada (começa no centro da tela)
self._x = 640.0
self._y = 400.0
# ------------------------------------------------------------------
# Helpers internos
# ------------------------------------------------------------------
@staticmethod
def _ease_in_out(t: float) -> float:
"""Curva de aceleração suave: devagar → rápido → devagar."""
return t * t * (3.0 - 2.0 * t)
@staticmethod
def _bezier(t: float, p0: tuple, p1: tuple, p2: tuple) -> tuple:
"""Ponto na curva Bézier quadrática em t ∈ [0, 1]."""
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:
"""
Ponto de controle aleatório deslocado perpendicularmente
à linha start→end (entre 10 % e 30 % do comprimento).
"""
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
# ------------------------------------------------------------------
# API pública
# ------------------------------------------------------------------
async def move_to(self, x: float, y: float, steps: int = 0):
"""
Move o mouse da posição atual até (x, y) em trajetória curva.
steps=0 → calculado automaticamente pela distância.
"""
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 suave (microtremor)
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)
# Velocidade variável: mais devagar nas extremidades
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"):
"""Move até (x, y) e clica com pausa humana."""
await self.move_to(x, y)
await asyncio.sleep(random.uniform(0.05, 0.18)) # pausa pré-clique
await self.page.mouse.down(button=button)
await asyncio.sleep(random.uniform(0.04, 0.12)) # duração do clique
await self.page.mouse.up(button=button)
await asyncio.sleep(random.uniform(0.08, 0.25)) # pausa pós-clique
async def click_element(self, locator, offset_x: float = 0, offset_y: float = 0):
"""
Obtém o bounding box de um locator e clica no centro (com desvio opcional),
usando trajetória humana de mouse.
Faz scroll automático para o elemento ficar visível antes de clicar.
"""
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}")
# Clica numa área levemente aleatória dentro do elemento
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):
"""
Digita texto caractere a caractere com delay humano variável.
Inclui ocasionais micro-pausas como se a pessoa estivesse pensando.
"""
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)
# Delay entre teclas: mais rápido no meio das palavras
if char == " ":
await asyncio.sleep(random.uniform(0.08, 0.18))
elif i > 0 and random.random() < 0.04:
# 4 % de chance de pausa longa (distração)
await asyncio.sleep(random.uniform(0.3, 0.7))
else:
await asyncio.sleep(random.uniform(0.04, 0.13))
async def idle_wiggle(self, duration_ms: int = 500):
"""Mexe o mouse levemente durante uma espera (simula impaciência)."""
end_time = asyncio.get_event_loop().time() + duration_ms / 1000
while asyncio.get_event_loop().time() < end_time:
dx = random.uniform(-8, 8)
dy = random.uniform(-5, 5)
await self.move_to(self._x + dx, self._y + dy, steps=4)
await asyncio.sleep(random.uniform(0.08, 0.20))
async def human_delay(min_ms: int = 300, max_ms: int = 900):
"""Pausa aleatória entre ações (em milissegundos)."""
await asyncio.sleep(random.uniform(min_ms, max_ms) / 1000)
# ==============================================================================
# AUTOMAÇÃO SIGA
# ==============================================================================
class SigaAutomation:
"""Automação do sistema SIGA via Playwright com comportamento humano."""
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,
# Passa por checagens simples de user-agent
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"
),
# Remove a flag que identifica automação
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)
# Remove propriedade webdriver do navigator
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)
async def check_session(self):
try:
login_field = self.page.get_by_role("textbox", name="Email/Usuário:")
if await login_field.is_visible(timeout=2000):
logger.warning("⚠️ Sessão expirada! Aguardando re-login...")
await self.navigate_and_wait_auth()
await self.navigate_to_fundo_biblico()
await self.validate_and_enter_month()
except PlaywrightTimeout:
pass
# ---------- NAVEGAÇÃO ----------
async def navigate_to_fundo_biblico(self):
page = self.page
mouse = self.mouse
try:
locality_dropdown = page.locator(
'//*[@id="navbar-container"]/div[2]/ul/li[3]/a'
)
if await locality_dropdown.is_visible(timeout=5000):
await mouse.click_element(locality_dropdown)
await human_delay(600, 1200)
localidades_menu = page.locator(
'//*[@id="navbar-container"]/div[2]/ul/li[3]/ul/li[2]/a'
)
await mouse.click_element(localidades_menu)
await human_delay(400, 800)
target_locality = page.locator('//*[@id="5044"]/a')
if await target_locality.count() > 0:
await target_locality.first.evaluate("el => el.click()")
else:
fallback = page.locator(f'a:has-text("{Config.SIGA_DEST_CODE}")').last
if await fallback.count() > 0:
await fallback.evaluate("el => el.click()")
# Wiggle enquanto o SIGA recarrega
await mouse.idle_wiggle(3500)
except Exception as e:
logger.warning(f"⚠️ Erro ao tentar mudar localidade: {e}")
fundo_link = page.get_by_role("link", name="Fundo Bíblico", exact=False).first
await fundo_link.wait_for(state="attached", timeout=15000)
await mouse.click_element(fundo_link)
await human_delay(1000, 2000)
logger.info("📂 Navegou para Fundo Bíblico.")
async def validate_and_enter_month(self):
page = self.page
now = datetime.now()
month_text = f"Mês de Trabalho {now.month:02d}/{now.year}"
month_link = page.get_by_role("link", name=month_text)
try:
await month_link.wait_for(state="visible", timeout=10000)
await self.mouse.click_element(month_link)
await human_delay(1000, 2000)
logger.info(f"📅 Entrou no {month_text}")
except PlaywrightTimeout:
raise RuntimeError(
f"❌ '{month_text}' não encontrado! "
"Certifique-se de que o mês atual está criado no SIGA."
)
# ---------- LANÇAMENTO DE SAÍDA ----------
async def process_group(self, group: SaleGroup) -> List[int]:
page = self.page
mouse = self.mouse
products = group.get_aggregated_products()
logger.info(f"\n{'='*60}")
logger.info(f"📦 SAÍDA: {group.data_venda} | {group.meio_pag} | {len(products)} produto(s)")
logger.info(f"{'='*60}")
await self.check_session()
# 1. Novo → Saída
novo_btn = page.get_by_role("button", name=" Novo ")
await mouse.click_element(novo_btn)
await human_delay(700, 1300)
saida_link = page.get_by_role("link", name="Saída")
await mouse.click_element(saida_link)
await human_delay(1000, 1800)
# 2. Datepicker
await self._select_date(group.data_venda)
# Aguardar spinner
await human_delay(500, 1000)
try:
await page.locator("text=Aguarde...").wait_for(state="hidden", timeout=10000)
except PlaywrightTimeout:
pass
await human_delay(800, 1500)
# 3. Inserir produtos
successful_ids: List[int] = []
failed_products: List[AggregatedProduct] = []
for product in products:
ok = await self._add_product(product.code, product.total_qty)
if ok:
successful_ids.extend(product.sale_ids)
else:
failed_products.append(product)
if not successful_ids:
logger.error("❌ Todos produtos falharam! Cancelando SAÍDA...")
await self._cancel_saida()
return []
if failed_products:
logger.warning(f"⚠️ Produtos não encontrados: {[p.code for p in failed_products]}")
# 4. Pagamento
await self._fill_payment_value(group.meio_pag)
# 5. Confirmar
await self._confirm()
logger.info(f"✅ SAÍDA confirmada! IDs: {successful_ids}")
return successful_ids
# ---------- DATEPICKER ----------
async def _select_date(self, target: date):
"""
Aguarda o datepicker Bootstrap abrir e clica no dia desejado.
O mês exibido é sempre o mês de trabalho do SIGA — sem navegação.
Dias de meses adjacentes têm classe 'old' ou 'new' e são ignorados.
"""
page = self.page
mouse = self.mouse
# Aguarda o datepicker aparecer (o SIGA abre automaticamente)
dp = page.locator(".datepicker-days")
try:
await dp.wait_for(state="visible", timeout=5_000)
except PlaywrightTimeout:
# Fallback: tenta abrir clicando em algum input de data visível
logger.warning("⚠️ Datepicker não abriu automaticamente, tentando campo...")
input_data = page.locator(
"input.datepicker, input[name*='data'], input[id*='data']"
).first
try:
await mouse.click_element(input_data)
await human_delay(400, 700)
await dp.wait_for(state="visible", timeout=5_000)
except PlaywrightTimeout:
logger.warning("⚠️ Datepicker não encontrado, continuando sem selecionar data.")
return
# Aproxima o mouse do calendário antes de interagir (comportamento humano)
dp_box = await dp.bounding_box()
if dp_box:
await mouse.move_to(
dp_box["x"] + dp_box["width"] / 2,
dp_box["y"] - 20,
)
await human_delay(150, 350)
# Localiza todas as células do mês atual (sem .old e sem .new)
cells = dp.locator("td.day:not(.old):not(.new)")
count = await cells.count()
for i in range(count):
cell = cells.nth(i)
if (await cell.inner_text()).strip() == str(target.day):
await mouse.click_element(cell)
logger.info(f"📅 Data selecionada: {target.strftime('%d/%m/%Y')}")
return
raise RuntimeError(
f"Dia {target.day} não encontrado no datepicker "
f"({target.month:02d}/{target.year})."
)
# ---------- AÇÕES INTERNAS ----------
async def _add_product(self, code: str, qty: int) -> bool:
page = self.page
mouse = self.mouse
try:
# Abrir dropdown
select_btn = page.get_by_role("link", name="* Selecione * ")
await mouse.click_element(select_btn)
await human_delay(400, 700)
# Buscar produto
search = page.get_by_label("", exact=True)
await mouse.click_element(search)
await human_delay(150, 300)
await mouse.human_type(search, code, clear_first=False)
await asyncio.sleep(random.uniform(0.3, 0.6))
await page.keyboard.press("Enter")
await human_delay(1200, 2000)
# Selecionar produto
selected = await self._select_exact_product(code)
if not selected:
logger.warning(f" ❌ Produto '{code}' não encontrado no catálogo.")
await page.keyboard.press("Escape")
await human_delay(300, 600)
return False
await human_delay(400, 700)
# Quantidade
qty_field = page.locator("#f_quantidade")
await mouse.click_element(qty_field)
await mouse.human_type(qty_field, str(qty))
# Inserir
inserir_btn = page.locator("#btn-inserir-produto")
await mouse.click_element(inserir_btn)
await human_delay(1000, 1800)
logger.info(f" ✅ {code} x{qty} inserido.")
return True
except Exception as e:
logger.error(f" ❌ Erro ao inserir '{code}': {e}")
try:
await page.keyboard.press("Escape")
except Exception:
pass
return False
async def _select_exact_product(self, code: str) -> bool:
page = self.page
mouse = self.mouse
code_upper = code.strip().upper()
# Estratégia 1: texto exato
try:
exact = page.locator("#select2-drop").get_by_text(code, exact=True)
if await exact.count() > 0 and await exact.first.is_visible(timeout=2000):
await mouse.click_element(exact.first)
return True
except Exception:
pass
# Estratégia 2: texto que começa com o código
try:
results = page.locator("#select2-drop .select2-results li")
count = await results.count()
for i in range(count):
item = results.nth(i)
text = (await item.inner_text()).strip().upper()
if text.startswith(code_upper + " ") or text == code_upper:
await mouse.click_element(item)
return True
except Exception:
pass
# Estratégia 3: role option
try:
options = page.get_by_role("option")
count = await options.count()
for i in range(count):
opt = options.nth(i)
text = (await opt.inner_text()).strip().upper()
if text.startswith(code_upper):
await mouse.click_element(opt)
return True
except Exception:
pass
return False
async def _cancel_saida(self):
cancel = self.page.locator(
'button.btn.btn-link.no-border[data-dismiss="modal"]',
has_text="Cancelar",
)
await self.mouse.click_element(cancel)
await human_delay(1000, 2000)
logger.info("🚫 SAÍDA cancelada.")
async def _fill_payment_value(self, meio_pag: str):
page = self.page
mouse = self.mouse
try:
valor_produtos = await page.locator("#f_valorproduto").input_value()
except Exception:
valor_produtos = "0,00"
if not valor_produtos or valor_produtos.strip() == "":
valor_produtos = "0,00"
# Pausa humana antes de preencher pagamento
await human_delay(400, 900)
if meio_pag == "DINHEIRO":
field = page.locator("#f_valorcaixa")
await mouse.click_element(field)
await mouse.human_type(field, valor_produtos)
logger.info(f"💰 Dinheiro no Caixa: {valor_produtos}")
elif meio_pag == "PIX":
field = page.locator("#f_valorQrcodePix")
await mouse.click_element(field)
await mouse.human_type(field, valor_produtos)
logger.info(f"💰 PIX/QRCode: {valor_produtos}")
else:
field = page.locator("#f_valorcaixa")
await mouse.click_element(field)
await mouse.human_type(field, valor_produtos)
logger.info(f"💰 Fallback dinheiro: {valor_produtos}")
async def _confirm(self):
page = self.page
mouse = self.mouse
await human_delay(500, 1000)
confirmar = page.get_by_role("button", name=" Confirmar")
await mouse.click_element(confirmar)
await human_delay(1200, 2200)
ok_btn = page.get_by_role("button", name="Ok")
await ok_btn.wait_for(state="visible", timeout=10_000)
await mouse.click_element(ok_btn)
await human_delay(1000, 2000)
# ==============================================================================
# APLICAÇÃO
# ==============================================================================
class Application:
def __init__(self):
Config.load()
async def run(self):
now = datetime.now()
month, year = now.month, now.year
logger.info(f"\n{'='*60}")
logger.info(f"🚀 FUNDO BÍBLICO RPA")
logger.info(f"📅 Mês: {month:02d}/{year}")
logger.info(f"{'='*60}\n")
sheets = GoogleSheetsService(Config.GOOGLE_CREDENTIALS_FILE, Config.SPREADSHEET_ID)
vendas = sheets.read_vendas(month, year)
launched_ids = sheets.read_lancamentos()
groups = group_sales(vendas, launched_ids)
if not groups:
return
siga = SigaAutomation()
try:
await siga.launch()
await siga.navigate_and_wait_auth()
await siga.navigate_to_fundo_biblico()
await siga.validate_and_enter_month()
total_ok: List[int] = []
total_fail: List[int] = []
for i, group in enumerate(groups, 1):
logger.info(f"\n🔄 Grupo {i}/{len(groups)}")
ids_ok = await siga.process_group(group)
if ids_ok:
total_ok.extend(ids_ok)
sheets.mark_as_launched(ids_ok)
else:
total_fail.extend(group.all_ids)
logger.info(f"\n{'='*60}")
logger.info(f"📊 RESUMO FINAL")
logger.info(f" ✅ Lançados: {len(total_ok)} vendas")
logger.info(f" ❌ Falhas: {len(total_fail)} vendas")
if total_fail:
logger.info(f" IDs falhos: {total_fail}")
logger.info(f"{'='*60}")
except Exception as e:
logger.critical(f"💥 Erro crítico: {e}")
raise
finally:
await siga.close()
# ==============================================================================
# MAIN
# ==============================================================================
if __name__ == "__main__":
asyncio.run(Application().run())