worker-automate-hub 0.5.814__tar.gz → 0.5.816__tar.gz

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.

Files changed (109) hide show
  1. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/PKG-INFO +1 -1
  2. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/pyproject.toml +1 -1
  3. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/client.py +2 -0
  4. worker_automate_hub-0.5.816/worker_automate_hub/tasks/jobs/geracao_balancetes_filial.py +295 -0
  5. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/integracao_contabil_generica.py +57 -81
  6. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/task_definitions.py +5 -1
  7. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/README.md +0 -0
  8. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/__init__.py +0 -0
  9. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/__init__.py +0 -0
  10. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/ahead_service.py +0 -0
  11. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/datalake_service.py +0 -0
  12. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/helpers/__init__.py +0 -0
  13. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/helpers/api_helpers.py +0 -0
  14. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/rdp_service.py +0 -0
  15. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/rpa_fila_service.py +0 -0
  16. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/rpa_historico_service.py +0 -0
  17. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/api/webhook_service.py +0 -0
  18. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/cli.py +0 -0
  19. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/config/__init__.py +0 -0
  20. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/config/settings.py +0 -0
  21. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/config.py +0 -0
  22. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/core/so_manipulation.py +0 -0
  23. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/__init__.py +0 -0
  24. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/deprecation.py +0 -0
  25. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/rate_limit.py +0 -0
  26. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/repeat.py +0 -0
  27. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/retry.py +0 -0
  28. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/singleton.py +0 -0
  29. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/decorators/timeit.py +0 -0
  30. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/__init__.py +0 -0
  31. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/__init__.py +0 -0
  32. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/rpa_configuracao.py +0 -0
  33. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/rpa_fila.py +0 -0
  34. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/rpa_historico.py +0 -0
  35. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/rpa_processo.py +0 -0
  36. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dao/rpa_robo.py +0 -0
  37. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/__init__.py +0 -0
  38. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/rpa_historico_request_dto.py +0 -0
  39. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/rpa_processo_entrada_dto.py +0 -0
  40. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/rpa_processo_rdp_dto.py +0 -0
  41. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/rpa_sap_dto.py +0 -0
  42. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/models/dto/rpa_sistema_dto.py +0 -0
  43. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/__init__.py +0 -0
  44. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/__init__.py +0 -0
  45. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/abertura_livros_fiscais.py +0 -0
  46. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/coleta_dje_process.py +0 -0
  47. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/conexao_rdp.py +0 -0
  48. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/cte_manual.py +0 -0
  49. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/cte_xml.py +0 -0
  50. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/descartes.py +0 -0
  51. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/devolucao_ctf.py +0 -0
  52. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/devolucao_ctf_35.py +0 -0
  53. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/devolucao_prazo_a_faturar.py +0 -0
  54. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_estadual_go.py +0 -0
  55. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_estadual_main.py +0 -0
  56. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_estadual_mt.py +0 -0
  57. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_estadual_sc.py +0 -0
  58. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_estadual_sp.py +0 -0
  59. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/ecac_federal.py +0 -0
  60. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_cte_1353.py +0 -0
  61. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_cte_333.py +0 -0
  62. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_15.py +0 -0
  63. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_16.py +0 -0
  64. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_207.py +0 -0
  65. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_22.py +0 -0
  66. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_32.py +0 -0
  67. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_33.py +0 -0
  68. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_34.py +0 -0
  69. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_36.py +0 -0
  70. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_37.py +0 -0
  71. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_39.py +0 -0
  72. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_500.py +0 -0
  73. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_503.py +0 -0
  74. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_505.py +0 -0
  75. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_7139.py +0 -0
  76. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_9.py +0 -0
  77. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/entrada_de_notas_9000.py +0 -0
  78. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/exemplo_processo.py +0 -0
  79. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/extracao_fechamento_contabil.py +0 -0
  80. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/extracao_fechamento_emsys.py +0 -0
  81. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/extracao_saldo_estoque.py +0 -0
  82. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/extracao_saldo_estoque_fiscal.py +0 -0
  83. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/fechar_conexao_rdp.py +0 -0
  84. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/fidc_exportacao_docs_portal_b2b.py +0 -0
  85. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/fidc_gerar_nosso_numero.py +0 -0
  86. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/fidc_remessa_cobranca_cnab240.py +0 -0
  87. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/fidc_retorno_cobranca.py +0 -0
  88. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/geracao_aprovacao_pedidos.py +0 -0
  89. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/geracao_aprovacao_pedidos_novo.py +0 -0
  90. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/integracao_contabil.py +0 -0
  91. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/lancamento_pis_cofins.py +0 -0
  92. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/lancamento_rateio.py +0 -0
  93. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/login_emsys.py +0 -0
  94. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/login_emsys_versao_especifica.py +0 -0
  95. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/notas_faturamento_sap.py +0 -0
  96. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/opex_capex.py +0 -0
  97. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/playground.py +0 -0
  98. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/sped_fiscal.py +0 -0
  99. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/jobs/transferencias.py +0 -0
  100. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/tasks/task_executor.py +0 -0
  101. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/__init__.py +0 -0
  102. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/env.py +0 -0
  103. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/get_creds_gworkspace.py +0 -0
  104. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/logger.py +0 -0
  105. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/toast.py +0 -0
  106. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/updater.py +0 -0
  107. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/util.py +0 -0
  108. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/utils/utils_nfe_entrada.py +0 -0
  109. {worker_automate_hub-0.5.814 → worker_automate_hub-0.5.816}/worker_automate_hub/worker.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: worker-automate-hub
3
- Version: 0.5.814
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,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "worker-automate-hub"
3
- version = "0.5.814"
3
+ version = "0.5.816"
4
4
  description = "Worker Automate HUB é uma aplicação para automatizar rotinas de RPA nos ambientes Argenta."
5
5
  authors = ["Joel Paim"]
6
6
  readme = "README.md"
@@ -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
+ )
@@ -202,7 +202,7 @@ async def integracao_contabil_generica(
202
202
 
203
203
  # console.print("Selecionando item do campo origem...")
204
204
  uuid_processo = task.uuidProcesso
205
- caminho_imagem = os.path.join(ASSETS_PATH_BASE, "integracao_contabil", f"{uuid_processo}.png")
205
+ caminho_imagem = f"assets\\integracao_contabil\\{uuid_processo}.png"
206
206
 
207
207
  await metodo_selecao_origem_especial()
208
208
  await localizar_e_clicar(caminho_imagem) # main_window.set_focus()
@@ -258,7 +258,7 @@ async def integracao_contabil_generica(
258
258
  console.print("Verificar se existem lotes")
259
259
  try:
260
260
  # Verifica mensagem sem lote pra integrar
261
- imagem_alvo = os.path.join(ASSETS_PATH_BASE, "integracao_contabil", "sem_lote.png")
261
+ imagem_alvo = "assets\\integracao_contabil\\sem_lote.png"
262
262
 
263
263
  localizacao = pyautogui.locateOnScreen(imagem_alvo, confidence=0.9)
264
264
 
@@ -297,7 +297,7 @@ async def integracao_contabil_generica(
297
297
  await worker_sleep(5)
298
298
 
299
299
  try:
300
- imagem_finalizada = os.path.join(ASSETS_PATH_BASE, "integracao_contabil", "pesquisa_finalizada.png")
300
+ imagem_finalizada = "assets\\integracao_contabil\\pesquisa_finalizada.png"
301
301
 
302
302
  if not os.path.exists(imagem_finalizada):
303
303
  raise FileNotFoundError(
@@ -399,9 +399,9 @@ async def integracao_contabil_generica(
399
399
  total_debito = numeros[1].window_text()
400
400
  total_credito = numeros[2].window_text()
401
401
 
402
- console.print("Diferença:", diferenca)
403
- console.print("Total Débito:", total_debito)
404
- console.print("Total Crédito:", total_credito)
402
+ print("Diferença:", diferenca)
403
+ print("Total Débito:", total_debito)
404
+ print("Total Crédito:", total_credito)
405
405
 
406
406
  if diferenca > "0,00":
407
407
  clicou = True
@@ -433,16 +433,19 @@ async def integracao_contabil_generica(
433
433
 
434
434
  await worker_sleep(5)
435
435
 
436
- # --- AJUSTE: retorno de SUCESSO quando detectar integracao_sucesso.png
437
- assets_int_cont = os.path.join(ASSETS_PATH_BASE, "integracao_contabil")
436
+ assets_int_cont = "assets\\integracao_contabil\\"
438
437
  err_dict = {
439
- os.path.join(assets_int_cont, "erro_duplicidade.png"): "Integração não realizada. Erro de Duplicidade localizado enquanto finalizava a integração, contate o suporte do Emsys.",
440
- os.path.join(assets_int_cont, "conta_indefinida_error.png"): "Integração não realizada. Conta contábil indefinida no sistema.",
441
- os.path.join(assets_int_cont, "lote_sem_complemento_error.png"): "Integração não realizada. Lote encontrado sem complemento obrigatório.",
442
- os.path.join(assets_int_cont, "diferenca_cred_deb.png"): "Integração não realizada. Existem diferença em lotes consistentes, por favor verificar.",
443
- os.path.join(assets_int_cont, "integracao_sucesso.png"): "Integração Finalizada com Sucesso.",
438
+ assets_int_cont
439
+ + "erro_duplicidade.png": "Integração não realizada. Erro de Duplicidade localizado enquanto finalizava a integração, contate o suporte do Emsys.",
440
+ assets_int_cont
441
+ + "conta_indefinida_error.png": "Integração não realizada. Conta contábil indefinida no sistema.",
442
+ assets_int_cont
443
+ + "lote_sem_complemento_error.png": "Integração não realizada. Lote encontrado sem complemento obrigatório.",
444
+ assets_int_cont
445
+ + "diferenca_cred_deb.png": "Integração não realizada. Existem diferença em lotes consistentes, por favor verificar.",
446
+ assets_int_cont
447
+ + "integracao_sucesso.png": "Integração Finalizada com Sucesso.",
444
448
  }
445
-
446
449
  # Aguardar finalizar
447
450
  while True:
448
451
  try:
@@ -451,56 +454,23 @@ async def integracao_contabil_generica(
451
454
  )
452
455
  msg_box = app["TMsgBox"]
453
456
 
454
- # Verifica por imagens de SUCESSO/ERRO
457
+ # Antes de qualquer coisa, verifica por imagem de erro
455
458
  for img_path, mensagem in err_dict.items():
456
459
  try:
457
- found = pyautogui.locateOnScreen(img_path, confidence=0.90)
458
- except Exception:
459
- found = None
460
+ err = pyautogui.locateOnScreen(img_path, confidence=0.90)
461
+ except:
462
+ continue
460
463
 
461
- if found:
462
- # Caso SUCESSO
463
- if img_path.endswith("integracao_sucesso.png"):
464
+ if err:
465
+ if "integracao_sucesso.png" in img_path:
464
466
  console.print(f"[green]{mensagem}[/green]")
465
- # fecha a TMsgBox se estiver aberta (best-effort)
466
- try:
467
- msg_box.child_window(class_name="TBitBtn", found_index=0).click_input()
468
- except:
469
- pass
470
-
471
- # Se integrou com 'Lotes Consistentes' marcados, é FALHA
472
- if lotesMarcados:
473
- try:
474
- # busca novamente o checkbox para garantir escopo
475
- cb = dlg.child_window(title="Lotes Consistentes", class_name="TCheckBox")
476
- if cb.exists() and cb.is_enabled() and cb.is_visible():
477
- cb.click_input()
478
- print("Checkbox 'Lotes Consistentes' desmarcado com sucesso.")
479
- except Exception as e:
480
- print(f"Não foi possível desmarcar checkbox: {e}")
481
-
482
- time.sleep(5)
483
- return RpaRetornoProcessoDTO(
484
- sucesso=False,
485
- retorno="Integração realizada, porém, existem LOTES INCONSISTENTES.",
486
- status=RpaHistoricoStatusEnum.Falha,
487
- tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)],
488
- )
489
-
490
- # Se não estava marcado, aí sim é sucesso
491
- return RpaRetornoProcessoDTO(
492
- sucesso=True,
493
- retorno=mensagem,
494
- status=RpaHistoricoStatusEnum.Sucesso,
495
- tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
496
- )
497
-
498
- # Demais imagens tratadas como ERRO
467
+ msg_box.child_window(
468
+ class_name="TBitBtn", found_index=0
469
+ ).click_input()
470
+ break
471
+
499
472
  console.print(f"[red]Erro encontrado:[/red] {mensagem}")
500
- try:
501
- msg_box.child_window(class_name="TBitBtn", found_index=0).click_input()
502
- except:
503
- pass
473
+
504
474
  return RpaRetornoProcessoDTO(
505
475
  sucesso=False,
506
476
  retorno=mensagem,
@@ -510,16 +480,19 @@ async def integracao_contabil_generica(
510
480
 
511
481
  await worker_sleep(1)
512
482
 
513
- # Se nenhuma imagem foi encontrada, tenta só fechar a TMsgBox (se existir) e sai
514
483
  try:
515
484
  app = Application(backend="win32").connect(
516
485
  class_name="TMsgBox", found_index=0
517
486
  )
518
487
  main_window = app["TMsgBox"]
519
- main_window.child_window(class_name="TBitBtn", found_index=0).click_input()
488
+ main_window.child_window(
489
+ class_name="TBitBtn", found_index=0
490
+ ).click_input()
520
491
  break
521
492
  except ElementNotFoundError:
522
- console.print("[yellow]Janela TMsgBox ainda não visível.[/yellow]")
493
+ console.print(
494
+ "[yellow]Janela TMsgBox ainda não visível.[/yellow]"
495
+ )
523
496
  break
524
497
 
525
498
  except ElementNotFoundError:
@@ -530,23 +503,6 @@ async def integracao_contabil_generica(
530
503
 
531
504
  await worker_sleep(1)
532
505
 
533
- try:
534
- app = Application(backend="win32").connect(
535
- class_name="TMsgBox", found_index=0
536
- )
537
- main_window = app["TMsgBox"]
538
- main_window.child_window(class_name="TBitBtn", found_index=0).click_input()
539
- time.sleep(5)
540
- break
541
- except ElementNotFoundError:
542
- console.print("[yellow]Janela TMsgBox ainda não visível.[/yellow]")
543
-
544
- except Exception as e:
545
- print(f"Erro inesperado ao verificar janela de confirmação: {e}")
546
- break
547
-
548
- await worker_sleep(1)
549
-
550
506
  try:
551
507
  app = Application(backend="win32").connect(
552
508
  class_name="TMsgBox", found_index=0
@@ -560,7 +516,28 @@ async def integracao_contabil_generica(
560
516
  except ElementNotFoundError:
561
517
  console.print("[yellow]Janela TMsgBox ainda não visível.[/yellow]")
562
518
 
563
-
519
+ if lotesMarcados:
520
+ if (
521
+ checkbox.exists()
522
+ and checkbox.is_enabled()
523
+ and checkbox.is_visible()
524
+ ):
525
+ checkbox.click_input()
526
+ print("Checkbox 'Lotes Consistentes' desmarcado com sucesso.")
527
+ time.sleep(5)
528
+ return RpaRetornoProcessoDTO(
529
+ sucesso=False,
530
+ retorno=f"Integração realizada, porém, existem LOTES INCONSISTENTES.",
531
+ status=RpaHistoricoStatusEnum.Falha,
532
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)],
533
+ )
534
+ else:
535
+ return RpaRetornoProcessoDTO(
536
+ sucesso=True,
537
+ retorno=f"Sucesso ao executar processo de integracao contabil",
538
+ status=RpaHistoricoStatusEnum.Sucesso,
539
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
540
+ )
564
541
  except Exception as erro:
565
542
  return RpaRetornoProcessoDTO(
566
543
  sucesso=False,
@@ -576,4 +553,3 @@ async def integracao_contabil_generica(
576
553
  status=RpaHistoricoStatusEnum.Falha,
577
554
  tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
578
555
  )
579
-
@@ -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