worker-automate-hub 0.5.815__py3-none-any.whl → 0.5.816__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.

Potentially problematic release.


This version of worker-automate-hub might be problematic. Click here for more details.

@@ -744,6 +744,8 @@ async def send_file(
744
744
  elif file_extension == "xlsx":
745
745
  filename = desArquivo
746
746
  content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
747
+ elif file_extension == "csv":
748
+ content_type = "text/csv"
747
749
  else:
748
750
  raise ValueError(f"Extensão de arquivo não suportada: {file_extension}")
749
751
 
@@ -0,0 +1,295 @@
1
+ import numpy
2
+ import asyncio
3
+ import sys
4
+ import os
5
+ import io
6
+ from pywinauto.keyboard import send_keys
7
+ # sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
8
+ from worker_automate_hub.models.dto.rpa_historico_request_dto import (
9
+ RpaHistoricoStatusEnum,
10
+ RpaRetornoProcessoDTO,
11
+ RpaTagDTO,
12
+ RpaTagEnum,
13
+ )
14
+ from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
15
+ RpaProcessoEntradaDTO,
16
+ )
17
+ from worker_automate_hub.utils.util import (
18
+ kill_all_emsys,
19
+ worker_sleep,
20
+ )
21
+ from rich.console import Console
22
+ import pyautogui
23
+ from datetime import datetime
24
+ # from dateutil.relativedelta import relativedelta
25
+ from PIL import ImageFilter, ImageEnhance
26
+ from pytesseract import image_to_string
27
+ from pywinauto import Application, Desktop
28
+ import subprocess
29
+ import os
30
+ from worker_automate_hub.api.client import (
31
+ get_config_by_name, send_file
32
+ )
33
+ from worker_automate_hub.utils.utils_nfe_entrada import EMSys
34
+ import psutil
35
+ from time import sleep
36
+
37
+ pyautogui.PAUSE = 0.5
38
+ console = Console()
39
+ emsys = EMSys()
40
+
41
+
42
+ def get_text_from_window(window, relative_coords, value=None):
43
+ try:
44
+ screenshot = window.capture_as_image()
45
+ imagem = screenshot.convert("L")
46
+ imagem = imagem.filter(ImageFilter.SHARPEN)
47
+ imagem = ImageEnhance.Contrast(imagem).enhance(2)
48
+ cropped_screenshot = imagem.crop(relative_coords)
49
+ texto = image_to_string(cropped_screenshot, lang="por")
50
+ return (value.upper() in texto.upper()) if value != None else texto.lower()
51
+ except Exception as error:
52
+ console.print(f"Error: {error}")
53
+
54
+
55
+ async def open_contabil_processes():
56
+ try:
57
+ console.print("Abrindo EMSys Contabil...")
58
+ os.startfile("C:\\Users\\automatehub\\Desktop\\Contabil\\contabil1.lnk")
59
+ await worker_sleep(3)
60
+ os.startfile("C:\\Users\\automatehub\\Desktop\\Contabil\\contabil2.lnk")
61
+ await worker_sleep(30)
62
+ os.startfile("C:\\Users\\automatehub\\Desktop\\Contabil\\contabil3.lnk")
63
+ await worker_sleep(20)
64
+ pyautogui.hotkey("win", "d")
65
+ await worker_sleep(4)
66
+ os.startfile("C:\\Users\\automatehub\\Desktop\\Contabil\\contabil4.lnk")
67
+ await worker_sleep(2)
68
+ except Exception as error:
69
+ console.print(f"Error: {error}")
70
+
71
+
72
+ async def geracao_balancetes_filial(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoDTO:
73
+ try:
74
+ await kill_all_emsys()
75
+ await open_contabil_processes()
76
+ config = await get_config_by_name("login_emsys_contabil")
77
+ filial = task.configEntrada.get("filialEmpresaOrigem")
78
+ periodo_inicial = task.configEntrada.get("periodoInicial")
79
+ periodo_final = task.configEntrada.get("periodoFinal")
80
+ historico_id = task.historico_id
81
+ if historico_id:
82
+ console.print("Historico ID recuperado com sucesso...\n")
83
+ app = None
84
+ max_attempts = 30
85
+ console.print("Tentando encontrar janela de login...")
86
+ for attempt in range(max_attempts):
87
+ try:
88
+ app = Application(backend="win32").connect(
89
+ title="Selecione o Usuário para autenticação"
90
+ )
91
+ console.print("Janela encontrada!")
92
+ break
93
+ except:
94
+ console.print("Janela ainda nao encontrada...")
95
+ await worker_sleep(1)
96
+ if not app:
97
+ console.print("Nao foi possivel encontrar a janela de login...")
98
+ return RpaRetornoProcessoDTO(
99
+ sucesso=False,
100
+ retorno="Erro durante tentativa localizacao de janelas...",
101
+ status=RpaHistoricoStatusEnum.Falha,
102
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
103
+ )
104
+ await emsys.verify_warning_and_error("Erro", "&Ok")
105
+ await worker_sleep(4)
106
+ pyautogui.click(x=1021, y=127)
107
+ console.print("Logando...")
108
+ await emsys.verify_warning_and_error("Erro", "&Ok")
109
+ pyautogui.write(config.conConfiguracao.get("user"))
110
+ pyautogui.press("enter")
111
+
112
+ await worker_sleep(4)
113
+ pyautogui.write(config.conConfiguracao.get("pass"))
114
+ pyautogui.press("enter")
115
+
116
+ await worker_sleep(10)
117
+
118
+ main_window = None
119
+ for attempt in range(max_attempts):
120
+ main_window = Application().connect(title="EMSys [Contabil]")
121
+ main_window = main_window.top_window()
122
+ if main_window.exists():
123
+ console.print("Janela encontrada!")
124
+ break
125
+ console.print("Janela ainda nao encontrada...")
126
+ await worker_sleep(1)
127
+
128
+ if not main_window:
129
+ return RpaRetornoProcessoDTO(
130
+ sucesso=False,
131
+ retorno="Erro durante tentativa localizacao de janelas....",
132
+ status=RpaHistoricoStatusEnum.Falha,
133
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
134
+ )
135
+
136
+ # Adicionando foco
137
+ try:
138
+ main_window.set_focus()
139
+ console.print(f"Ativando janela: {main_window}")
140
+ except Exception as error:
141
+ console.print(f"Erro ao setar foco na janela: {main_window}")
142
+
143
+ await worker_sleep(4)
144
+ console.print("Cicar em BAL")
145
+ pyautogui.click(x=453, y=96)
146
+ await worker_sleep(4)
147
+
148
+ console.print("Preenchendo campo periodo...")
149
+
150
+ app = Application(backend="win32").connect(class_name="TFrmBalancete")
151
+ win = app.window(class_name="TFrmBalancete")
152
+
153
+ # Seus índices: inicial = found_index=1, final = found_index=0
154
+ ctrl_inicial = win.child_window(class_name="TRzEditDate", found_index=1).wrapper_object()
155
+ ctrl_final = win.child_window(class_name="TRzEditDate", found_index=0).wrapper_object()
156
+
157
+ # ---- Inicial ----
158
+ try:
159
+ ctrl_inicial.set_edit_text(periodo_inicial) # tenta via WM_SETTEXT
160
+ except Exception:
161
+ ctrl_inicial.set_focus()
162
+ ctrl_inicial.click_input()
163
+ send_keys('^a{DELETE}')
164
+ send_keys(periodo_inicial.replace('/', '')) # fallback: digita só dígitos (máscara)
165
+
166
+ # ---- Final ----
167
+ try:
168
+ ctrl_final.set_edit_text(periodo_final)
169
+ except Exception:
170
+ ctrl_final.set_focus()
171
+ ctrl_final.click_input()
172
+ send_keys('^a{DELETE}')
173
+ send_keys(periodo_final.replace('/', ''))
174
+
175
+ await worker_sleep(2)
176
+
177
+ console.print("Selecionar detalhada por centro de custo..")
178
+ detalhada = win.child_window(
179
+ class_name="TRzComboBox", found_index=0
180
+ )
181
+ detalhada.select("Centro de Custo")
182
+
183
+ await worker_sleep(2)
184
+
185
+ console.print("Selecionar considerar contas analíticas zerada")
186
+ contas_analit_zeradas = win.child_window(class_name="TRzCheckBox", found_index=2).click()
187
+
188
+ console.print("Selecionar considerar contas sintéticas zerada")
189
+ contas_sint_zeradas = win.child_window(class_name="TRzCheckBox", found_index=0).click()
190
+
191
+ console.print("Selecionar por filiais")
192
+ selec_filiais = win.child_window(class_name="TRzCheckBox", found_index=3).click()
193
+
194
+ console.print("Selecionar CSV")
195
+ selec_csv = win.child_window(class_name="TRzComboBox", found_index=1)
196
+ selec_csv.select("Arquivo CSV")
197
+
198
+ console.print("Clicar em gerar relatório")
199
+ btn_gerar_relatorio = win.child_window(class_name="TBitBtn", found_index=0).click()
200
+
201
+ # Selecionar filial
202
+ app = Application(backend="win32").connect(title="Seleção de Empresas", timeout=10)
203
+ dlg = app.window(title ="Seleção de Empresas")
204
+ edit = dlg.child_window(class_name="TEdit", found_index=0).wrapper_object()
205
+
206
+ # Tenta via WM_SETTEXT
207
+ try:
208
+ edit.set_focus()
209
+ edit.set_edit_text("") # limpa
210
+ edit.set_edit_text("3") # escreve
211
+ except Exception:
212
+ # Fallback: digita como teclado
213
+ edit.set_focus()
214
+ edit.click_input()
215
+ send_keys('^a{DELETE}')
216
+ send_keys("3", with_spaces=True)
217
+
218
+ await worker_sleep(3)
219
+
220
+ # Marcar filial
221
+ imagem_alvo = "assets\\geracao_bal_filial\\btn_selec_uma_filial.png"
222
+
223
+ btn_sect_uma = pyautogui.locateCenterOnScreen(imagem_alvo, confidence=0.9) # requer opencv-python
224
+ if btn_sect_uma: # se achou, clica
225
+ pyautogui.click(btn_sect_uma)
226
+
227
+ btn_ok = dlg.child_window(class_name="TBitBtn", title="&OK").click()
228
+
229
+ # aguarda até a janela "Gera Arquivo CSV (Excel)" existir (ou ficar visível)
230
+ csv_win = Desktop(backend="win32").window(title="Gera Arquivo CSV (Excel)")
231
+ csv_win.wait('exists', timeout=3600)
232
+
233
+ app_csv = Application(backend="win32").connect(title="Gera Arquivo CSV (Excel)")
234
+ dlg_csv = app_csv.window(title="Gera Arquivo CSV (Excel)")
235
+ edit = dlg_csv.child_window(class_name="Edit", found_index=0)
236
+ # Tenta via WM_SETTEXT (mais estável)
237
+ try:
238
+ periodo_inicial = periodo_inicial.replace("/","")
239
+ periodo_final = periodo_final.replace("/","")
240
+ edit.set_focus()
241
+ edit.set_edit_text("") # limpa
242
+ edit.set_edit_text(fr"C:\Users\automatehub\Downloads\balancete_{periodo_inicial}_{periodo_final}_{filial}")
243
+ except Exception:
244
+ # Fallback: digita como teclado
245
+ edit.set_focus()
246
+ edit.click_input()
247
+ send_keys('^a{DELETE}')
248
+ send_keys(fr"C:\Users\automatehub\Downloads\balancete_{periodo_inicial}_{periodo_final}_{filial}", with_spaces=True)
249
+
250
+ # Clicar em salvar
251
+ app = Application(backend="win32").connect(title="Gera Arquivo CSV (Excel)", timeout=10)
252
+ dlg = app.window(title ="Gera Arquivo CSV (Excel)")
253
+ btn_salvar = dlg.child_window(class_name="Button", found_index=0).click()
254
+
255
+ await worker_sleep(3)
256
+
257
+ # Janela confirmação clicar em OK
258
+ app = Application(backend="win32").connect(title="Informação", timeout=10)
259
+ dlg = app.window(title ="Informação")
260
+ btn_ok = dlg.child_window(class_name="Button", found_index=0).click()
261
+
262
+ console.print("Arquivo salvo com sucesso...\n")
263
+ await worker_sleep(3)
264
+ path_to_txt = fr"C:\Users\automatehub\Downloads\balancete_{periodo_inicial}_{periodo_final}_{filial}"
265
+
266
+ with open(f"{path_to_txt}.csv", 'rb') as file:
267
+ file_bytes = io.BytesIO(file.read())
268
+
269
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
270
+ desArquivo = f"balancete_{periodo_inicial}_{periodo_final}_{filial}.csv"
271
+ try:
272
+ await send_file(historico_id, desArquivo, "csv", file_bytes, file_extension="csv")
273
+ os.remove(path_to_txt+".csv")
274
+ return RpaRetornoProcessoDTO(
275
+ sucesso=True,
276
+ retorno="Balancete gerado com sucesso",
277
+ status=RpaHistoricoStatusEnum.Sucesso
278
+ )
279
+ except Exception as e:
280
+ result = f"Arquivo balancete gerado com sucesso, porém gerou erro ao realizar o envio para o backoffice {e} - Arquivo ainda salvo na dispositivo utilizado no diretório {path_to_txt}!"
281
+ console.print(result, style="bold red")
282
+ return RpaRetornoProcessoDTO(
283
+ sucesso=False,
284
+ retorno=result,
285
+ status=RpaHistoricoStatusEnum.Falha,
286
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
287
+ )
288
+
289
+ except Exception as erro:
290
+ return RpaRetornoProcessoDTO(
291
+ sucesso=False,
292
+ retorno=f"Erro durante o processo integração contabil, erro : {erro}",
293
+ status=RpaHistoricoStatusEnum.Falha,
294
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
295
+ )
@@ -105,6 +105,9 @@ from worker_automate_hub.tasks.jobs.opex_capex import (
105
105
  from worker_automate_hub.tasks.jobs.entrada_de_notas_22 import (
106
106
  entrada_de_notas_22,
107
107
  )
108
+ from worker_automate_hub.tasks.jobs.geracao_balancetes_filial import (
109
+ geracao_balancetes_filial,
110
+ )
108
111
 
109
112
 
110
113
  task_definitions = {
@@ -212,7 +215,8 @@ task_definitions = {
212
215
  "16debe45-3520-4f63-acfe-ef0e8784fcab": extracao_saldo_estoque,
213
216
  "9cbc6016-7c0e-4a3a-8ee9-fb9dc4b35e33": extracao_saldo_estoque_fiscal,
214
217
  "07072711-c9d0-49e4-b180-530cecbe0728": opex_capex,
215
- "98bc6679-2e6b-4757-9fdc-b27eebd98f54": entrada_de_notas_22
218
+ "98bc6679-2e6b-4757-9fdc-b27eebd98f54": entrada_de_notas_22,
219
+ "d7794924-0330-453c-b79b-74f3c8991562": geracao_balancetes_filial
216
220
  }
217
221
 
218
222
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: worker-automate-hub
3
- Version: 0.5.815
3
+ Version: 0.5.816
4
4
  Summary: Worker Automate HUB é uma aplicação para automatizar rotinas de RPA nos ambientes Argenta.
5
5
  Author: Joel Paim
6
6
  Requires-Python: >=3.12,<4.0
@@ -1,7 +1,7 @@
1
1
  worker_automate_hub/__init__.py,sha256=LV28uQvBfpPIqudGIMJmVB8E941MjXHcu8DMoX5n8AM,25
2
2
  worker_automate_hub/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
3
  worker_automate_hub/api/ahead_service.py,sha256=QbNrZf9q7fS0s-S5fZVytqC7dINi9u2f6aB6SDrGVVA,2231
4
- worker_automate_hub/api/client.py,sha256=QY6OgIIkkB1bSJikRfYdDhTm6Wza_J3pGdrG4Q_jW_g,32003
4
+ worker_automate_hub/api/client.py,sha256=gVSUj9J9eXXQjuUscyIBEEZadLVjEiTuU2BoWxPUqnE,32082
5
5
  worker_automate_hub/api/datalake_service.py,sha256=qw_N_OOgDKDuPbI-fdYkWWTlT4CUtFTl0VVlZ0fLM-M,3001
6
6
  worker_automate_hub/api/helpers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
7
  worker_automate_hub/api/helpers/api_helpers.py,sha256=SkheO2fXexeh-a4shr8Qzsz_kZhuSG0DJ7kbODctRbM,3696
@@ -81,6 +81,7 @@ worker_automate_hub/tasks/jobs/fidc_remessa_cobranca_cnab240.py,sha256=CuyTBQOR8
81
81
  worker_automate_hub/tasks/jobs/fidc_retorno_cobranca.py,sha256=mmBW7KetUeRjiZkjnrxMKGX32io3YLZ8KGaY5_o7new,11891
82
82
  worker_automate_hub/tasks/jobs/geracao_aprovacao_pedidos.py,sha256=QzK2aG5d9pmFbb8cTaNm3LWf5NMkmCvBkgo70gcLu0c,14781
83
83
  worker_automate_hub/tasks/jobs/geracao_aprovacao_pedidos_novo.py,sha256=4Rtm2uCfA6tZ-KW6aunKug7reTqbBX69CCBZCBnwbYc,21856
84
+ worker_automate_hub/tasks/jobs/geracao_balancetes_filial.py,sha256=or2EpVk8XSJmS346Z2UKjKZnbsrlfrjV7fm0y5c_Ioc,12162
84
85
  worker_automate_hub/tasks/jobs/integracao_contabil.py,sha256=psoIU0tjtTJq2W8aGXjXrfkAOYlIpUtHZyNolI7dp-0,16263
85
86
  worker_automate_hub/tasks/jobs/integracao_contabil_generica.py,sha256=cA41rQlqTkNo9XD1QM0xtSDhJQoWJenvNuA_WePW4OM,22048
86
87
  worker_automate_hub/tasks/jobs/lancamento_pis_cofins.py,sha256=0mlu-oPwRd9qCocB-6tWsEI0-wd48mkBJn5juYqOAX8,40788
@@ -92,7 +93,7 @@ worker_automate_hub/tasks/jobs/opex_capex.py,sha256=KnZymjtYtRO0EmNAk12xA9Hx9XlS
92
93
  worker_automate_hub/tasks/jobs/playground.py,sha256=7vWDg9DwToHwGJ6_XOa8TQ6LmfRV5Qz2TaOV3q3P9sA,1918
93
94
  worker_automate_hub/tasks/jobs/sped_fiscal.py,sha256=rinyHCF7QYHUc6oWACJgnQiAv0S-_Fel9Z0bImiHUoM,31064
94
95
  worker_automate_hub/tasks/jobs/transferencias.py,sha256=5TIktufkvUPnVTR2gf7GFQJ5KQP6PWnmoWiE08WiVDQ,46191
95
- worker_automate_hub/tasks/task_definitions.py,sha256=AKzuSb5CiNu97-9V_Ykb2jmXXNenOLiTFeBT3Pw9chI,12815
96
+ worker_automate_hub/tasks/task_definitions.py,sha256=VD1xq76A_ai_3DHrnCy6aYG6HY_vqfs0ntS_QvloVEI,12994
96
97
  worker_automate_hub/tasks/task_executor.py,sha256=F5ngJLGz7vbUrX-batUlt3FFwiCE8denFmtTTLaE77I,6044
97
98
  worker_automate_hub/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
98
99
  worker_automate_hub/utils/env.py,sha256=TacQjGRO7PUNpttrhTAc5Gnegaiysl2Knsv1P8qfkfs,57
@@ -103,7 +104,7 @@ worker_automate_hub/utils/updater.py,sha256=en2FCGhI8aZ-JNP3LQm64NJDc4awCNW7UhbV
103
104
  worker_automate_hub/utils/util.py,sha256=p15z2pqyV-fPD8lL6ulurecsWQw9XpKPFf_xEr4U5lM,210781
104
105
  worker_automate_hub/utils/utils_nfe_entrada.py,sha256=F7jk95LpDwl5WfaQXahCA5yDdnySnWdctDqczHXwGqE,38195
105
106
  worker_automate_hub/worker.py,sha256=zEnYUrm5kY2cHbbee15QJkwkx4euD2SB2zRvUIbjS90,6850
106
- worker_automate_hub-0.5.815.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
107
- worker_automate_hub-0.5.815.dist-info/METADATA,sha256=OrtUVWxNu_6_tsaoS3JTHEkxvj0nGcMKMSl9pBWuq04,3100
108
- worker_automate_hub-0.5.815.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
109
- worker_automate_hub-0.5.815.dist-info/RECORD,,
107
+ worker_automate_hub-0.5.816.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
108
+ worker_automate_hub-0.5.816.dist-info/METADATA,sha256=q_fwYlv9j6kNau9BmXIZJQKDLZd39Tpj1FUQc8rCMiY,3100
109
+ worker_automate_hub-0.5.816.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
110
+ worker_automate_hub-0.5.816.dist-info/RECORD,,