worker-automate-hub 0.5.762__py3-none-any.whl → 0.5.764__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.
@@ -1,9 +1,10 @@
1
1
  import asyncio
2
2
  import os
3
3
  from datetime import datetime
4
- from pywinauto import Application, timings, findwindows
4
+ from pywinauto import Application, timings, findwindows, Desktop
5
5
  import sys
6
6
  import io
7
+ import win32gui
7
8
  # sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
8
9
 
9
10
  from worker_automate_hub.models.dto.rpa_historico_request_dto import (
@@ -114,10 +115,13 @@ async def extracao_saldo_estoque(task: RpaProcessoEntradaDTO):
114
115
  tentativa = 1
115
116
  sucesso = False
116
117
 
118
+ # defina caminho_arquivo ANTES para não ficar indefinido
119
+ caminho_arquivo = rf"C:\Users\automatehub\Downloads\saldo_estoque_{periodo_format}_{filial}.xlsx"
120
+
117
121
  while tentativa <= max_tentativas and not sucesso:
118
122
  console.print(f"Tentativa {tentativa} de {max_tentativas}", style="bold cyan")
119
123
 
120
- # 1) Abrir o picker de formatos pelo botão (imagem)
124
+ # 1) Abrir o picker pelo botão (imagem)
121
125
  console.print("Procurando botão de salvar (imagem)...", style="bold cyan")
122
126
  caminho_img = r'assets\\extracao_relatorios\\btn_salvar.png'
123
127
  if os.path.isfile(caminho_img):
@@ -132,40 +136,92 @@ async def extracao_saldo_estoque(task: RpaProcessoEntradaDTO):
132
136
 
133
137
  await worker_sleep(8)
134
138
 
135
- # 2) Selecionar formato "Excel" na janela TFrmRelatorioFormato
139
+ # 2) Selecionar formato Excel (desambiguando múltiplas TFrmRelatorioFormato)
136
140
  console.print("Selecionando formato Excel...", style="bold cyan")
137
141
  try:
138
- app_fmt = Application().connect(class_name="TFrmRelatorioFormato", timeout=10)
139
- win_fmt = app_fmt["TFrmRelatorioFormato"]
140
- win_fmt.wait("visible", timeout=10)
142
+ desktop = Desktop(backend="win32")
143
+
144
+ # Liste todas as visíveis
145
+ wins_visiveis = desktop.windows(class_name="TFrmRelatorioFormato", visible_only=True)
146
+ if not wins_visiveis:
147
+ raise RuntimeError("Janela de formato não apareceu.")
148
+
149
+ # 2.1) Tente a janela em foco (foreground)
150
+ h_fore = win32gui.GetForegroundWindow()
151
+ alvo = None
152
+ for w in wins_visiveis:
153
+ if w.handle == h_fore:
154
+ alvo = w
155
+ break
156
+
157
+ # 2.2) Se não estiver em foco, pegue a que contém um TComboBox (a 'Configuração para Salvar arq...')
158
+ if alvo is None:
159
+ candidatos = []
160
+ for w in wins_visiveis:
161
+ try:
162
+ if w.child_window(class_name="TComboBox").exists(timeout=0.8):
163
+ candidatos.append(w)
164
+ except Exception:
165
+ pass
166
+ if candidatos:
167
+ alvo = candidatos[-1] # a mais recente
168
+ else:
169
+ alvo = wins_visiveis[-1] # fallback
170
+
171
+ # Trabalhe via WindowSpecification
172
+ spec_fmt = desktop.window(handle=alvo.handle)
173
+ spec_fmt.wait("visible", timeout=10)
174
+ win_fmt = spec_fmt.wrapper_object()
175
+ win_fmt.set_focus()
176
+
177
+ # Acessar o ComboBox
178
+ try:
179
+ combo_spec = spec_fmt.child_window(class_name="TComboBox")
180
+ except Exception:
181
+ combo_spec = spec_fmt.child_window(control_type="ComboBox")
182
+ combo_spec.wait("exists enabled", timeout=10)
183
+ combo = combo_spec.wrapper_object()
141
184
 
142
- combo = win_fmt.ComboBox
143
185
  textos = combo.texts()
144
186
  console.print(f"Itens do ComboBox: {textos}", style="bold yellow")
145
187
 
146
- # Se souber o índice correto, mantenha. Caso contrário, tente por texto contendo 'Excel'
188
+ # Seleção por índice conhecido; fallback por texto
147
189
  try:
148
190
  combo.select(8)
149
191
  except Exception:
150
- alvo = None
192
+ alvo_idx = None
151
193
  for i, t in enumerate(textos):
152
194
  if "EXCEL" in str(t).upper() or "XLSX" in str(t).upper():
153
- alvo = i
195
+ alvo_idx = i
154
196
  break
155
- if alvo is not None:
156
- combo.select(alvo)
157
- else:
197
+ if alvo_idx is None:
158
198
  console.print("Não foi possível localizar a opção de Excel no ComboBox.", style="bold red")
159
199
  tentativa += 1
160
200
  await worker_sleep(2)
161
201
  continue
202
+ combo.select(alvo_idx)
162
203
 
163
204
  await worker_sleep(1)
164
205
 
165
- # Botão OK/Confirmar na janela de formato
166
- # Em muitos Delphi VCL, TBitBtn com found_index=1 costuma ser OK.
167
- win_fmt.child_window(class_name="TBitBtn", found_index=1).wait("enabled", timeout=5)
168
- win_fmt.child_window(class_name="TBitBtn", found_index=1).click_input()
206
+ # Clique em OK
207
+ btn_ok_spec = spec_fmt.child_window(class_name="TBitBtn", found_index=1)
208
+ btn_ok_spec.wait("enabled", timeout=5)
209
+ btn_ok_spec.click_input()
210
+
211
+ # Aguarde a janela de formato desaparecer
212
+ try:
213
+ spec_fmt.wait_not("visible", timeout=10)
214
+ except Exception:
215
+ pass
216
+
217
+ # Feche possíveis duplicatas remanescentes (defensivo)
218
+ for w in desktop.windows(class_name="TFrmRelatorioFormato", visible_only=True):
219
+ if w.handle != alvo.handle:
220
+ try:
221
+ w.close()
222
+ except Exception:
223
+ pass
224
+
169
225
  except Exception as e:
170
226
  console.print(f"Falha ao selecionar formato: {e}", style="bold red")
171
227
  tentativa += 1
@@ -177,19 +233,17 @@ async def extracao_saldo_estoque(task: RpaProcessoEntradaDTO):
177
233
  # 3) Janela "Salvar para arquivo"
178
234
  console.print("Abrindo janela de salvar arquivo...", style="bold cyan")
179
235
  try:
180
- app_save = Application().connect(title_re="Salvar para arquivo", timeout=30)
181
- win_save = app_save.window(title_re="Salvar para arquivo")
182
- win_save.wait("visible", timeout=30)
236
+ app_save = Application(backend="win32").connect(title_re="Salvar para arquivo|Salvar como|Save As", timeout=30)
237
+ spec_save = app_save.window(title_re="Salvar para arquivo|Salvar como|Save As")
238
+ spec_save.wait("visible", timeout=30)
239
+ win_save = spec_save.wrapper_object()
183
240
  except Exception as e:
184
241
  console.print(f"Não achou a janela 'Salvar para arquivo': {e}", style="bold red")
185
242
  tentativa += 1
186
243
  await worker_sleep(3)
187
244
  continue
188
245
 
189
- # Caminho do arquivo a salvar
190
- caminho_arquivo = rf"C:\Users\automatehub\Downloads\saldo_estoque_{periodo_format}_{filial}.xlsx"
191
-
192
- # Se já existe, removemos para evitar pop-up de confirmação
246
+ # 3.1) Remover arquivo pré-existente
193
247
  if os.path.exists(caminho_arquivo):
194
248
  try:
195
249
  os.remove(caminho_arquivo)
@@ -197,27 +251,32 @@ async def extracao_saldo_estoque(task: RpaProcessoEntradaDTO):
197
251
  except Exception as e:
198
252
  console.print(f"Não foi possível remover o arquivo existente: {e}", style="bold red")
199
253
 
254
+ # 3.2) Preencher nome e salvar
200
255
  try:
201
- # Campo "Nome" (Edit, control_id=1148)
202
- campo_nome = win_save.child_window(class_name="Edit", control_id=1148).wrapper_object()
256
+ campo_spec = spec_save.child_window(class_name="Edit", control_id=1148)
257
+ campo_spec.wait("exists enabled visible", timeout=10)
258
+ campo_nome = campo_spec.wrapper_object()
203
259
  campo_nome.set_focus()
204
- # limpa conteúdo
205
260
  try:
206
261
  campo_nome.set_edit_text("")
207
262
  except Exception:
208
- # fallback limpando com Ctrl+A + Delete
209
263
  campo_nome.type_keys("^a{DELETE}", pause=0.02)
210
264
 
211
- # digita caminho
212
265
  campo_nome.type_keys(caminho_arquivo, with_spaces=True, pause=0.01)
213
266
  console.print(f"Arquivo configurado para: {caminho_arquivo}", style="bold green")
214
267
 
215
268
  await worker_sleep(1)
216
269
 
217
- # Botão Salvar (primeiro Button)
218
- btn_salvar = win_save.child_window(class_name="Button", found_index=0)
219
- btn_salvar.wait("enabled", timeout=10)
220
- btn_salvar.click_input()
270
+ btn_salvar_spec = spec_save.child_window(class_name="Button", found_index=0)
271
+ btn_salvar_spec.wait("enabled", timeout=10)
272
+ btn_salvar_spec.click_input()
273
+
274
+ # Esperar a janela sumir
275
+ try:
276
+ spec_save.wait_not("visible", timeout=15)
277
+ except Exception:
278
+ pass
279
+
221
280
  except Exception as e:
222
281
  console.print(f"Erro ao confirmar salvar: {e}", style="bold red")
223
282
  tentativa += 1
@@ -226,32 +285,27 @@ async def extracao_saldo_estoque(task: RpaProcessoEntradaDTO):
226
285
 
227
286
  await worker_sleep(2)
228
287
 
229
- # 3.1) Tratar confirmação de sobrescrita, se aparecer
288
+ # 3.3) Confirmar sobrescrita (se houver)
230
289
  try:
231
- # Pode vir em PT/EN dependendo do SO
232
- # Título comum: "Confirm Save As" (EN) ou "Confirmar Salvar Como" (PT)
233
- try:
234
- app_conf = Application().connect(title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As", timeout=3)
235
- win_conf = app_conf.window(title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As")
236
- win_conf.wait("visible", timeout=3)
237
- # Botões costumam ser "Sim"/"Yes" como class_name="Button"
238
- # Tente o primeiro botão (Yes/Sim)
239
- win_conf.child_window(class_name="Button", found_index=0).click_input()
240
- console.print("Confirmação de sobrescrita respondida.", style="bold yellow")
241
- except Exception:
242
- pass
290
+ app_conf = Application(backend="win32").connect(
291
+ title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As", timeout=3
292
+ )
293
+ spec_conf = app_conf.window(title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As")
294
+ spec_conf.wait("visible", timeout=3)
295
+ spec_conf.child_window(class_name="Button", found_index=0).click_input()
296
+ console.print("Confirmação de sobrescrita respondida.", style="bold yellow")
243
297
  except Exception:
244
298
  pass
245
299
 
246
300
  await worker_sleep(2)
247
301
 
248
- # 4) Aguardar o processamento/Printing encerrar
302
+ # 4) Aguardar 'Printing' (se existir)
249
303
  console.print("Aguardando finalização do processo de impressão/salvamento...", style="bold cyan")
250
304
  try:
251
- app_print = Application().connect(title_re="Printing", timeout=5)
252
- win_print = app_print.window(title_re="Printing")
305
+ app_print = Application(backend="win32").connect(title_re="Printing", timeout=5)
306
+ spec_print = app_print.window(title_re="Printing")
253
307
  try:
254
- win_print.wait_not("visible", timeout=60)
308
+ spec_print.wait_not("visible", timeout=60)
255
309
  console.print("Janela 'Printing' fechada.", style="bold green")
256
310
  except Exception:
257
311
  console.print("Janela 'Printing' não fechou no tempo esperado. Seguindo.", style="bold yellow")
@@ -1,9 +1,10 @@
1
1
  import asyncio
2
2
  import os
3
3
  from datetime import datetime
4
- from pywinauto import Application, timings, findwindows, keyboard
4
+ from pywinauto import Application, timings, findwindows, keyboard, Desktop
5
5
  import sys
6
6
  import io
7
+ import win32gui
7
8
 
8
9
  # sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
9
10
 
@@ -59,9 +60,7 @@ async def extracao_saldo_estoque_fiscal(
59
60
  # Fecha a instancia do emsys - caso esteja aberta
60
61
  await kill_all_emsys()
61
62
 
62
- app = Application(backend="win32").start(
63
- "C:\\Rezende\\EMSys3\\EMSysFiscal_39.exe"
64
- )
63
+ app = Application(backend="win32").start("C:\\Rezende\\EMSys3\\EMSysFiscal.exe")
65
64
  warnings.filterwarnings(
66
65
  "ignore",
67
66
  category=UserWarning,
@@ -286,57 +285,129 @@ async def extracao_saldo_estoque_fiscal(
286
285
  tentativa = 1
287
286
  sucesso = False
288
287
 
288
+ # defina caminho_arquivo ANTES para não ficar indefinido
289
+ caminho_arquivo = rf"C:\Users\automatehub\Downloads\saldo_estoque_fiscal_{periodo_format}_{filial}.xlsx"
290
+
289
291
  while tentativa <= max_tentativas and not sucesso:
290
- console.print(f"Tentativa {tentativa} de {max_tentativas}", style="bold cyan")
292
+ console.print(
293
+ f"Tentativa {tentativa} de {max_tentativas}", style="bold cyan"
294
+ )
291
295
 
292
- # 1) Abrir o picker de formatos pelo botão (imagem)
296
+ # 1) Abrir o picker pelo botão (imagem)
293
297
  console.print("Procurando botão de salvar (imagem)...", style="bold cyan")
294
- caminho_img = r'assets\\extracao_relatorios\\btn_salvar.png'
298
+ caminho_img = r"assets\\extracao_relatorios\\btn_salvar.png"
295
299
  if os.path.isfile(caminho_img):
296
300
  pos = pyautogui.locateCenterOnScreen(caminho_img, confidence=0.9)
297
301
  if pos:
298
302
  pyautogui.click(pos)
299
- console.print("Clique realizado no botão salvar", style="bold green")
303
+ console.print(
304
+ "Clique realizado no botão salvar", style="bold green"
305
+ )
300
306
  else:
301
- console.print("Imagem encontrada mas não está visível na tela", style="bold yellow")
307
+ console.print(
308
+ "Imagem encontrada mas não está visível na tela",
309
+ style="bold yellow",
310
+ )
302
311
  else:
303
312
  console.print("Imagem do botão salvar NÃO existe", style="bold red")
304
313
 
305
314
  await worker_sleep(8)
306
315
 
307
- # 2) Selecionar formato "Excel" na janela TFrmRelatorioFormato
316
+ # 2) Selecionar formato Excel (desambiguando múltiplas TFrmRelatorioFormato)
308
317
  console.print("Selecionando formato Excel...", style="bold cyan")
309
318
  try:
310
- app_fmt = Application().connect(class_name="TFrmRelatorioFormato", timeout=10)
311
- win_fmt = app_fmt["TFrmRelatorioFormato"]
312
- win_fmt.wait("visible", timeout=10)
319
+ desktop = Desktop(backend="win32")
320
+
321
+ # Liste todas as visíveis
322
+ wins_visiveis = desktop.windows(
323
+ class_name="TFrmRelatorioFormato", visible_only=True
324
+ )
325
+ if not wins_visiveis:
326
+ raise RuntimeError("Janela de formato não apareceu.")
327
+
328
+ # 2.1) Tente a janela em foco (foreground)
329
+ h_fore = win32gui.GetForegroundWindow()
330
+ alvo = None
331
+ for w in wins_visiveis:
332
+ if w.handle == h_fore:
333
+ alvo = w
334
+ break
335
+
336
+ # 2.2) Se não estiver em foco, pegue a que contém um TComboBox (a 'Configuração para Salvar arq...')
337
+ if alvo is None:
338
+ candidatos = []
339
+ for w in wins_visiveis:
340
+ try:
341
+ if w.child_window(class_name="TComboBox").exists(
342
+ timeout=0.8
343
+ ):
344
+ candidatos.append(w)
345
+ except Exception:
346
+ pass
347
+ if candidatos:
348
+ alvo = candidatos[-1] # a mais recente
349
+ else:
350
+ alvo = wins_visiveis[-1] # fallback
351
+
352
+ # Trabalhe via WindowSpecification
353
+ spec_fmt = desktop.window(handle=alvo.handle)
354
+ spec_fmt.wait("visible", timeout=10)
355
+ win_fmt = spec_fmt.wrapper_object()
356
+ win_fmt.set_focus()
357
+
358
+ # Acessar o ComboBox
359
+ try:
360
+ combo_spec = spec_fmt.child_window(class_name="TComboBox")
361
+ except Exception:
362
+ combo_spec = spec_fmt.child_window(control_type="ComboBox")
363
+ combo_spec.wait("exists enabled", timeout=10)
364
+ combo = combo_spec.wrapper_object()
313
365
 
314
- combo = win_fmt.ComboBox
315
366
  textos = combo.texts()
316
367
  console.print(f"Itens do ComboBox: {textos}", style="bold yellow")
317
368
 
318
- # Se souber o índice correto, mantenha. Caso contrário, tente por texto contendo 'Excel'
369
+ # Seleção por índice conhecido; fallback por texto
319
370
  try:
320
371
  combo.select(8)
321
372
  except Exception:
322
- alvo = None
373
+ alvo_idx = None
323
374
  for i, t in enumerate(textos):
324
375
  if "EXCEL" in str(t).upper() or "XLSX" in str(t).upper():
325
- alvo = i
376
+ alvo_idx = i
326
377
  break
327
- if alvo is not None:
328
- combo.select(alvo)
329
- else:
330
- console.print("Não foi possível localizar a opção de Excel no ComboBox.", style="bold red")
378
+ if alvo_idx is None:
379
+ console.print(
380
+ "Não foi possível localizar a opção de Excel no ComboBox.",
381
+ style="bold red",
382
+ )
331
383
  tentativa += 1
332
384
  await worker_sleep(2)
333
385
  continue
386
+ combo.select(alvo_idx)
334
387
 
335
388
  await worker_sleep(1)
336
389
 
337
- # Botão OK/Confirmar na janela de formato
338
- win_fmt.child_window(class_name="TBitBtn", found_index=1).wait("enabled", timeout=5)
339
- win_fmt.child_window(class_name="TBitBtn", found_index=1).click_input()
390
+ # Clique em OK
391
+ btn_ok_spec = spec_fmt.child_window(class_name="TBitBtn", found_index=1)
392
+ btn_ok_spec.wait("enabled", timeout=5)
393
+ btn_ok_spec.click_input()
394
+
395
+ # Aguarde a janela de formato desaparecer
396
+ try:
397
+ spec_fmt.wait_not("visible", timeout=10)
398
+ except Exception:
399
+ pass
400
+
401
+ # Feche possíveis duplicatas remanescentes (defensivo)
402
+ for w in desktop.windows(
403
+ class_name="TFrmRelatorioFormato", visible_only=True
404
+ ):
405
+ if w.handle != alvo.handle:
406
+ try:
407
+ w.close()
408
+ except Exception:
409
+ pass
410
+
340
411
  except Exception as e:
341
412
  console.print(f"Falha ao selecionar formato: {e}", style="bold red")
342
413
  tentativa += 1
@@ -348,47 +419,66 @@ async def extracao_saldo_estoque_fiscal(
348
419
  # 3) Janela "Salvar para arquivo"
349
420
  console.print("Abrindo janela de salvar arquivo...", style="bold cyan")
350
421
  try:
351
- app_save = Application().connect(title_re="Salvar para arquivo", timeout=30)
352
- win_save = app_save.window(title_re="Salvar para arquivo")
353
- win_save.wait("visible", timeout=30)
422
+ app_save = Application(backend="win32").connect(
423
+ title_re="Salvar para arquivo|Salvar como|Save As", timeout=30
424
+ )
425
+ spec_save = app_save.window(
426
+ title_re="Salvar para arquivo|Salvar como|Save As"
427
+ )
428
+ spec_save.wait("visible", timeout=30)
429
+ win_save = spec_save.wrapper_object()
354
430
  except Exception as e:
355
- console.print(f"Não achou a janela 'Salvar para arquivo': {e}", style="bold red")
431
+ console.print(
432
+ f"Não achou a janela 'Salvar para arquivo': {e}", style="bold red"
433
+ )
356
434
  tentativa += 1
357
435
  await worker_sleep(3)
358
436
  continue
359
437
 
360
- # Caminho do arquivo a salvar
361
- caminho_arquivo = rf"C:\Users\automatehub\Downloads\saldo_estoque_fiscal_{periodo_format}_{filial}.xlsx"
362
-
363
- # Se já existe, removemos para evitar pop-up de confirmação
438
+ # 3.1) Remover arquivo pré-existente
364
439
  if os.path.exists(caminho_arquivo):
365
440
  try:
366
441
  os.remove(caminho_arquivo)
367
- console.print("Arquivo existente removido para evitar prompt de sobrescrita.", style="bold yellow")
442
+ console.print(
443
+ "Arquivo existente removido para evitar prompt de sobrescrita.",
444
+ style="bold yellow",
445
+ )
368
446
  except Exception as e:
369
- console.print(f"Não foi possível remover o arquivo existente: {e}", style="bold red")
447
+ console.print(
448
+ f"Não foi possível remover o arquivo existente: {e}",
449
+ style="bold red",
450
+ )
370
451
 
452
+ # 3.2) Preencher nome e salvar
371
453
  try:
372
- # Campo "Nome" (Edit, control_id=1148)
373
- campo_nome = win_save.child_window(class_name="Edit", control_id=1148).wrapper_object()
454
+ campo_spec = spec_save.child_window(class_name="Edit", control_id=1148)
455
+ campo_spec.wait("exists enabled visible", timeout=10)
456
+ campo_nome = campo_spec.wrapper_object()
374
457
  campo_nome.set_focus()
375
- # limpa conteúdo
376
458
  try:
377
459
  campo_nome.set_edit_text("")
378
460
  except Exception:
379
- # fallback limpando com Ctrl+A + Delete
380
461
  campo_nome.type_keys("^a{DELETE}", pause=0.02)
381
462
 
382
- # digita caminho
383
463
  campo_nome.type_keys(caminho_arquivo, with_spaces=True, pause=0.01)
384
- console.print(f"Arquivo configurado para: {caminho_arquivo}", style="bold green")
464
+ console.print(
465
+ f"Arquivo configurado para: {caminho_arquivo}", style="bold green"
466
+ )
385
467
 
386
468
  await worker_sleep(1)
387
469
 
388
- # Botão Salvar (primeiro Button)
389
- btn_salvar = win_save.child_window(class_name="Button", found_index=0)
390
- btn_salvar.wait("enabled", timeout=10)
391
- btn_salvar.click_input()
470
+ btn_salvar_spec = spec_save.child_window(
471
+ class_name="Button", found_index=0
472
+ )
473
+ btn_salvar_spec.wait("enabled", timeout=10)
474
+ btn_salvar_spec.click_input()
475
+
476
+ # Esperar a janela sumir
477
+ try:
478
+ spec_save.wait_not("visible", timeout=15)
479
+ except Exception:
480
+ pass
481
+
392
482
  except Exception as e:
393
483
  console.print(f"Erro ao confirmar salvar: {e}", style="bold red")
394
484
  tentativa += 1
@@ -397,35 +487,42 @@ async def extracao_saldo_estoque_fiscal(
397
487
 
398
488
  await worker_sleep(2)
399
489
 
400
- # 3.1) Tratar confirmação de sobrescrita, se aparecer
490
+ # 3.3) Confirmar sobrescrita (se houver)
401
491
  try:
402
- # Pode vir em PT/EN dependendo do SO
403
- # Título comum: "Confirm Save As" (EN) ou "Confirmar Salvar Como" (PT)
404
- try:
405
- app_conf = Application().connect(title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As", timeout=3)
406
- win_conf = app_conf.window(title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As")
407
- win_conf.wait("visible", timeout=3)
408
- # Botões costumam ser "Sim"/"Yes" como class_name="Button"
409
- # Tente o primeiro botão (Yes/Sim)
410
- win_conf.child_window(class_name="Button", found_index=0).click_input()
411
- console.print("Confirmação de sobrescrita respondida.", style="bold yellow")
412
- except Exception:
413
- pass
492
+ app_conf = Application(backend="win32").connect(
493
+ title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As", timeout=3
494
+ )
495
+ spec_conf = app_conf.window(
496
+ title_re="Confirm(ar)?( )?Salvar( )?Como|Confirm Save As"
497
+ )
498
+ spec_conf.wait("visible", timeout=3)
499
+ spec_conf.child_window(class_name="Button", found_index=0).click_input()
500
+ console.print(
501
+ "Confirmação de sobrescrita respondida.", style="bold yellow"
502
+ )
414
503
  except Exception:
415
504
  pass
416
505
 
417
506
  await worker_sleep(2)
418
507
 
419
- # 4) Aguardar o processamento/Printing encerrar
420
- console.print("Aguardando finalização do processo de impressão/salvamento...", style="bold cyan")
508
+ # 4) Aguardar 'Printing' (se existir)
509
+ console.print(
510
+ "Aguardando finalização do processo de impressão/salvamento...",
511
+ style="bold cyan",
512
+ )
421
513
  try:
422
- app_print = Application().connect(title_re="Printing", timeout=5)
423
- win_print = app_print.window(title_re="Printing")
514
+ app_print = Application(backend="win32").connect(
515
+ title_re="Printing", timeout=5
516
+ )
517
+ spec_print = app_print.window(title_re="Printing")
424
518
  try:
425
- win_print.wait_not("visible", timeout=60)
519
+ spec_print.wait_not("visible", timeout=60)
426
520
  console.print("Janela 'Printing' fechada.", style="bold green")
427
521
  except Exception:
428
- console.print("Janela 'Printing' não fechou no tempo esperado. Seguindo.", style="bold yellow")
522
+ console.print(
523
+ "Janela 'Printing' não fechou no tempo esperado. Seguindo.",
524
+ style="bold yellow",
525
+ )
429
526
  except findwindows.ElementNotFoundError:
430
527
  console.print("Janela 'Printing' não apareceu.", style="bold yellow")
431
528
  except Exception as e:
@@ -433,18 +530,23 @@ async def extracao_saldo_estoque_fiscal(
433
530
 
434
531
  # 5) Validar arquivo salvo
435
532
  if os.path.exists(caminho_arquivo):
436
- console.print(f"Arquivo encontrado: {caminho_arquivo}", style="bold green")
533
+ console.print(
534
+ f"Arquivo encontrado: {caminho_arquivo}", style="bold green"
535
+ )
437
536
  with open(caminho_arquivo, "rb") as f:
438
537
  file_bytes = io.BytesIO(f.read())
439
538
  sucesso = True
440
539
  else:
441
- console.print("Arquivo não encontrado, tentando novamente...", style="bold red")
540
+ console.print(
541
+ "Arquivo não encontrado, tentando novamente...", style="bold red"
542
+ )
442
543
  tentativa += 1
443
544
  await worker_sleep(3)
444
545
 
445
546
  if not sucesso:
446
- console.print("Falha após 5 tentativas. Arquivo não foi gerado.", style="bold red")
447
-
547
+ console.print(
548
+ "Falha após 5 tentativas. Arquivo não foi gerado.", style="bold red"
549
+ )
448
550
 
449
551
  nome_com_extensao = f"saldo_estoque_fiscal_{periodo_format}_{filial}.xlsx"
450
552
  # lê o arquivo
@@ -488,4 +590,3 @@ async def extracao_saldo_estoque_fiscal(
488
590
  status=RpaHistoricoStatusEnum.Falha,
489
591
  tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)],
490
592
  )
491
-
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: worker-automate-hub
3
- Version: 0.5.762
3
+ Version: 0.5.764
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
@@ -70,8 +70,8 @@ worker_automate_hub/tasks/jobs/entrada_de_notas_9000.py,sha256=0mOmS28tQKF5m7vMz
70
70
  worker_automate_hub/tasks/jobs/exemplo_processo.py,sha256=nV0iLoip2FH2-FhLmhX3nPqsfl_MPufZ3E5Q5krJvdc,3544
71
71
  worker_automate_hub/tasks/jobs/extracao_fechamento_contabil.py,sha256=6Kr5DKjKLqtFvGzyiXtt7xrQsuU898l8pQXDq9C6AX8,19567
72
72
  worker_automate_hub/tasks/jobs/extracao_fechamento_emsys.py,sha256=-T2nZUDiFrUGm_KLxJd_4qcrageDxVpWW3KAAniLFC4,21448
73
- worker_automate_hub/tasks/jobs/extracao_saldo_estoque.py,sha256=_tmKYCKqd05xueln-nfd3yVhwpkpsflNQY1BDtyzEZQ,13726
74
- worker_automate_hub/tasks/jobs/extracao_saldo_estoque_fiscal.py,sha256=d4ckXWJ2sZmE8femwVsGpy6YRIqcleEUOyhLDpjoidM,20010
73
+ worker_automate_hub/tasks/jobs/extracao_saldo_estoque.py,sha256=Pviu3Tt5VTx6LzM1Xl8YOXOMwPH2uIbsRlch7aZVN8g,15747
74
+ worker_automate_hub/tasks/jobs/extracao_saldo_estoque_fiscal.py,sha256=cSKEPsMMETxEfxEb0poSHJBznj8zjD3L3o1a5RQHmf4,23168
75
75
  worker_automate_hub/tasks/jobs/fechar_conexao_rdp.py,sha256=UWAKCS2dbfgDlSQOBdjmVJXfD1MMuUrOi3weDgB0CAc,5718
76
76
  worker_automate_hub/tasks/jobs/fidc_exportacao_docs_portal_b2b.py,sha256=tWUmYy3Zhi3JEt8AoqTsWpU-wbf5-OxhCrTOooh1WH4,15616
77
77
  worker_automate_hub/tasks/jobs/fidc_gerar_nosso_numero.py,sha256=FAmcCqKVjedf7wIped8XRLIZ9S3oWc6fakF-r1Zm0kg,12637
@@ -101,7 +101,7 @@ worker_automate_hub/utils/updater.py,sha256=en2FCGhI8aZ-JNP3LQm64NJDc4awCNW7UhbV
101
101
  worker_automate_hub/utils/util.py,sha256=V2WtWoETdTrAtGA8UgeqAAVphUj9KkGSZFzYsHJFATA,210055
102
102
  worker_automate_hub/utils/utils_nfe_entrada.py,sha256=TOXKSHOPxy8N3-ROpTGjNIHstX0i2b8qekcj1tRvjG8,38174
103
103
  worker_automate_hub/worker.py,sha256=uhZ3f-iaQ1i8cANbljp50vkYl-Xm0_sHtjwwF_2y72o,7191
104
- worker_automate_hub-0.5.762.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
105
- worker_automate_hub-0.5.762.dist-info/METADATA,sha256=BEbaURlGZPVFULs8hLkai5d3PzlMyahZkrGyc-YfmyI,3049
106
- worker_automate_hub-0.5.762.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
107
- worker_automate_hub-0.5.762.dist-info/RECORD,,
104
+ worker_automate_hub-0.5.764.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
105
+ worker_automate_hub-0.5.764.dist-info/METADATA,sha256=EzoBywaY4Qp_AK22cG8Wbu4U4we21kcgoYsGOmn9qAo,3049
106
+ worker_automate_hub-0.5.764.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
107
+ worker_automate_hub-0.5.764.dist-info/RECORD,,