worker-automate-hub 0.5.9__py3-none-any.whl → 0.5.12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- worker_automate_hub/api/rdp_service.py +38 -0
- worker_automate_hub/api/rpa_fila_service.py +22 -16
- worker_automate_hub/api/rpa_historico_service.py +135 -0
- worker_automate_hub/models/dao/rpa_fila.py +18 -0
- worker_automate_hub/tasks/jobs/fechar_conexao_rdp.py +131 -0
- worker_automate_hub/tasks/task_definitions.py +2 -0
- worker_automate_hub/tasks/task_executor.py +18 -143
- worker_automate_hub/worker.py +29 -4
- {worker_automate_hub-0.5.9.dist-info → worker_automate_hub-0.5.12.dist-info}/METADATA +1 -1
- {worker_automate_hub-0.5.9.dist-info → worker_automate_hub-0.5.12.dist-info}/RECORD +12 -9
- {worker_automate_hub-0.5.9.dist-info → worker_automate_hub-0.5.12.dist-info}/WHEEL +0 -0
- {worker_automate_hub-0.5.9.dist-info → worker_automate_hub-0.5.12.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,38 @@
|
|
1
|
+
import asyncio
|
2
|
+
import aiohttp
|
3
|
+
from rich.console import Console
|
4
|
+
from worker_automate_hub.config.settings import load_env_config
|
5
|
+
from worker_automate_hub.utils.logger import logger
|
6
|
+
|
7
|
+
console = Console()
|
8
|
+
|
9
|
+
async def send_rdp_action(uuid_robo: str, action: str):
|
10
|
+
env_config, _ = load_env_config()
|
11
|
+
|
12
|
+
body = {
|
13
|
+
"uuidRobo": uuid_robo,
|
14
|
+
"action": action
|
15
|
+
}
|
16
|
+
|
17
|
+
headers_basic = {"Authorization": f"Basic {env_config['API_AUTHORIZATION']}"}
|
18
|
+
url = f"{env_config['API_BASE_URL']}/robo/api/manage"
|
19
|
+
|
20
|
+
try:
|
21
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=True)) as session:
|
22
|
+
async with session.post(url, json=body, headers=headers_basic) as response:
|
23
|
+
if response.status == 200:
|
24
|
+
data = await response.json()
|
25
|
+
logger.info(f"Ação '{action}' enviada com sucesso: {data}")
|
26
|
+
console.print(f"Ação '{action}' enviada com sucesso.", style="bold green")
|
27
|
+
return data
|
28
|
+
else:
|
29
|
+
err_msg = f"Erro ao enviar ação '{action}': {response.status} - {await response.text()}"
|
30
|
+
logger.error(err_msg)
|
31
|
+
console.print(err_msg, style="bold red")
|
32
|
+
return {"error": err_msg}
|
33
|
+
|
34
|
+
except Exception as e:
|
35
|
+
err_msg = f"Erro ao comunicar com o endpoint RDP: {e}"
|
36
|
+
logger.error(err_msg)
|
37
|
+
console.print(err_msg, style="bold red")
|
38
|
+
return {"error": str(e)}
|
@@ -1,30 +1,34 @@
|
|
1
|
-
|
2
|
-
from worker_automate_hub.utils.logger import logger
|
1
|
+
import aiohttp
|
3
2
|
from rich.console import Console
|
4
3
|
|
5
|
-
import
|
4
|
+
from worker_automate_hub.config.settings import load_env_config
|
5
|
+
from worker_automate_hub.models.dao.rpa_fila import RpaFila
|
6
|
+
from worker_automate_hub.utils.logger import logger
|
6
7
|
|
7
8
|
console = Console()
|
8
9
|
|
9
10
|
|
10
11
|
async def burn_queue(id_fila: str):
|
11
12
|
env_config, _ = load_env_config()
|
12
|
-
try:
|
13
|
+
try:
|
13
14
|
|
14
15
|
headers_basic = {"Authorization": f"Basic {env_config["API_AUTHORIZATION"]}"}
|
15
|
-
|
16
16
|
|
17
|
-
async with aiohttp.ClientSession(
|
17
|
+
async with aiohttp.ClientSession(
|
18
|
+
connector=aiohttp.TCPConnector(verify_ssl=True)
|
19
|
+
) as session:
|
18
20
|
async with session.delete(
|
19
21
|
f"{env_config["API_BASE_URL"]}/fila/burn-queue/{id_fila}",
|
20
22
|
headers=headers_basic,
|
21
23
|
) as response:
|
22
24
|
if response.status == 200:
|
23
25
|
logger.info("Fila excluida com sucesso.")
|
24
|
-
console.print("\nFila excluida com sucesso.\n", style="bold green")
|
26
|
+
console.print("\nFila excluida com sucesso.\n", style="bold green")
|
25
27
|
else:
|
26
|
-
logger.error(f"Erro ao excluir a fila: {response.content}")
|
27
|
-
console.print(
|
28
|
+
logger.error(f"Erro ao excluir a fila: {response.content}")
|
29
|
+
console.print(
|
30
|
+
f"Erro ao excluir a fila: {response.content}", style="bold red"
|
31
|
+
)
|
28
32
|
|
29
33
|
except Exception as e:
|
30
34
|
err_msg = f"Erro remover registro da fila: {e}"
|
@@ -34,16 +38,18 @@ async def burn_queue(id_fila: str):
|
|
34
38
|
style="bold red",
|
35
39
|
)
|
36
40
|
return None
|
37
|
-
|
41
|
+
|
42
|
+
|
38
43
|
async def unlock_queue(id: str):
|
39
44
|
env_config, _ = load_env_config()
|
40
|
-
try:
|
41
|
-
headers_basic = {"Authorization": f"Basic {env_config["API_AUTHORIZATION"]}"}
|
42
|
-
|
45
|
+
try:
|
46
|
+
headers_basic = {"Authorization": f"Basic {env_config["API_AUTHORIZATION"]}"}
|
43
47
|
|
44
|
-
async with aiohttp.ClientSession(
|
48
|
+
async with aiohttp.ClientSession(
|
49
|
+
connector=aiohttp.TCPConnector(verify_ssl=True)
|
50
|
+
) as session:
|
45
51
|
async with session.get(
|
46
|
-
f"{env_config["API_BASE_URL"]}/fila/unlock-queue/{id}",
|
52
|
+
f"{env_config["API_BASE_URL"]}/fila/unlock-queue/{id}",
|
47
53
|
headers=headers_basic,
|
48
54
|
) as response:
|
49
55
|
return await response.text()
|
@@ -55,4 +61,4 @@ async def unlock_queue(id: str):
|
|
55
61
|
f"{err_msg}\n",
|
56
62
|
style="bold red",
|
57
63
|
)
|
58
|
-
return None
|
64
|
+
return None
|
@@ -1,12 +1,147 @@
|
|
1
|
+
from datetime import datetime
|
2
|
+
|
1
3
|
import aiohttp
|
4
|
+
from pytz import timezone
|
5
|
+
from rich.console import Console
|
2
6
|
|
3
7
|
from worker_automate_hub.config.settings import load_env_config
|
4
8
|
from worker_automate_hub.models.dao.rpa_historico import RpaHistorico
|
9
|
+
from worker_automate_hub.models.dao.rpa_processo import RpaProcesso
|
5
10
|
from worker_automate_hub.models.dto.rpa_historico_request_dto import (
|
6
11
|
RpaHistoricoRequestDTO,
|
12
|
+
RpaHistoricoStatusEnum,
|
13
|
+
RpaRetornoProcessoDTO,
|
14
|
+
)
|
15
|
+
from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
|
16
|
+
RpaProcessoEntradaDTO,
|
7
17
|
)
|
8
18
|
from worker_automate_hub.utils.logger import logger
|
9
19
|
|
20
|
+
console = Console()
|
21
|
+
|
22
|
+
|
23
|
+
async def create_store_historico(
|
24
|
+
task: RpaProcessoEntradaDTO,
|
25
|
+
processo: RpaProcesso,
|
26
|
+
status: RpaHistoricoStatusEnum,
|
27
|
+
retorno_processo: RpaRetornoProcessoDTO = None,
|
28
|
+
) -> RpaHistorico:
|
29
|
+
"""
|
30
|
+
Salva o histórico de um processo com status Processando.
|
31
|
+
|
32
|
+
Recebe um RpaProcessoEntradaDTO e um RpaProcesso como parâmetro e salva o
|
33
|
+
histórico com status Processando. Retorna um dicionário com o uuid do
|
34
|
+
histórico salvo.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
task (RpaProcessoEntradaDTO): O processo a ser salvo.
|
38
|
+
processo (RpaProcesso): O processo que está sendo executado.
|
39
|
+
|
40
|
+
Returns:
|
41
|
+
RpaHistorico: Dicionário com o uuid do histórico salvo.
|
42
|
+
"""
|
43
|
+
try:
|
44
|
+
from worker_automate_hub.config.settings import load_worker_config
|
45
|
+
|
46
|
+
worker_config = load_worker_config()
|
47
|
+
tz = timezone("America/Sao_Paulo")
|
48
|
+
start_time = datetime.now(tz).isoformat()
|
49
|
+
|
50
|
+
identificador_processo = (
|
51
|
+
task.configEntrada.get("nfe") or task.configEntrada.get("empresa") or ""
|
52
|
+
)
|
53
|
+
|
54
|
+
# Armazenar início da operação no histórico
|
55
|
+
start_data = RpaHistoricoRequestDTO(
|
56
|
+
uuidProcesso=task.uuidProcesso,
|
57
|
+
uuidRobo=worker_config["UUID_ROBO"],
|
58
|
+
prioridade=processo.prioridade,
|
59
|
+
desStatus=status,
|
60
|
+
configEntrada=task.configEntrada,
|
61
|
+
datInicioExecucao=start_time,
|
62
|
+
datEntradaFila=task.datEntradaFila,
|
63
|
+
identificador=identificador_processo,
|
64
|
+
retorno=retorno_processo,
|
65
|
+
)
|
66
|
+
|
67
|
+
store_response: RpaHistorico = await store(start_data)
|
68
|
+
console.print(
|
69
|
+
f"\nHistorico salvo com o uuid: {store_response.uuidHistorico}\n",
|
70
|
+
style="green",
|
71
|
+
)
|
72
|
+
return store_response
|
73
|
+
except Exception as e:
|
74
|
+
err_msg = f"Erro ao salvar o registro no histórico: {e}"
|
75
|
+
console.print(f"\n{err_msg}\n", style="red")
|
76
|
+
logger.error(f"{err_msg}")
|
77
|
+
|
78
|
+
|
79
|
+
async def create_update_historico(
|
80
|
+
historico_uuid: str,
|
81
|
+
task: RpaProcessoEntradaDTO,
|
82
|
+
retorno_processo: RpaRetornoProcessoDTO,
|
83
|
+
processo: RpaProcesso,
|
84
|
+
):
|
85
|
+
"""
|
86
|
+
Atualiza o histórico de um processo com o status de sucesso ou falha.
|
87
|
+
|
88
|
+
Recebe o uuid do histórico, o RpaProcessoEntradaDTO do processo, um booleano
|
89
|
+
indicando se o processo foi um sucesso ou não, o RpaRetornoProcessoDTO do
|
90
|
+
processo e o RpaProcesso do processo como parâmetro e atualiza o histórico
|
91
|
+
com o status de sucesso ou falha. Retorna um dicionário com o uuid do
|
92
|
+
histórico atualizado.
|
93
|
+
|
94
|
+
Args:
|
95
|
+
historico_uuid (str): O uuid do histórico.
|
96
|
+
task (RpaProcessoEntradaDTO): O RpaProcessoEntradaDTO do processo.
|
97
|
+
sucesso (bool): Um booleano indicando se o processo foi um sucesso ou não.
|
98
|
+
retorno_processo (RpaRetornoProcessoDTO): O RpaRetornoProcessoDTO do processo.
|
99
|
+
processo (RpaProcesso): O RpaProcesso do processo.
|
100
|
+
|
101
|
+
Returns:
|
102
|
+
RpaHistorico: Dicionário com o uuid do histórico atualizado.
|
103
|
+
"""
|
104
|
+
|
105
|
+
try:
|
106
|
+
from worker_automate_hub.config.settings import load_worker_config
|
107
|
+
|
108
|
+
worker_config = load_worker_config()
|
109
|
+
tz = timezone("America/Sao_Paulo")
|
110
|
+
des_status: RpaHistoricoStatusEnum = retorno_processo.status
|
111
|
+
end_time = datetime.now(tz).isoformat()
|
112
|
+
|
113
|
+
identificador_processo = (
|
114
|
+
task.configEntrada.get("nfe") or task.configEntrada.get("empresa") or ""
|
115
|
+
)
|
116
|
+
if not retorno_processo.tags:
|
117
|
+
retorno_processo.tags = []
|
118
|
+
|
119
|
+
# Armazenar fim da operação no histórico
|
120
|
+
end_data = RpaHistoricoRequestDTO(
|
121
|
+
uuidHistorico=historico_uuid,
|
122
|
+
uuidProcesso=task.uuidProcesso,
|
123
|
+
uuidRobo=worker_config["UUID_ROBO"],
|
124
|
+
prioridade=processo.prioridade,
|
125
|
+
desStatus=des_status,
|
126
|
+
configEntrada=task.configEntrada,
|
127
|
+
retorno=retorno_processo,
|
128
|
+
datFimExecucao=end_time,
|
129
|
+
identificador=identificador_processo,
|
130
|
+
tags=retorno_processo.tags,
|
131
|
+
)
|
132
|
+
|
133
|
+
update_response: RpaHistorico = await update(end_data)
|
134
|
+
console.print(
|
135
|
+
f"\nHistorico atualizado com o uuid: {update_response.uuidHistorico}\n",
|
136
|
+
style="green",
|
137
|
+
)
|
138
|
+
return update_response
|
139
|
+
|
140
|
+
except Exception as e:
|
141
|
+
err_msg = f"Erro ao atualizar o histórico do processo: {e}"
|
142
|
+
console.print(f"\n{err_msg}\n", style="red")
|
143
|
+
logger.error(err_msg)
|
144
|
+
|
10
145
|
|
11
146
|
async def store(data: RpaHistoricoRequestDTO) -> dict:
|
12
147
|
"""
|
@@ -0,0 +1,18 @@
|
|
1
|
+
from datetime import datetime
|
2
|
+
from typing import Optional
|
3
|
+
|
4
|
+
from pydantic import BaseModel, Field
|
5
|
+
|
6
|
+
|
7
|
+
class RpaFila(BaseModel):
|
8
|
+
uuidFila: Optional[str] = Field(None, alias="uuidFila")
|
9
|
+
uuidRobo: Optional[str] = Field(None, alias="uuidRobo")
|
10
|
+
uuidProcesso: str = Field(..., alias="uuidProcesso")
|
11
|
+
prioridade: int = Field(..., alias="prioridade")
|
12
|
+
configEntrada: Optional[dict] = Field(None, alias="configEntrada")
|
13
|
+
dtLeituraFila: Optional[datetime] = Field(None, alias="dtLeituraFila")
|
14
|
+
lock: Optional[bool] = Field(None, alias="lock")
|
15
|
+
mutarNotificacao: Optional[int] = Field(None, alias="mutarNotificacao")
|
16
|
+
|
17
|
+
class Config:
|
18
|
+
populate_by_name = True
|
@@ -0,0 +1,131 @@
|
|
1
|
+
import asyncio
|
2
|
+
import platform
|
3
|
+
import subprocess
|
4
|
+
import socket
|
5
|
+
import pyautogui
|
6
|
+
import pygetwindow as gw
|
7
|
+
from rich.console import Console
|
8
|
+
from pywinauto import Application
|
9
|
+
from worker_automate_hub.api.rdp_service import send_rdp_action
|
10
|
+
from worker_automate_hub.models.dto.rpa_historico_request_dto import RpaHistoricoStatusEnum, RpaRetornoProcessoDTO
|
11
|
+
from worker_automate_hub.models.dto.rpa_processo_rdp_dto import RpaProcessoRdpDTO
|
12
|
+
from worker_automate_hub.utils.logger import logger
|
13
|
+
from worker_automate_hub.utils.util import worker_sleep
|
14
|
+
|
15
|
+
console = Console()
|
16
|
+
|
17
|
+
class RDPConnection:
|
18
|
+
def __init__(self, task: RpaProcessoRdpDTO):
|
19
|
+
self.task = task
|
20
|
+
self.ip = task.configEntrada.get("ip")
|
21
|
+
self.user = task.configEntrada.get("user")
|
22
|
+
self.password = task.configEntrada.get("password")
|
23
|
+
self.processo = task.configEntrada.get("processo")
|
24
|
+
self.uuid_robo = task.configEntrada.get("uuidRobo")
|
25
|
+
|
26
|
+
async def verificar_conexao(self) -> bool:
|
27
|
+
"""
|
28
|
+
Verifica a conectividade com o host remoto via ping e verificação da porta RDP (3389).
|
29
|
+
"""
|
30
|
+
sistema_operacional = platform.system().lower()
|
31
|
+
console.print(f"Sistema operacional detectado: {sistema_operacional}")
|
32
|
+
|
33
|
+
comando_ping = (
|
34
|
+
["ping", "-n", "1", "-w", "1000", self.ip] if sistema_operacional == "windows" else ["ping", "-c", "1", "-W", "1", self.ip]
|
35
|
+
)
|
36
|
+
console.print(f"Executando comando de ping: {' '.join(comando_ping)}")
|
37
|
+
|
38
|
+
try:
|
39
|
+
resposta_ping = subprocess.run(comando_ping, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
40
|
+
ping_alcancado = resposta_ping.returncode == 0
|
41
|
+
console.print(f"Ping {'sucesso' if ping_alcancado else 'falhou'}")
|
42
|
+
except Exception as e:
|
43
|
+
console.print(f"Erro ao executar ping: {e}")
|
44
|
+
ping_alcancado = False
|
45
|
+
|
46
|
+
porta_aberta = False
|
47
|
+
try:
|
48
|
+
with socket.create_connection((self.ip, 3389), timeout=10):
|
49
|
+
console.print(f"Porta 3389 aberta em {self.ip}")
|
50
|
+
porta_aberta = True
|
51
|
+
except (socket.timeout, OSError) as e:
|
52
|
+
console.print(f"Erro ao verificar a porta RDP: {e}")
|
53
|
+
|
54
|
+
return ping_alcancado and porta_aberta
|
55
|
+
|
56
|
+
async def desligar(self):
|
57
|
+
"""
|
58
|
+
Fecha a conexão RDP interagindo com a janela do cliente RDP.
|
59
|
+
"""
|
60
|
+
janelas_rdp = [
|
61
|
+
win
|
62
|
+
for win in gw.getAllTitles()
|
63
|
+
if self.ip in win
|
64
|
+
]
|
65
|
+
|
66
|
+
if not janelas_rdp:
|
67
|
+
console.print(f"Nenhuma janela RDP encontrada para o IP: {self.ip}")
|
68
|
+
return
|
69
|
+
|
70
|
+
for titulo in janelas_rdp:
|
71
|
+
janela = gw.getWindowsWithTitle(titulo)[0]
|
72
|
+
if not janela:
|
73
|
+
console.print(f"Erro ao localizar a janela: {titulo}")
|
74
|
+
continue
|
75
|
+
|
76
|
+
try:
|
77
|
+
janela = gw.getWindowsWithTitle(titulo)[0]
|
78
|
+
console.print(f"Processando janela: {titulo}")
|
79
|
+
|
80
|
+
app = Application(backend="uia").connect(title=titulo)
|
81
|
+
app_window = app.window(title=titulo)
|
82
|
+
console.print(f"Janela encontrada: {titulo}")
|
83
|
+
|
84
|
+
if not app or not app_window:
|
85
|
+
raise Exception("Nenhuma janela com título correspondente foi encontrada.")
|
86
|
+
|
87
|
+
app_window.set_focus()
|
88
|
+
console.print("Janela RDP ativada.")
|
89
|
+
|
90
|
+
x, y = janela.left, janela.top
|
91
|
+
|
92
|
+
pyautogui.moveTo(x + 2, y + 2)
|
93
|
+
pyautogui.hotkey("alt", "space")
|
94
|
+
await worker_sleep(2)
|
95
|
+
pyautogui.press("down", presses=10, interval=0.1)
|
96
|
+
await worker_sleep(2)
|
97
|
+
pyautogui.press("enter")
|
98
|
+
await worker_sleep(2)
|
99
|
+
pyautogui.press("enter")
|
100
|
+
break
|
101
|
+
|
102
|
+
except Exception as e:
|
103
|
+
console.print(f"Erro ao interagir com a janela {titulo}: {e}")
|
104
|
+
raise(e)
|
105
|
+
|
106
|
+
async def fechar_conexao_rdp(task: RpaProcessoRdpDTO) -> RpaRetornoProcessoDTO:
|
107
|
+
"""
|
108
|
+
Gerencia o processo de fechamento da conexão RDP e retorna um status do processo.
|
109
|
+
"""
|
110
|
+
try:
|
111
|
+
rdp_connection = RDPConnection(task)
|
112
|
+
console.print("Iniciando o fechamento da conexão RDP.")
|
113
|
+
conectado = await rdp_connection.verificar_conexao()
|
114
|
+
|
115
|
+
if not conectado:
|
116
|
+
msg = f"A máquina informada não está ligada. Verifique o IP: {rdp_connection.ip} e a disponibilidade da porta."
|
117
|
+
logger.warning(msg)
|
118
|
+
return RpaRetornoProcessoDTO(sucesso=False, retorno=msg, status=RpaHistoricoStatusEnum.Falha)
|
119
|
+
|
120
|
+
await rdp_connection.desligar()
|
121
|
+
await send_rdp_action(rdp_connection.uuid_robo, "stop")
|
122
|
+
|
123
|
+
return RpaRetornoProcessoDTO(
|
124
|
+
sucesso=True,
|
125
|
+
retorno="Conexão RDP encerrada com sucesso.",
|
126
|
+
status=RpaHistoricoStatusEnum.Sucesso,
|
127
|
+
)
|
128
|
+
except Exception as ex:
|
129
|
+
err_msg = f"Erro ao executar o fechamento da conexão RDP para a máquina {rdp_connection.ip}: {ex}"
|
130
|
+
console.print(err_msg)
|
131
|
+
return RpaRetornoProcessoDTO(sucesso=False, retorno=err_msg, status=RpaHistoricoStatusEnum.Falha)
|
@@ -4,6 +4,7 @@ from worker_automate_hub.tasks.jobs.coleta_dje_process import (
|
|
4
4
|
coleta_dje_start_update,
|
5
5
|
)
|
6
6
|
from worker_automate_hub.tasks.jobs.conexao_rdp import conexao_rdp
|
7
|
+
from worker_automate_hub.tasks.jobs.fechar_conexao_rdp import fechar_conexao_rdp
|
7
8
|
from worker_automate_hub.tasks.jobs.descartes import descartes
|
8
9
|
from worker_automate_hub.tasks.jobs.ecac_estadual_main import (
|
9
10
|
ecac_estadual_main,
|
@@ -61,6 +62,7 @@ task_definitions = {
|
|
61
62
|
"abcfa1ba-d580-465a-aefb-c15ac4514407": descartes,
|
62
63
|
"2c8ee738-7447-4517-aee7-ce2c9d25cea9": transferencias,
|
63
64
|
"855f9e0f-e972-4f52-bc1a-60d1fc244e79": conexao_rdp,
|
65
|
+
"d36b0c83-9cc3-465f-ac80-934099a0e661": fechar_conexao_rdp,
|
64
66
|
"81785803-0594-4bba-9aa0-7f220c200296": coleta_dje_start_update,
|
65
67
|
"3907c8d4-d05b-4d92-b19a-2c4e934f1d78": ecac_estadual_main,
|
66
68
|
"81d2d6e6-e9eb-414d-a939-d220476d2bab": ecac_federal,
|
@@ -1,19 +1,17 @@
|
|
1
|
-
from datetime import datetime
|
2
|
-
|
3
1
|
from pytz import timezone
|
4
|
-
from worker_automate_hub.api.webhook_service import send_to_webhook
|
5
2
|
from rich.console import Console
|
6
3
|
|
7
|
-
from worker_automate_hub.api.client import
|
8
|
-
|
9
|
-
|
4
|
+
from worker_automate_hub.api.client import get_processo, send_gchat_message
|
5
|
+
from worker_automate_hub.api.rpa_fila_service import burn_queue
|
6
|
+
from worker_automate_hub.api.rpa_historico_service import (
|
7
|
+
create_store_historico,
|
8
|
+
create_update_historico,
|
10
9
|
)
|
11
|
-
from worker_automate_hub.api.
|
12
|
-
from worker_automate_hub.
|
10
|
+
from worker_automate_hub.api.webhook_service import send_to_webhook
|
11
|
+
from worker_automate_hub.config.settings import load_worker_config
|
13
12
|
from worker_automate_hub.models.dao.rpa_historico import RpaHistorico
|
14
13
|
from worker_automate_hub.models.dao.rpa_processo import RpaProcesso
|
15
14
|
from worker_automate_hub.models.dto.rpa_historico_request_dto import (
|
16
|
-
RpaHistoricoRequestDTO,
|
17
15
|
RpaHistoricoStatusEnum,
|
18
16
|
RpaRetornoProcessoDTO,
|
19
17
|
)
|
@@ -24,9 +22,6 @@ from worker_automate_hub.tasks.task_definitions import task_definitions
|
|
24
22
|
from worker_automate_hub.utils.logger import logger
|
25
23
|
from worker_automate_hub.utils.toast import show_toast
|
26
24
|
from worker_automate_hub.utils.util import capture_and_send_screenshot
|
27
|
-
from worker_automate_hub.config.settings import (
|
28
|
-
load_worker_config,
|
29
|
-
)
|
30
25
|
|
31
26
|
console = Console()
|
32
27
|
|
@@ -52,7 +47,9 @@ async def perform_task(task: RpaProcessoEntradaDTO):
|
|
52
47
|
registrar_historico = True
|
53
48
|
|
54
49
|
if registrar_historico:
|
55
|
-
historico: RpaHistorico = await
|
50
|
+
historico: RpaHistorico = await create_store_historico(
|
51
|
+
task, processo, RpaHistoricoStatusEnum.Processando
|
52
|
+
)
|
56
53
|
try:
|
57
54
|
if task_uuid in task_definitions:
|
58
55
|
# Executar a task
|
@@ -61,7 +58,7 @@ async def perform_task(task: RpaProcessoEntradaDTO):
|
|
61
58
|
|
62
59
|
result: RpaRetornoProcessoDTO = await task_definitions[task_uuid](task)
|
63
60
|
if registrar_historico:
|
64
|
-
await
|
61
|
+
await create_update_historico(
|
65
62
|
historico_uuid=historico.uuidHistorico,
|
66
63
|
task=task,
|
67
64
|
retorno_processo=result,
|
@@ -87,19 +84,21 @@ async def perform_task(task: RpaProcessoEntradaDTO):
|
|
87
84
|
show_toast("Erro", err_msg)
|
88
85
|
|
89
86
|
if registrar_historico:
|
90
|
-
await
|
87
|
+
await create_update_historico(
|
91
88
|
historico_uuid=historico.uuidHistorico,
|
92
89
|
task=task,
|
93
90
|
retorno_processo=RpaRetornoProcessoDTO(
|
94
91
|
sucesso=False,
|
95
92
|
retorno=err_msg,
|
96
|
-
status=RpaHistoricoStatusEnum.
|
93
|
+
status=RpaHistoricoStatusEnum.Descartado,
|
97
94
|
),
|
98
95
|
processo=processo,
|
99
96
|
)
|
100
|
-
await
|
97
|
+
await burn_queue(task.uuidFila)
|
101
98
|
if url_retorno is not None:
|
102
|
-
await send_to_webhook(
|
99
|
+
await send_to_webhook(
|
100
|
+
url_retorno, RpaHistoricoStatusEnum.Descartado, err_msg
|
101
|
+
)
|
103
102
|
return None
|
104
103
|
except Exception as e:
|
105
104
|
err_msg = f"Erro ao performar o processo: {e}"
|
@@ -108,7 +107,7 @@ async def perform_task(task: RpaProcessoEntradaDTO):
|
|
108
107
|
show_toast("Erro", err_msg)
|
109
108
|
|
110
109
|
if registrar_historico:
|
111
|
-
await
|
110
|
+
await create_update_historico(
|
112
111
|
historico_uuid=historico.uuidHistorico,
|
113
112
|
task=task,
|
114
113
|
retorno_processo=RpaRetornoProcessoDTO(
|
@@ -121,127 +120,3 @@ async def perform_task(task: RpaProcessoEntradaDTO):
|
|
121
120
|
)
|
122
121
|
if url_retorno is not None:
|
123
122
|
await send_to_webhook(url_retorno, RpaHistoricoStatusEnum.Falha, err_msg)
|
124
|
-
|
125
|
-
|
126
|
-
async def _store_historico(
|
127
|
-
task: RpaProcessoEntradaDTO, processo: RpaProcesso
|
128
|
-
) -> RpaHistorico:
|
129
|
-
"""
|
130
|
-
Salva o histórico de um processo com status Processando.
|
131
|
-
|
132
|
-
Recebe um RpaProcessoEntradaDTO e um RpaProcesso como parâmetro e salva o
|
133
|
-
histórico com status Processando. Retorna um dicionário com o uuid do
|
134
|
-
histórico salvo.
|
135
|
-
|
136
|
-
Args:
|
137
|
-
task (RpaProcessoEntradaDTO): O processo a ser salvo.
|
138
|
-
processo (RpaProcesso): O processo que está sendo executado.
|
139
|
-
|
140
|
-
Returns:
|
141
|
-
RpaHistorico: Dicionário com o uuid do histórico salvo.
|
142
|
-
"""
|
143
|
-
try:
|
144
|
-
from worker_automate_hub.config.settings import load_worker_config
|
145
|
-
|
146
|
-
worker_config = load_worker_config()
|
147
|
-
tz = timezone("America/Sao_Paulo")
|
148
|
-
start_time = datetime.now(tz).isoformat()
|
149
|
-
|
150
|
-
identificador_processo = (
|
151
|
-
task.configEntrada.get("nfe") or
|
152
|
-
task.configEntrada.get("empresa") or
|
153
|
-
""
|
154
|
-
)
|
155
|
-
|
156
|
-
|
157
|
-
# Armazenar início da operação no histórico
|
158
|
-
start_data = RpaHistoricoRequestDTO(
|
159
|
-
uuidProcesso=task.uuidProcesso,
|
160
|
-
uuidRobo=worker_config["UUID_ROBO"],
|
161
|
-
prioridade=processo.prioridade,
|
162
|
-
desStatus=RpaHistoricoStatusEnum.Processando,
|
163
|
-
configEntrada=task.configEntrada,
|
164
|
-
datInicioExecucao=start_time,
|
165
|
-
datEntradaFila=task.datEntradaFila,
|
166
|
-
identificador=identificador_processo,
|
167
|
-
)
|
168
|
-
|
169
|
-
store_response: RpaHistorico = await store(start_data)
|
170
|
-
console.print(
|
171
|
-
f"\nHistorico salvo com o uuid: {store_response.uuidHistorico}\n",
|
172
|
-
style="green",
|
173
|
-
)
|
174
|
-
return store_response
|
175
|
-
except Exception as e:
|
176
|
-
err_msg = f"Erro ao salvar o registro no histórico: {e}"
|
177
|
-
console.print(f"\n{err_msg}\n", style="red")
|
178
|
-
logger.error(f"{err_msg}")
|
179
|
-
|
180
|
-
|
181
|
-
async def _update_historico(
|
182
|
-
historico_uuid: str,
|
183
|
-
task: RpaProcessoEntradaDTO,
|
184
|
-
retorno_processo: RpaRetornoProcessoDTO,
|
185
|
-
processo: RpaProcesso,
|
186
|
-
):
|
187
|
-
"""
|
188
|
-
Atualiza o histórico de um processo com o status de sucesso ou falha.
|
189
|
-
|
190
|
-
Recebe o uuid do histórico, o RpaProcessoEntradaDTO do processo, um booleano
|
191
|
-
indicando se o processo foi um sucesso ou não, o RpaRetornoProcessoDTO do
|
192
|
-
processo e o RpaProcesso do processo como parâmetro e atualiza o histórico
|
193
|
-
com o status de sucesso ou falha. Retorna um dicionário com o uuid do
|
194
|
-
histórico atualizado.
|
195
|
-
|
196
|
-
Args:
|
197
|
-
historico_uuid (str): O uuid do histórico.
|
198
|
-
task (RpaProcessoEntradaDTO): O RpaProcessoEntradaDTO do processo.
|
199
|
-
sucesso (bool): Um booleano indicando se o processo foi um sucesso ou não.
|
200
|
-
retorno_processo (RpaRetornoProcessoDTO): O RpaRetornoProcessoDTO do processo.
|
201
|
-
processo (RpaProcesso): O RpaProcesso do processo.
|
202
|
-
|
203
|
-
Returns:
|
204
|
-
RpaHistorico: Dicionário com o uuid do histórico atualizado.
|
205
|
-
"""
|
206
|
-
|
207
|
-
try:
|
208
|
-
from worker_automate_hub.config.settings import load_worker_config
|
209
|
-
|
210
|
-
worker_config = load_worker_config()
|
211
|
-
tz = timezone("America/Sao_Paulo")
|
212
|
-
des_status: RpaHistoricoStatusEnum = retorno_processo.status
|
213
|
-
end_time = datetime.now(tz).isoformat()
|
214
|
-
|
215
|
-
identificador_processo = (
|
216
|
-
task.configEntrada.get("nfe") or
|
217
|
-
task.configEntrada.get("empresa") or
|
218
|
-
""
|
219
|
-
)
|
220
|
-
if not retorno_processo.tags:
|
221
|
-
retorno_processo.tags = []
|
222
|
-
|
223
|
-
# Armazenar fim da operação no histórico
|
224
|
-
end_data = RpaHistoricoRequestDTO(
|
225
|
-
uuidHistorico=historico_uuid,
|
226
|
-
uuidProcesso=task.uuidProcesso,
|
227
|
-
uuidRobo=worker_config["UUID_ROBO"],
|
228
|
-
prioridade=processo.prioridade,
|
229
|
-
desStatus=des_status,
|
230
|
-
configEntrada=task.configEntrada,
|
231
|
-
retorno=retorno_processo,
|
232
|
-
datFimExecucao=end_time,
|
233
|
-
identificador=identificador_processo,
|
234
|
-
tags=retorno_processo.tags,
|
235
|
-
)
|
236
|
-
|
237
|
-
update_response: RpaHistorico = await update(end_data)
|
238
|
-
console.print(
|
239
|
-
f"\nHistorico atualizado com o uuid: {update_response.uuidHistorico}\n",
|
240
|
-
style="green",
|
241
|
-
)
|
242
|
-
return update_response
|
243
|
-
|
244
|
-
except Exception as e:
|
245
|
-
err_msg = f"Erro ao atualizar o histórico do processo: {e}"
|
246
|
-
console.print(f"\n{err_msg}\n", style="red")
|
247
|
-
logger.error(err_msg)
|
worker_automate_hub/worker.py
CHANGED
@@ -3,19 +3,30 @@ import os
|
|
3
3
|
import threading
|
4
4
|
from pathlib import Path
|
5
5
|
|
6
|
-
from worker_automate_hub.api.rpa_fila_service import burn_queue, unlock_queue
|
7
6
|
import pyfiglet
|
8
7
|
from rich.console import Console
|
9
8
|
|
10
9
|
from worker_automate_hub.api.client import (
|
11
10
|
get_new_task,
|
11
|
+
get_processo,
|
12
12
|
notify_is_alive,
|
13
13
|
send_gchat_message,
|
14
14
|
)
|
15
|
+
from worker_automate_hub.api.rpa_fila_service import burn_queue
|
16
|
+
from worker_automate_hub.api.rpa_historico_service import (
|
17
|
+
create_store_historico,
|
18
|
+
)
|
15
19
|
from worker_automate_hub.config.settings import (
|
16
20
|
load_env_config,
|
17
21
|
load_worker_config,
|
18
22
|
)
|
23
|
+
from worker_automate_hub.models.dao.rpa_processo import RpaProcesso
|
24
|
+
from worker_automate_hub.models.dto.rpa_historico_request_dto import (
|
25
|
+
RpaHistoricoStatusEnum,
|
26
|
+
RpaRetornoProcessoDTO,
|
27
|
+
RpaTagDTO,
|
28
|
+
RpaTagEnum,
|
29
|
+
)
|
19
30
|
from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
|
20
31
|
RpaProcessoEntradaDTO,
|
21
32
|
)
|
@@ -40,15 +51,29 @@ async def check_and_execute_tasks(stop_event: threading.Event):
|
|
40
51
|
worker_config = load_worker_config()
|
41
52
|
if task is not None:
|
42
53
|
processo_existe = await is_uuid_in_tasks(task.uuidProcesso)
|
54
|
+
await burn_queue(task.uuidFila)
|
43
55
|
if processo_existe:
|
44
|
-
await burn_queue(task.uuidFila)
|
45
56
|
logger.info(f"Executando a task: {task.nomProcesso}")
|
46
57
|
await perform_task(task)
|
47
58
|
else:
|
48
|
-
|
49
|
-
log_message = f"O processo [{task.nomProcesso}] não existe no Worker [{worker_config['NOME_ROBO']}] e foi devolvido para a fila."
|
59
|
+
log_message = f"O processo [{task.nomProcesso}] não existe no Worker [{worker_config['NOME_ROBO']}] e foi removido da fila."
|
50
60
|
console.print(f"\n{log_message}\n", style="yellow")
|
51
61
|
logger.error(log_message)
|
62
|
+
try:
|
63
|
+
processo: RpaProcesso = await get_processo(task.uuidProcesso)
|
64
|
+
await create_store_historico(
|
65
|
+
task,
|
66
|
+
processo,
|
67
|
+
RpaHistoricoStatusEnum.Descartado,
|
68
|
+
retorno_processo=RpaRetornoProcessoDTO(
|
69
|
+
sucesso=False,
|
70
|
+
retorno=log_message,
|
71
|
+
status=RpaHistoricoStatusEnum.Descartado,
|
72
|
+
tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
|
73
|
+
),
|
74
|
+
)
|
75
|
+
except Exception as e:
|
76
|
+
console.print(f"Erro ao salvar histórico de processo não implementado: {e}", style="bold red")
|
52
77
|
await send_gchat_message(log_message)
|
53
78
|
else:
|
54
79
|
await asyncio.sleep(5)
|
@@ -4,8 +4,9 @@ worker_automate_hub/api/ahead_service.py,sha256=0tX-i1ACRg3_yOI-_AfFEZ6FNU3L8Zb3
|
|
4
4
|
worker_automate_hub/api/client.py,sha256=tFrIr4mpjvUJ1uU--BCiWa3NT2Ru_yliBsWmfiGt1LA,19720
|
5
5
|
worker_automate_hub/api/helpers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
6
6
|
worker_automate_hub/api/helpers/api_helpers.py,sha256=SkheO2fXexeh-a4shr8Qzsz_kZhuSG0DJ7kbODctRbM,3696
|
7
|
-
worker_automate_hub/api/
|
8
|
-
worker_automate_hub/api/
|
7
|
+
worker_automate_hub/api/rdp_service.py,sha256=cDG3RP59U1m2rRX51IMqqKwkQ2-Rgl0PRJ8e4cXyhjs,1547
|
8
|
+
worker_automate_hub/api/rpa_fila_service.py,sha256=6RyzCvj2qODifz3cIwOg5kuUpk8cyN_yFmLV5YOJAoQ,2186
|
9
|
+
worker_automate_hub/api/rpa_historico_service.py,sha256=wQw8_k8i0S-r7qrrn4BSoztkgtiuH_bHRSEytbZebDg,9690
|
9
10
|
worker_automate_hub/api/webhook_service.py,sha256=9KvTv1U02CSYpf_vLnqs4RZqZzR7Mn0v1OVOI451yOM,1762
|
10
11
|
worker_automate_hub/cli.py,sha256=JB45pjPJ8_E-4xw0OjqDMcAw-tpDV0mjmvwJRTnTzY0,6862
|
11
12
|
worker_automate_hub/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
@@ -22,6 +23,7 @@ worker_automate_hub/decorators/timeit.py,sha256=lL2bK8TbF4GE5Ma3LI5N5iJxGF1vwlZ4
|
|
22
23
|
worker_automate_hub/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
23
24
|
worker_automate_hub/models/dao/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
24
25
|
worker_automate_hub/models/dao/rpa_configuracao.py,sha256=pftPsgbqsDjN8pRrzcjBKKfXaHPFA7KkJx9gl8LW7lk,328
|
26
|
+
worker_automate_hub/models/dao/rpa_fila.py,sha256=ZV-0ykAPKjMRTvgmts3WwPQQlCRv6h4mYr6Ki8IeoEE,699
|
25
27
|
worker_automate_hub/models/dao/rpa_historico.py,sha256=zKo_Wz_qMdB-cmFkJY1ckFx63wBPUumir37OxFijhes,1071
|
26
28
|
worker_automate_hub/models/dao/rpa_processo.py,sha256=AfOUhJKL-AAOyjON4g7f6B7Bxa174FNC1Eh7oItK2kA,1233
|
27
29
|
worker_automate_hub/models/dto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
@@ -53,14 +55,15 @@ worker_automate_hub/tasks/jobs/entrada_de_notas_505.py,sha256=jIml8gjXPdI6_x7S9V
|
|
53
55
|
worker_automate_hub/tasks/jobs/entrada_de_notas_7139.py,sha256=oxH2CUJj3UyhYoSxEY2hUr_6wFgZPLcHswEbApIu8VY,15558
|
54
56
|
worker_automate_hub/tasks/jobs/entrada_de_notas_9.py,sha256=Urt_7dZNuyUkSyG9fYb2ArBXzEONXlrqWIesoXeL1EI,50984
|
55
57
|
worker_automate_hub/tasks/jobs/exemplo_processo.py,sha256=3-zxbb-9YHPmSA_K1Qgxp_FwSqg2QDjGBRCLxDZ8QoQ,3451
|
58
|
+
worker_automate_hub/tasks/jobs/fechar_conexao_rdp.py,sha256=80FnDN6n_NMmDdQn6mmXEExRpK4BiYPrF0-C48Y1MBc,5445
|
56
59
|
worker_automate_hub/tasks/jobs/fidc_gerar_nosso_numero.py,sha256=mZ6mCaz1lYmyFxwC8MVLXPsgynE1VkNKlEzYGsciDiY,10179
|
57
60
|
worker_automate_hub/tasks/jobs/fidc_remessa_cobranca_cnab240.py,sha256=QBGm6eS5JghgNWNqZlk1g2a2iV8LnBLiOTBBL3Giet0,4181
|
58
61
|
worker_automate_hub/tasks/jobs/login_emsys.py,sha256=IoGCIvO4UwmuxOZEn3cvYJlKyhsWvtHvbFk8vwjTroQ,5620
|
59
62
|
worker_automate_hub/tasks/jobs/playground.py,sha256=bdnXv3C7WLQUxt4edGZDfAbRJJ2-q4zuIQaK3GLnaUc,1765
|
60
63
|
worker_automate_hub/tasks/jobs/sped_fiscal.py,sha256=_byvD7i_N3pgPjQd1lc0XNKCFONIPbmvX3_jq5AnbKY,26707
|
61
64
|
worker_automate_hub/tasks/jobs/transferencias.py,sha256=zwCbVTwX15SCeLtvYgAyENeUSIuETx4Z9Cysr1Es8Jo,38013
|
62
|
-
worker_automate_hub/tasks/task_definitions.py,sha256=
|
63
|
-
worker_automate_hub/tasks/task_executor.py,sha256=
|
65
|
+
worker_automate_hub/tasks/task_definitions.py,sha256=KG84tDaTlCpthdYmdR1193BOudELGcoglmIpQpd2PLQ,4606
|
66
|
+
worker_automate_hub/tasks/task_executor.py,sha256=tVmuU-MWDkgbGg3uSK5IBEb_tJqGSnYZpwszdGUofOM,5150
|
64
67
|
worker_automate_hub/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
65
68
|
worker_automate_hub/utils/env.py,sha256=TacQjGRO7PUNpttrhTAc5Gnegaiysl2Knsv1P8qfkfs,57
|
66
69
|
worker_automate_hub/utils/get_creds_gworkspace.py,sha256=ZJ0IIEjM4IXIV9rwfbOZ1V1wiaMoJAGZeSy0D37sYdU,2212
|
@@ -69,8 +72,8 @@ worker_automate_hub/utils/toast.py,sha256=xPHc5r5uOxB_cZlCzm13Kt2qSKLLFZALncU6Qg
|
|
69
72
|
worker_automate_hub/utils/updater.py,sha256=en2FCGhI8aZ-JNP3LQm64NJDc4awCNW7UhbVlwDl49Y,7972
|
70
73
|
worker_automate_hub/utils/util.py,sha256=3XNBaYVbJ-KgWyHDKY2jIFuQzgBQs-w1d5iEQZv1D4U,125867
|
71
74
|
worker_automate_hub/utils/utils_nfe_entrada.py,sha256=p5r_L5k7gqCBvV8v6dbLFM6INKiSpGc4Gegid0_YAh4,29017
|
72
|
-
worker_automate_hub/worker.py,sha256=
|
73
|
-
worker_automate_hub-0.5.
|
74
|
-
worker_automate_hub-0.5.
|
75
|
-
worker_automate_hub-0.5.
|
76
|
-
worker_automate_hub-0.5.
|
75
|
+
worker_automate_hub/worker.py,sha256=ojfBsKdCuUAQS5_F3eZVMLV015GmtrasVvxKsmo2rx8,5942
|
76
|
+
worker_automate_hub-0.5.12.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
|
77
|
+
worker_automate_hub-0.5.12.dist-info/METADATA,sha256=VEzm6fiv2ZT3qD3obSxZdLPWw2Hza8yzOnlszMui0JE,2894
|
78
|
+
worker_automate_hub-0.5.12.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
79
|
+
worker_automate_hub-0.5.12.dist-info/RECORD,,
|
File without changes
|
{worker_automate_hub-0.5.9.dist-info → worker_automate_hub-0.5.12.dist-info}/entry_points.txt
RENAMED
File without changes
|