File size: 5,495 Bytes
6fcb771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
from dataclasses import dataclass
import re
from typing import Dict, Optional

from playwright.sync_api import sync_playwright


@dataclass
class AutomationConfig:
    url: str
    pre_submit_delay: float = 1.0
    headless: bool = True


def norm(s: str) -> str:
    s = (s or '').lower().strip()
    table = str.maketrans('áàãâäéèêëíìîïóòõôöúùûüç', 'aaaaaeeeeiiiiooooouuuuc')
    s = s.translate(table)
    s = re.sub(r'\s+', ' ', s)
    return s


def candidate_text(locator) -> str:
    parts = []
    for attr in ('aria-label', 'placeholder', 'name', 'id', 'type'):
        try:
            v = locator.get_attribute(attr)
            if v:
                parts.append(v)
        except Exception:
            pass
    return norm(' '.join(parts))


class SPXAutomation:
    def __init__(self, config: AutomationConfig):
        self.config = config

    def _fill_best_match(self, page, value: str, aliases: list[str]) -> Optional[str]:
        if not value:
            return None
        wanted = [norm(x) for x in aliases]

        for alias in wanted:
            try:
                loc = page.get_by_label(alias, exact=False).first
                if loc.count() and loc.is_visible():
                    loc.fill(value)
                    return alias
            except Exception:
                pass

        controls = page.locator('input:not([type="hidden"]), textarea, select')
        try:
            count = controls.count()
        except Exception:
            count = 0

        for i in range(count):
            c = controls.nth(i)
            try:
                if not c.is_visible():
                    continue
                meta = candidate_text(c)
                if any(a in meta or meta in a for a in wanted):
                    typ = (c.get_attribute('type') or '').lower()
                    if typ in ('radio', 'checkbox', 'file'):
                        continue
                    c.fill(value)
                    return meta or wanted[0]
            except Exception:
                continue
        return None

    def _discover_embedded_frame(self, page):
        for frame in page.frames:
            try:
                if frame.locator('input, textarea, select').count() > 0:
                    return frame
            except Exception:
                pass
        return page

    def fill_and_submit(self, profile: Dict[str, str]) -> str:
        aliases = {
            'nome': ['nome', 'nome completo', 'seu nome'],
            'cpf': ['cpf'],
            'telefone': ['telefone', 'celular', 'whatsapp'],
            'email': ['email', 'e-mail'],
            'cidade': ['cidade', 'municipio', 'município'],
            'cep': ['cep'],
            'disponibilidade': ['disponibilidade', 'dias disponiveis', 'dias disponíveis', 'disponível'],
            'hub': ['hub', 'unidade'],
            'observacao': ['observacao', 'observação', 'obs'],
        }

        with sync_playwright() as p:
            browser = p.chromium.launch(headless=self.config.headless)
            context = browser.new_context(viewport={'width': 1365, 'height': 900})
            page = context.new_page()
            try:
                page.goto(self.config.url, wait_until='domcontentloaded', timeout=60000)
                page.wait_for_timeout(2500)
                frame = self._discover_embedded_frame(page)

                filled = []
                missing = []
                for key, value in profile.items():
                    if not value:
                        continue
                    matched = self._fill_best_match(frame, value, aliases.get(key, [key]))
                    if matched:
                        filled.append(key)
                    else:
                        missing.append(key)

                page.wait_for_timeout(int(max(0, self.config.pre_submit_delay) * 1000))

                submit_candidates = [
                    frame.get_by_role('button', name=re.compile(r'enviar|submit|registrar|confirmar|salvar', re.I)),
                    frame.locator('input[type="submit"]'),
                    frame.locator('button[type="submit"]'),
                ]
                submit = None
                for cand in submit_candidates:
                    try:
                        count = cand.count()
                        if count > 0:
                            for idx in range(min(count, 3)):
                                el = cand.nth(idx)
                                if el.is_visible() and el.is_enabled():
                                    submit = el
                                    break
                        if submit:
                            break
                    except Exception:
                        pass

                if not submit:
                    raise RuntimeError(
                        f'Botão de envio não localizado. Campos preenchidos: {", ".join(filled) or "nenhum"}. '
                        f'Não encontrados: {", ".join(missing) if missing else "nenhum"}.'
                    )

                submit.click()
                page.wait_for_timeout(2500)

                return (
                    f'Campos preenchidos: {", ".join(filled) or "nenhum"}. '
                    f'Não encontrados: {", ".join(missing) if missing else "nenhum"}. '
                    f'URL final: {page.url}'
                )
            finally:
                context.close()
                browser.close()