Conseguiu entrar no formulario e datepicker
This commit is contained in:
@@ -3,10 +3,14 @@
|
||||
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
|
||||
@@ -59,7 +63,6 @@ class Config:
|
||||
# ==============================================================================
|
||||
@dataclass
|
||||
class SaleItem:
|
||||
"""Uma venda individual da planilha."""
|
||||
id: int
|
||||
data_venda: date
|
||||
item_code: str
|
||||
@@ -70,7 +73,6 @@ class SaleItem:
|
||||
|
||||
@dataclass
|
||||
class AggregatedProduct:
|
||||
"""Produto agregado (mesmo código) dentro de um grupo."""
|
||||
code: str
|
||||
total_qty: int
|
||||
total_valor: float
|
||||
@@ -79,7 +81,6 @@ class AggregatedProduct:
|
||||
|
||||
@dataclass
|
||||
class SaleGroup:
|
||||
"""Grupo de vendas agrupado por data + meio de pagamento."""
|
||||
data_venda: date
|
||||
meio_pag: str
|
||||
items: List[SaleItem] = field(default_factory=list)
|
||||
@@ -109,7 +110,6 @@ class SaleGroup:
|
||||
# UTILITÁRIOS
|
||||
# ==============================================================================
|
||||
def parse_date(date_val) -> Optional[date]:
|
||||
"""Converte diversos formatos de data do Google Sheets para date."""
|
||||
if date_val is None:
|
||||
return None
|
||||
if isinstance(date_val, (int, float)):
|
||||
@@ -138,8 +138,6 @@ def parse_date(date_val) -> Optional[date]:
|
||||
# GOOGLE SHEETS SERVICE
|
||||
# ==============================================================================
|
||||
class GoogleSheetsService:
|
||||
"""Leitura/escrita no Google Sheets via Service Account."""
|
||||
|
||||
def __init__(self, credentials_file: str, spreadsheet_id: str):
|
||||
scopes = [
|
||||
"https://www.googleapis.com/auth/spreadsheets",
|
||||
@@ -155,7 +153,6 @@ class GoogleSheetsService:
|
||||
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"))
|
||||
@@ -221,11 +218,157 @@ def group_sales(sales: List[SaleItem], launched_ids: Set[int]) -> List[SaleGroup
|
||||
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."""
|
||||
"""Automação do sistema SIGA via Playwright com comportamento humano."""
|
||||
|
||||
TIMEOUT = 30_000
|
||||
AUTH_TIMEOUT = 3_600_000 # 1 hora
|
||||
@@ -234,22 +377,39 @@ class SigaAutomation:
|
||||
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()
|
||||
|
||||
# Define o caminho do perfil apontando para ./perfil_chromium na raiz do projeto
|
||||
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
|
||||
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",
|
||||
)
|
||||
|
||||
# 'launch_persistent_context' já cria uma página por padrão
|
||||
|
||||
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):
|
||||
@@ -265,7 +425,6 @@ class SigaAutomation:
|
||||
page = self.page
|
||||
await page.goto(Config.SIGA_URL)
|
||||
logger.info("⏳ Aguardando login manual + reCAPTCHA...")
|
||||
logger.info(" → Faça login no navegador e resolva o captcha.")
|
||||
|
||||
await page.locator(
|
||||
"a:has-text('PRIMAVERA DO LESTE DL -'), "
|
||||
@@ -273,9 +432,9 @@ class SigaAutomation:
|
||||
).first.wait_for(state="visible", timeout=self.AUTH_TIMEOUT)
|
||||
|
||||
logger.info("✅ Login detectado!")
|
||||
await human_delay(800, 1500)
|
||||
|
||||
async def check_session(self):
|
||||
"""Se sessão expirou, aguarda re-login e re-navega."""
|
||||
try:
|
||||
login_field = self.page.get_by_role("textbox", name="Email/Usuário:")
|
||||
if await login_field.is_visible(timeout=2000):
|
||||
@@ -290,45 +449,40 @@ class SigaAutomation:
|
||||
|
||||
async def navigate_to_fundo_biblico(self):
|
||||
page = self.page
|
||||
mouse = self.mouse
|
||||
|
||||
try:
|
||||
# 1. Clicar no menu principal de localidade no topo
|
||||
locality_dropdown = page.locator('//*[@id="navbar-container"]/div[2]/ul/li[3]/a')
|
||||
locality_dropdown = page.locator(
|
||||
'//*[@id="navbar-container"]/div[2]/ul/li[3]/a'
|
||||
)
|
||||
if await locality_dropdown.is_visible(timeout=5000):
|
||||
await locality_dropdown.click()
|
||||
await page.wait_for_timeout(1000)
|
||||
await mouse.click_element(locality_dropdown)
|
||||
await human_delay(600, 1200)
|
||||
|
||||
# 2. Hover em "Localidades"
|
||||
localidades_menu = page.locator('//*[@id="navbar-container"]/div[2]/ul/li[3]/ul/li[2]/a')
|
||||
await localidades_menu.hover()
|
||||
await page.wait_for_timeout(500)
|
||||
try:
|
||||
await localidades_menu.click(timeout=2000)
|
||||
except Exception:
|
||||
pass # Se o clique falhar por sobreposição, o hover deve ser suficiente
|
||||
await page.wait_for_timeout(1000)
|
||||
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)
|
||||
|
||||
# 3. Clicar na localidade alvo (BR 09-0231 - PRIMAVERA DO LESTE - CENTRO)
|
||||
target_locality = page.locator('//*[@id="5044"]/a')
|
||||
# O click tradicional falha em menus ocultos. O evento no JS contorna as validações visuais:
|
||||
if await target_locality.count() > 0:
|
||||
await target_locality.first.evaluate("el => el.click()")
|
||||
else:
|
||||
logger.warning("ID 5044 não visível de primeira, tentando via fallback de texto.")
|
||||
fallback = page.locator(f'a:has-text("{Config.SIGA_DEST_CODE}")').last
|
||||
if await fallback.count() > 0:
|
||||
await fallback.evaluate("el => el.click()")
|
||||
|
||||
await page.wait_for_timeout(3500) # Mais tempo para o SIGA recarregar a sessão
|
||||
|
||||
# Wiggle enquanto o SIGA recarrega
|
||||
await mouse.idle_wiggle(3500)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"⚠️ Erro ao tentar mudar localidade: {e}")
|
||||
|
||||
# 4. Encontrar o link Fundo Bíblico - Busca mais flexível (ignora espaços exatos)
|
||||
fundo_link = page.get_by_role("link", name="Fundo Bíblico", exact=False).first
|
||||
# Esperamos apenas 'attached' (existir no DOM) em vez de 'visible', pois pode estar oculto num accordion
|
||||
await fundo_link.wait_for(state="attached", timeout=15000)
|
||||
await fundo_link.evaluate("el => el.click()")
|
||||
await page.wait_for_timeout(2000)
|
||||
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):
|
||||
@@ -339,8 +493,8 @@ class SigaAutomation:
|
||||
month_link = page.get_by_role("link", name=month_text)
|
||||
try:
|
||||
await month_link.wait_for(state="visible", timeout=10000)
|
||||
await month_link.click()
|
||||
await page.wait_for_timeout(2000)
|
||||
await self.mouse.click_element(month_link)
|
||||
await human_delay(1000, 2000)
|
||||
logger.info(f"📅 Entrou no {month_text}")
|
||||
except PlaywrightTimeout:
|
||||
raise RuntimeError(
|
||||
@@ -351,8 +505,8 @@ class SigaAutomation:
|
||||
# ---------- LANÇAMENTO DE SAÍDA ----------
|
||||
|
||||
async def process_group(self, group: SaleGroup) -> List[int]:
|
||||
"""Cria uma SAÍDA para o grupo. Retorna IDs lançados com sucesso."""
|
||||
page = self.page
|
||||
mouse = self.mouse
|
||||
products = group.get_aggregated_products()
|
||||
|
||||
logger.info(f"\n{'='*60}")
|
||||
@@ -362,22 +516,24 @@ class SigaAutomation:
|
||||
await self.check_session()
|
||||
|
||||
# 1. Novo → Saída
|
||||
await page.get_by_role("button", name=" Novo ").click()
|
||||
await page.wait_for_timeout(1000)
|
||||
await page.get_by_role("link", name="Saída").click()
|
||||
await page.wait_for_timeout(1500)
|
||||
novo_btn = page.get_by_role("button", name=" Novo ")
|
||||
await mouse.click_element(novo_btn)
|
||||
await human_delay(700, 1300)
|
||||
|
||||
# 2. Datepicker (aparece automaticamente após clicar "Saída")
|
||||
await self._select_date(group.data_venda.day)
|
||||
saida_link = page.get_by_role("link", name="Saída")
|
||||
await mouse.click_element(saida_link)
|
||||
await human_delay(1000, 1800)
|
||||
|
||||
# Aguardar loading do sistema (spinner "Aguarde...") após seleção de data
|
||||
# O destinatário é preenchido automaticamente após a data
|
||||
await page.wait_for_timeout(2000)
|
||||
# 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 page.wait_for_timeout(1000)
|
||||
await human_delay(800, 1500)
|
||||
|
||||
# 3. Inserir produtos
|
||||
successful_ids: List[int] = []
|
||||
@@ -390,79 +546,115 @@ class SigaAutomation:
|
||||
else:
|
||||
failed_products.append(product)
|
||||
|
||||
# 4. Se todos falharam → cancelar
|
||||
if not successful_ids:
|
||||
logger.error("❌ Todos produtos falharam! Cancelando SAÍDA...")
|
||||
await self._cancel_saida()
|
||||
return []
|
||||
|
||||
if failed_products:
|
||||
codes = [p.code for p in failed_products]
|
||||
logger.warning(f"⚠️ Produtos não encontrados: {codes}")
|
||||
logger.warning(f"⚠️ Produtos não encontrados: {[p.code for p in failed_products]}")
|
||||
|
||||
# 5. Ler valor calculado e preencher campo de pagamento
|
||||
# 4. Pagamento
|
||||
await self._fill_payment_value(group.meio_pag)
|
||||
|
||||
# 6. Confirmar
|
||||
# 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 _select_date(self, day: int):
|
||||
"""Seleciona o dia no datepicker Bootstrap (aparece automaticamente)."""
|
||||
page = self.page
|
||||
|
||||
try:
|
||||
dp = page.locator(".datepicker-days")
|
||||
await dp.wait_for(state="visible", timeout=5000)
|
||||
|
||||
cells = dp.locator("td.day:not(.old):not(.new)")
|
||||
count = await cells.count()
|
||||
for i in range(count):
|
||||
text = (await cells.nth(i).inner_text()).strip()
|
||||
if text == str(day):
|
||||
await cells.nth(i).click()
|
||||
logger.info(f"📅 Dia {day} selecionado.")
|
||||
return
|
||||
|
||||
raise RuntimeError(f"Dia {day} não encontrado no datepicker!")
|
||||
except PlaywrightTimeout:
|
||||
logger.warning("⚠️ Datepicker não apareceu, continuando...")
|
||||
|
||||
async def _add_product(self, code: str, qty: int) -> bool:
|
||||
"""Insere um produto na SAÍDA. Retorna True se OK."""
|
||||
page = self.page
|
||||
mouse = self.mouse
|
||||
try:
|
||||
# Abrir dropdown
|
||||
await page.get_by_role("link", name="* Selecione * ").click()
|
||||
await page.wait_for_timeout(500)
|
||||
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 search.fill(code)
|
||||
await search.press("Enter")
|
||||
await page.wait_for_timeout(2000)
|
||||
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 exato
|
||||
# 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 page.wait_for_timeout(500)
|
||||
await human_delay(300, 600)
|
||||
return False
|
||||
|
||||
await page.wait_for_timeout(500)
|
||||
await human_delay(400, 700)
|
||||
|
||||
# Preencher quantidade
|
||||
# Quantidade
|
||||
qty_field = page.locator("#f_quantidade")
|
||||
await qty_field.click()
|
||||
await qty_field.fill(str(qty))
|
||||
await mouse.click_element(qty_field)
|
||||
await mouse.human_type(qty_field, str(qty))
|
||||
|
||||
# Inserir
|
||||
await page.locator("#btn-inserir-produto").click()
|
||||
await page.wait_for_timeout(1500)
|
||||
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
|
||||
@@ -476,27 +668,28 @@ class SigaAutomation:
|
||||
return False
|
||||
|
||||
async def _select_exact_product(self, code: str) -> bool:
|
||||
"""Tenta selecionar o produto exato no dropdown select2."""
|
||||
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 exact.first.click()
|
||||
await mouse.click_element(exact.first)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Estratégia 2: opção que começa com o código
|
||||
# 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):
|
||||
text = (await results.nth(i).inner_text()).strip().upper()
|
||||
item = results.nth(i)
|
||||
text = (await item.inner_text()).strip().upper()
|
||||
if text.startswith(code_upper + " ") or text == code_upper:
|
||||
await results.nth(i).click()
|
||||
await mouse.click_element(item)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
@@ -506,9 +699,10 @@ class SigaAutomation:
|
||||
options = page.get_by_role("option")
|
||||
count = await options.count()
|
||||
for i in range(count):
|
||||
text = (await options.nth(i).inner_text()).strip().upper()
|
||||
opt = options.nth(i)
|
||||
text = (await opt.inner_text()).strip().upper()
|
||||
if text.startswith(code_upper):
|
||||
await options.nth(i).click()
|
||||
await mouse.click_element(opt)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
@@ -516,17 +710,18 @@ class SigaAutomation:
|
||||
return False
|
||||
|
||||
async def _cancel_saida(self):
|
||||
page = self.page
|
||||
cancel = page.locator('button.btn.btn-link.no-border[data-dismiss="modal"]', has_text="Cancelar")
|
||||
await cancel.click()
|
||||
await page.wait_for_timeout(2000)
|
||||
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):
|
||||
"""Lê o valor total dos produtos e preenche o campo correto (Dinheiro ou PIX)."""
|
||||
page = self.page
|
||||
mouse = self.mouse
|
||||
|
||||
# Ler o valor total dos produtos calculado pelo sistema
|
||||
try:
|
||||
valor_produtos = await page.locator("#f_valorproduto").input_value()
|
||||
except Exception:
|
||||
@@ -535,36 +730,44 @@ class SigaAutomation:
|
||||
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 field.click()
|
||||
await field.fill(valor_produtos)
|
||||
logger.info(f"💰 Valor em Dinheiro no Caixa: {valor_produtos}")
|
||||
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 field.click()
|
||||
await field.fill(valor_produtos)
|
||||
logger.info(f"💰 Pagto QRCode/PIX: {valor_produtos}")
|
||||
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 field.click()
|
||||
await field.fill(valor_produtos)
|
||||
logger.info(f"💰 Valor (fallback dinheiro): {valor_produtos}")
|
||||
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
|
||||
await page.get_by_role("button", name=" Confirmar").click()
|
||||
await page.wait_for_timeout(2000)
|
||||
await page.get_by_role("button", name="Ok").click()
|
||||
await page.wait_for_timeout(2000)
|
||||
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:
|
||||
"""Orquestrador principal."""
|
||||
|
||||
def __init__(self):
|
||||
Config.load()
|
||||
|
||||
@@ -577,17 +780,14 @@ class Application:
|
||||
logger.info(f"📅 Mês: {month:02d}/{year}")
|
||||
logger.info(f"{'='*60}\n")
|
||||
|
||||
# 1. Ler planilhas
|
||||
sheets = GoogleSheetsService(Config.GOOGLE_CREDENTIALS_FILE, Config.SPREADSHEET_ID)
|
||||
vendas = sheets.read_vendas(month, year)
|
||||
launched_ids = sheets.read_lancamentos()
|
||||
|
||||
# 2. Agrupar vendas pendentes
|
||||
groups = group_sales(vendas, launched_ids)
|
||||
if not groups:
|
||||
return
|
||||
|
||||
# 3. Automação SIGA
|
||||
siga = SigaAutomation()
|
||||
try:
|
||||
await siga.launch()
|
||||
@@ -608,7 +808,6 @@ class Application:
|
||||
else:
|
||||
total_fail.extend(group.all_ids)
|
||||
|
||||
# Resumo
|
||||
logger.info(f"\n{'='*60}")
|
||||
logger.info(f"📊 RESUMO FINAL")
|
||||
logger.info(f" ✅ Lançados: {len(total_ok)} vendas")
|
||||
@@ -628,4 +827,4 @@ class Application:
|
||||
# MAIN
|
||||
# ==============================================================================
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(Application().run())
|
||||
asyncio.run(Application().run())
|
||||
Reference in New Issue
Block a user