worker-automate-hub 0.5.37__py3-none-any.whl → 0.5.39__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.
@@ -0,0 +1,1488 @@
1
+ import getpass
2
+ import warnings
3
+ import os
4
+ import re
5
+ import io
6
+ import uuid
7
+
8
+ import pyautogui
9
+ import pytesseract
10
+ from datetime import datetime, timedelta
11
+ from pywinauto.application import Application
12
+ from pypdf import PdfReader
13
+ from PIL import Image, ImageEnhance
14
+ from pywinauto.keyboard import send_keys
15
+ import win32clipboard
16
+ from pywinauto_recorder.player import set_combobox
17
+ from rich.console import Console
18
+ from worker_automate_hub.api.ahead_service import save_xml_to_downloads
19
+ from worker_automate_hub.api.client import (
20
+ get_config_by_name,
21
+ get_status_nf_emsys,
22
+ send_file,
23
+ )
24
+ from worker_automate_hub.models.dto.rpa_historico_request_dto import (
25
+ RpaHistoricoStatusEnum,
26
+ RpaRetornoProcessoDTO,
27
+ RpaTagDTO,
28
+ RpaTagEnum,
29
+ )
30
+ from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
31
+ RpaProcessoEntradaDTO,
32
+ )
33
+ from worker_automate_hub.utils.logger import logger
34
+ from worker_automate_hub.utils.util import (
35
+ e_ultimo_dia_util,
36
+ delete_xml,
37
+ ocr_warnings,
38
+ nf_busca_nf_saida,
39
+ pessoas_ativa_cliente_fornecedor,
40
+ nf_devolucao_liquidar_cupom,
41
+ gerenciador_nf_header,
42
+ cadastro_pre_venda_header,
43
+ incluir_registro,
44
+ is_window_open,
45
+ is_window_open_by_class,
46
+ kill_all_emsys,
47
+ login_emsys,
48
+ select_documento_type,
49
+ set_variable,
50
+ type_text_into_field,
51
+ worker_sleep,
52
+ post_partner,
53
+ )
54
+
55
+ pyautogui.PAUSE = 0.5
56
+ pyautogui.FAILSAFE = False
57
+ console = Console()
58
+
59
+
60
+ async def devolucao_prazo_a_faturar(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoDTO:
61
+ """
62
+ Processo que relazia entrada de notas no ERP EMSys(Linx).
63
+
64
+ """
65
+ try:
66
+ #DEFINIR CONSTANTE DEFAULT PARA O ASSETS
67
+ ASSETS_PATH = "assets"
68
+ # Get config from BOF
69
+ config = await get_config_by_name("login_emsys")
70
+ try:
71
+ aliquota_icms = await get_config_by_name("Aliquota_ICMS")
72
+ conconfig_aliquota_icms = aliquota_icms.conConfiguracao
73
+ except Exception as e:
74
+ return RpaRetornoProcessoDTO(
75
+ sucesso=False,
76
+ retorno=f"Não foi possivel recuperar o valor da configuração de Aliquota, erro: {e}.",
77
+ status=RpaHistoricoStatusEnum.Falha,
78
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
79
+ )
80
+ console.print(task)
81
+
82
+ # Seta config entrada na var nota para melhor entendimento
83
+ nota = task.configEntrada
84
+
85
+ #Definindo Variaveis com Escopo global
86
+ numero_cupom_fiscal = nota.get("numCupomNotaFiscal")
87
+ cod_cliente_correto = nota.get("codClienteCorreto")
88
+ cod_cliente_incorreto = nota.get("codClienteIncorreto")
89
+ steps = ""
90
+ numero_nota_fiscal = ""
91
+ valor_nota_fiscal = ""
92
+ item_arla = False
93
+ cidade_cliente = ""
94
+ data_hoje = datetime.today().strftime('%d/%m/%Y')
95
+ multiplicador_timeout = int(float(task.sistemas[0].timeout))
96
+ set_variable("timeout_multiplicador", multiplicador_timeout)
97
+
98
+ #VERIFICANDO ENTRADA
99
+ historico_id = task.historico_id
100
+ if historico_id:
101
+ console.print("Historico ID recuperado com sucesso...\n")
102
+ else:
103
+ console.print("Não foi possivel recuperar o histórico do ID, não sendo possivel enviar os arquivo gerados como retorno...\n")
104
+ return RpaRetornoProcessoDTO(
105
+ sucesso=False,
106
+ retorno="Não foi possivel recuperar o histórico do ID, não sendo possivel enviar os arquivo gerados como retorno",
107
+ status=RpaHistoricoStatusEnum.Falha,
108
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
109
+ )
110
+
111
+ # Fecha a instancia do emsys - caso esteja aberta
112
+ await kill_all_emsys()
113
+
114
+ #Validar se é o ultimo dia
115
+ if await e_ultimo_dia_util():
116
+ return RpaRetornoProcessoDTO(
117
+ sucesso=False,
118
+ retorno="Não será possivel processar devido a regra - 'Não deve ser processado nenhuma devolução no último dia útil do mês vigente'",
119
+ status=RpaHistoricoStatusEnum.Falha,
120
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
121
+ )
122
+
123
+ #Realizando o login
124
+ app = Application(backend="win32").start("C:\\Rezende\\EMSys3\\EMSys3.exe")
125
+ warnings.filterwarnings("ignore",category=UserWarning,message="32-bit application should be automated using 32-bit Python")
126
+ console.print("\nEMSys iniciando...", style="bold green")
127
+ return_login = await login_emsys(config.conConfiguracao, app, task)
128
+ if return_login.sucesso == True:
129
+ console.print("Processo de login realizado com sucesso... \n")
130
+ else:
131
+ logger.info(f"\nError Message: {return_login.retorno}")
132
+ console.print(f"\nError Message: {return_login.retorno}", style="bold red")
133
+ return return_login
134
+
135
+ #VALIDAR SE CLIENTE É FIDIC
136
+ console.print("Validando se o Cliente é FIDC...\n")
137
+ if nota.get("clienteFIDC").lower() == 'não':
138
+ #HABILITAR CLIENTE E FORNECEDOR PARA COD INCORRETO
139
+ console.print("Seguindo com o processo de habilitar Cliente e Fornecedor para andamento do processo.. \n")
140
+ type_text_into_field("Pessoas", app["TFrmMenuPrincipal"]["Edit"], True, "50")
141
+ pyautogui.press("enter")
142
+ send_keys("{DOWN " + ("2") + "}")
143
+ pyautogui.press("enter")
144
+
145
+ await worker_sleep(2)
146
+ console.print("Verificando se o cliente esta ativo como Cliente e como Fornecedor... \n")
147
+ ativar_cliente_fornecedor = await pessoas_ativa_cliente_fornecedor(cod_cliente_incorreto, True, True)
148
+ if ativar_cliente_fornecedor.sucesso == True:
149
+ steps += 'ETAPA 00 - CLIENTE E FORNECEDOR - ATIVADOS COM SUCESSO'
150
+ console.log(ativar_cliente_fornecedor.retorno, style="bold green")
151
+ else:
152
+ return RpaRetornoProcessoDTO(
153
+ sucesso=False,
154
+ retorno=ativar_cliente_fornecedor.retorno,
155
+ status=RpaHistoricoStatusEnum.Falha,
156
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
157
+ )
158
+
159
+ #REALIZAR PROCESSO DE NOTA FISCAL DE SAIDA
160
+ type_text_into_field("Nota Fiscal de Saida", app["TFrmMenuPrincipal"]["Edit"], True, "50")
161
+ pyautogui.press("enter")
162
+ await worker_sleep(2)
163
+ pyautogui.press("enter")
164
+ console.print(f"\nPesquisa: 'Nota Fiscal de Saída' realizada com sucesso",style="bold green")
165
+ await worker_sleep(6)
166
+
167
+ busca_nf_saida = await nf_busca_nf_saida(numero_cupom_fiscal)
168
+ if busca_nf_saida.sucesso == True:
169
+ console.log(busca_nf_saida.retorno, style="bold green")
170
+ else:
171
+ retorno = f"{busca_nf_saida.retorno} \nEtapas Executadas:\n{steps}"
172
+ return RpaRetornoProcessoDTO(
173
+ sucesso=False,
174
+ retorno=retorno,
175
+ status=RpaHistoricoStatusEnum.Falha,
176
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
177
+ )
178
+
179
+
180
+ #VERIFICANDO A EXISTENCIA DE WARNINGS
181
+ console.print("Verificando a existência de Warning... \n")
182
+ warning_pop_up = await is_window_open("Warning")
183
+ if warning_pop_up["IsOpened"] == True:
184
+ console.print("possui Pop-up de Warning, analisando... \n")
185
+ ocr_pop_warning = await ocr_warnings(numero_cupom_fiscal)
186
+ if ocr_pop_warning.sucesso == True:
187
+ retorno = f"POP UP Warning não mapeado para seguimento do processo, mensagem: {ocr_pop_warning.retorno} \nEtapas Executadas:\n{steps}"
188
+ return RpaRetornoProcessoDTO(
189
+ sucesso=False,
190
+ retorno=retorno,
191
+ status=RpaHistoricoStatusEnum.Falha,
192
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
193
+ )
194
+ else:
195
+ retorno = f"{ocr_pop_warning.retorno} \nEtapas Executadas:\n{steps}"
196
+ return RpaRetornoProcessoDTO(
197
+ sucesso=False,
198
+ retorno=retorno,
199
+ status=RpaHistoricoStatusEnum.Falha,
200
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
201
+ )
202
+ else:
203
+ console.print("Não possui pop de Warning...\n")
204
+
205
+
206
+ #VERIFICANDO SE O BOTÃO IR PARA A NOTA FATURA
207
+ console.print("Verificando o status do Botão [Ir para Nota Fatura]...\n")
208
+ try:
209
+ btn_ir_para_nota = pyautogui.locateOnScreen(ASSETS_PATH + "\\notas_saida\\ir_para_nota_a_fatura_esmaecido.png", confidence=0.8)
210
+ if btn_ir_para_nota:
211
+ console.print("Botão 'Ir para nota de faturar' inativo, seguindo com o processo...\n")
212
+ else:
213
+ retorno = f"Botão [Ir para nota de faturar] está ativo, impossibilitando realizar a devolução \nEtapas Executadas:\n{steps}"
214
+ return RpaRetornoProcessoDTO(
215
+ sucesso=False,
216
+ retorno=retorno,
217
+ status=RpaHistoricoStatusEnum.Falha,
218
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
219
+ )
220
+ except Exception as e:
221
+ return RpaRetornoProcessoDTO(
222
+ sucesso=False,
223
+ retorno=f"Não foi possivel verificar o botão [Ir para nota de faturar], erro: {e}",
224
+ status=RpaHistoricoStatusEnum.Falha,
225
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
226
+ )
227
+
228
+ #Para liquidar o cupom
229
+ type_text_into_field("Titulos a receber", app["TFrmMenuPrincipal"]["Edit"], True, "50")
230
+ pyautogui.press("enter")
231
+ await worker_sleep(2)
232
+ pyautogui.press("enter")
233
+
234
+
235
+ liquidar_cupom = await nf_devolucao_liquidar_cupom(numero_cupom_fiscal, data_hoje)
236
+ if liquidar_cupom.sucesso == True:
237
+ console.log(liquidar_cupom.retorno, style="bold green")
238
+ steps += 'ETAPA 01 - Processo de liquidar cupom finalizado com sucesso'
239
+ else:
240
+ descricao_tag = liquidar_cupom.tags[0]
241
+ retorno = f"{liquidar_cupom.retorno} \nEtapas Executadas:\n{steps}"
242
+ return RpaRetornoProcessoDTO(
243
+ sucesso=False,
244
+ retorno=retorno,
245
+ status=RpaHistoricoStatusEnum.Falha,
246
+ tags=[RpaTagDTO(descricao=descricao_tag.descricao)]
247
+ )
248
+
249
+
250
+ #ETAPA 14 A 18
251
+ #STEP 2 - EMISSAO DA NOTA
252
+ type_text_into_field("Nota Fiscal de Entrada", app["TFrmMenuPrincipal"]["Edit"], True, "50")
253
+ pyautogui.press("enter")
254
+ await worker_sleep(2)
255
+ pyautogui.press("enter")
256
+ console.print(f"\nPesquisa: 'Nota Fiscal de Entrada' realizada com sucesso",style="bold green",
257
+ )
258
+
259
+ # Procura campo documento
260
+ console.print("Navegando pela Janela de Nota Fiscal de Entrada...\n")
261
+ document_type = await select_documento_type("NFe - NOTA FISCAL ELETRONICA PROPRIA - DANFE SERIE 077")
262
+ if document_type.sucesso == True:
263
+ console.log(document_type.retorno, style="bold green")
264
+ else:
265
+ retorno = f"{document_type.retorno} \nEtapas Executadas:\n{steps}"
266
+ return RpaRetornoProcessoDTO(
267
+ sucesso=False,
268
+ retorno=retorno,
269
+ status=RpaHistoricoStatusEnum.Falha,
270
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
271
+ )
272
+
273
+ await worker_sleep(4)
274
+
275
+ app = Application().connect(class_name="TFrmNotaFiscalEntrada", timeout=60)
276
+ main_window = app["TFrmNotaFiscalEntrada"]
277
+
278
+ main_window.set_focus()
279
+ await worker_sleep(3)
280
+
281
+ console.print("Controles encontrados na janela 'Nota Fiscal de Entrada, navegando entre eles...\n")
282
+ panel_TNotebook = main_window.child_window(class_name="TNotebook", found_index=0)
283
+ panel_TPage = panel_TNotebook.child_window(class_name="TPage", found_index=0)
284
+ panel_TPageControl = panel_TPage.child_window(class_name="TPageControl", found_index=0)
285
+ panel_TTabSheet = panel_TPageControl.child_window(class_name="TTabSheet", found_index=0)
286
+
287
+ #SELECIONANDO O TIPO NOTA
288
+ console.print("SELECIONANDO O TIPO NOTA...\n")
289
+ panel_tipo_nota = panel_TPageControl.child_window(class_name="TDBIGroupBox", found_index=1)
290
+ radio_nota_devolucao = panel_tipo_nota.child_window(class_name="TDBIRadioButton", found_index=1)
291
+ radio_nota_devolucao.click()
292
+ await worker_sleep(1)
293
+
294
+ #INSERINDO A ENTRADA E EMISSÃO
295
+ console.print("INSERINDO A ENTRADA E EMISSÃO ...\n")
296
+ field_entrada = panel_TTabSheet.child_window(class_name="TDBIEditDate", found_index=1)
297
+ field_emissao = panel_TTabSheet.child_window(class_name="TDBIEditDate", found_index=0)
298
+ field_entrada.set_edit_text(data_hoje)
299
+ field_emissao.set_edit_text(data_hoje)
300
+ await worker_sleep(1)
301
+
302
+ #INSERINDO CODIGO DO FORNECEDOR
303
+ console.print("INSERINDO CODIGO DO FORNECEDOR ...\n")
304
+ field_fornecedor = panel_TTabSheet.child_window(class_name="TDBIEditCode", found_index=0)
305
+ field_fornecedor.set_edit_text(cod_cliente_incorreto)
306
+ pyautogui.press("tab")
307
+
308
+ #SELECIONAO A NOP
309
+ console.print("SELECIONAO A NOP...\n")
310
+ select_box_nop_select = main_window.child_window(class_name="TDBIComboBox", found_index=0)
311
+ select_box_nop_select.click()
312
+ set_combobox("||List", "1662 - DEVOLUÇÃO DE VENDA MERC. ADQ. TERCEIROS- 1.662 DEV COMB C/FI")
313
+ await worker_sleep(2)
314
+
315
+ try:
316
+ pesquisar_icon = pyautogui.locateOnScreen(ASSETS_PATH + "\\emsys\\selecionar_venda.png", confidence=0.8)
317
+ pyautogui.click(pesquisar_icon)
318
+ await worker_sleep(5)
319
+ except Exception as e:
320
+ retorno = f"Não foi possivel clicar no botão Selecionar Venda, erro: {e} \nEtapas Executadas:\n{steps}"
321
+ return RpaRetornoProcessoDTO(
322
+ sucesso=False,
323
+ retorno=retorno,
324
+ status=RpaHistoricoStatusEnum.Falha,
325
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
326
+ )
327
+
328
+ await worker_sleep(2)
329
+ pesquisar_venda_devolucao = await is_window_open_by_class("TFrmPesquisarVendaDevolucao", "TFrmPesquisarVendaDevolucao")
330
+ if pesquisar_venda_devolucao["IsOpened"] == True:
331
+ app = Application().connect(class_name="TFrmPesquisarVendaDevolucao", timeout=60)
332
+ main_window = app["TFrmPesquisarVendaDevolucao"]
333
+ main_window.set_focus()
334
+
335
+ panel_filtro = main_window.child_window(class_name="TGroupBox", found_index=0)
336
+ #INSERINDO O NUMERO VENDA
337
+ console.print("INSERINDO O NUMERO VENDA...\n")
338
+ field_num_venda = panel_filtro.child_window(class_name="TDBIEditString", found_index=0)
339
+ field_num_venda.set_edit_text(numero_cupom_fiscal)
340
+ await worker_sleep(1)
341
+
342
+ #INSERINDO O CODIGO DO CLIENTE
343
+ console.print("INSERINDO O CODIGO DO CLIENTE...\n")
344
+ field_cliente = panel_filtro.child_window(class_name="TDBIEditCode", found_index=0)
345
+ field_cliente.set_edit_text(cod_cliente_incorreto)
346
+ await worker_sleep(1)
347
+
348
+ try:
349
+ pesquisar_icon = pyautogui.locateOnScreen(ASSETS_PATH + "\\emsys\\icon_pesquisa_nota_saida.png", confidence=0.8)
350
+ pyautogui.click(pesquisar_icon)
351
+ await worker_sleep(5)
352
+ except Exception as e:
353
+ retorno = f"Não foi possivel clicar na Lupa para buscar a nota fiscal, erro: {e} \nEtapas Executadas:\n{steps}"
354
+ return RpaRetornoProcessoDTO(
355
+ sucesso=False,
356
+ retorno=retorno,
357
+ status=RpaHistoricoStatusEnum.Falha,
358
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
359
+ )
360
+
361
+ i = 0
362
+ max_attempts = 17
363
+
364
+ while i < max_attempts:
365
+ i += 1
366
+ console.print("Verificando se a nota foi encontrada...\n")
367
+ try:
368
+ main_window.set_focus()
369
+ no_data_full_path = "assets\\entrada_notas\\no_data_display.png"
370
+ img_no_data = pyautogui.locateCenterOnScreen(no_data_full_path, confidence=0.6)
371
+ if img_no_data:
372
+ console.print("'No data display' ainda aparente. Tentando novamente...")
373
+ await worker_sleep(10)
374
+ except pyautogui.ImageNotFoundException:
375
+ console.print("'No data display' não encontrado na tela!")
376
+ break
377
+
378
+ except Exception as e:
379
+ console.print(f"Ocorreu um erro: {e}")
380
+
381
+
382
+ await worker_sleep(5)
383
+ # VERIFICANDO A EXISTENCIA DE ERRO
384
+ erro_pop_up = await is_window_open_by_class("TMessageForm")
385
+ if erro_pop_up["IsOpened"] == True:
386
+ retorno = f"Nota não encontrada no EMsys na tela de Pesquisa Vendas para Devolução \nEtapas Executadas:\n{steps}"
387
+ return RpaRetornoProcessoDTO(
388
+ sucesso=False,
389
+ retorno=retorno,
390
+ status=RpaHistoricoStatusEnum.Falha,
391
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
392
+ )
393
+
394
+ main_window.set_focus()
395
+ try:
396
+ selecionar_todos_itens = pyautogui.locateOnScreen(ASSETS_PATH + "\\emsys\\selecinar_todos_itens_quadro_azul.png", confidence=0.8)
397
+ pyautogui.click(selecionar_todos_itens)
398
+ await worker_sleep(5)
399
+ except Exception as e:
400
+ retorno = f"Não foi possivel clicar em selecionar todos os itens na tela de Pesquisar Vendas para Devolução, erro: {e} \nEtapas Executadas:\n{steps}"
401
+ return RpaRetornoProcessoDTO(
402
+ sucesso=False,
403
+ retorno=retorno,
404
+ status=RpaHistoricoStatusEnum.Falha,
405
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
406
+ )
407
+
408
+ try:
409
+ pesquisar_icon = pyautogui.locateOnScreen(ASSETS_PATH + "\\emsys\\inserir.png", confidence=0.8)
410
+ pyautogui.click(pesquisar_icon)
411
+ await worker_sleep(5)
412
+ except Exception as e:
413
+ retorno = f"Não foi possivel clicar em Inserir para selecionar a nota fiscal, erro: {e} \nEtapas Executadas:\n{steps}"
414
+ return RpaRetornoProcessoDTO(
415
+ sucesso=False,
416
+ retorno=retorno,
417
+ status=RpaHistoricoStatusEnum.Falha,
418
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
419
+ )
420
+
421
+ await worker_sleep(5)
422
+ console.print("Navegando pela Janela de Nota Fiscal de Entrada...\n")
423
+ app = Application().connect(class_name="TFrmNotaFiscalEntrada")
424
+ main_window = app["TFrmNotaFiscalEntrada"]
425
+
426
+ main_window.set_focus()
427
+ console.print("Acessando os itens da nota... \n")
428
+ panel_TPage = main_window.child_window(class_name="TPage", title="Formulario")
429
+ panel_TTabSheet = panel_TPage.child_window(class_name="TcxCustomInnerTreeView")
430
+ panel_TTabSheet.wait("visible")
431
+ panel_TTabSheet.click()
432
+ send_keys("^({HOME})")
433
+ await worker_sleep(1)
434
+ send_keys("{DOWN " + ("1") + "}")
435
+
436
+ # CONFIRMANDO SE A ABA DE ITENS FOI ACESSADA COM SUCESSO
437
+ panel_TPage = main_window.child_window(class_name="TPage", title="Formulario")
438
+ panel_TPage.wait("visible")
439
+ panel_TTabSheet = panel_TPage.child_window(class_name="TTabSheet")
440
+ title_n_serie = panel_TPage.child_window(title="N° Série")
441
+
442
+ console.print("Verificando se os itens foram abertos com sucesso... \n")
443
+ if not title_n_serie:
444
+ retorno = f"Não foi possivel acessar a aba de 'Itens da nota \nEtapas Executadas:\n{steps}"
445
+ console.print(f"Não foi possivel acessar a aba de 'Itens da nota...\n")
446
+ return RpaRetornoProcessoDTO(
447
+ sucesso=False,
448
+ retorno=retorno,
449
+ status=RpaHistoricoStatusEnum.Falha,
450
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
451
+ )
452
+
453
+ await worker_sleep(2)
454
+
455
+ console.print("Acessando os itens indivualmente... \n")
456
+ send_keys("{TAB 2}", pause=0.1)
457
+ await worker_sleep(2)
458
+
459
+ index = 0
460
+ last_line_item_emsys = 'x'
461
+
462
+ try:
463
+ while True:
464
+ await worker_sleep(2)
465
+ send_keys("^({HOME})")
466
+ await worker_sleep(1)
467
+ send_keys("{DOWN " + str(index) + "}", pause=0.1)
468
+ await worker_sleep(1)
469
+
470
+ with pyautogui.hold('ctrl'):
471
+ pyautogui.press('c')
472
+ await worker_sleep(1)
473
+ with pyautogui.hold('ctrl'):
474
+ pyautogui.press('c')
475
+
476
+ win32clipboard.OpenClipboard()
477
+ line_itens_emsys = win32clipboard.GetClipboardData().strip()
478
+ win32clipboard.CloseClipboard()
479
+ console.print(f"Linha atual copiada do Emsys: {line_itens_emsys}\nUltima Linha copiada: {last_line_item_emsys}")
480
+
481
+ if bool(line_itens_emsys):
482
+ if last_line_item_emsys == line_itens_emsys:
483
+ break
484
+ else:
485
+ last_line_item_emsys = line_itens_emsys
486
+
487
+ send_keys("+{F10}")
488
+ await worker_sleep(1)
489
+ send_keys("{DOWN 2}")
490
+ await worker_sleep(1)
491
+ send_keys("{ENTER}")
492
+ await worker_sleep(4)
493
+
494
+ app = Application().connect(title="Alteração de Item")
495
+ main_window = app["Alteração de Item"]
496
+
497
+ main_window.set_focus()
498
+
499
+ # ITERAGINDO COM O IPI
500
+ tpage_ipi = main_window.child_window(
501
+ class_name="TPanel", found_index=0
502
+ )
503
+ ipi = tpage_ipi.child_window(
504
+ class_name="TDBIComboBox", found_index=2
505
+ )
506
+
507
+ ipi_value = ipi.window_text()
508
+
509
+ console.print(
510
+ f"Trabalhando com os itens, valor do IP {ipi_value}... \n"
511
+ )
512
+ if "IPI - ENTRADAS OUTROS" in ipi_value:
513
+ console.print(f"IPI Corretamente selecionado ... \n")
514
+ else:
515
+ console.print(
516
+ f"Trabalhando com os itens, valor do IP em branco, selecionando IPI 0% ... \n"
517
+ )
518
+ ipi.click_input()
519
+ send_keys("^({HOME})")
520
+ send_keys("{DOWN 6}")
521
+ send_keys("{ENTER}")
522
+
523
+ await worker_sleep(4)
524
+ tpage_ipi = main_window.child_window(
525
+ class_name="TPanel", found_index=0
526
+ )
527
+ ipi = tpage_ipi.child_window(
528
+ class_name="TDBIComboBox", found_index=2
529
+ )
530
+
531
+ ipi_value = ipi.window_text()
532
+
533
+ if "IPI - ENTRADAS OUTROS" in ipi_value:
534
+ console.print(
535
+ f"Trabalhando com os itens, sucesso ao selecionar o valor do IPI ... \n"
536
+ )
537
+ else:
538
+ return RpaRetornoProcessoDTO(
539
+ sucesso=False,
540
+ retorno=f"Erro ao selecionar o IPI de unidade nos itens, IPI: {ipi_value}",
541
+ status=RpaHistoricoStatusEnum.Falha,
542
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
543
+ )
544
+
545
+ await worker_sleep(4)
546
+
547
+ console.print(f"Iten selecionado com sucesso, clicando em alterar ...\n")
548
+ try:
549
+ btn_alterar = main_window.child_window(title="&Alterar")
550
+ btn_alterar.click()
551
+ except:
552
+ btn_alterar = main_window.child_window(title="Alterar")
553
+ btn_alterar.click()
554
+ await worker_sleep(3)
555
+
556
+ confirm_pop_up = await is_window_open_by_class("TMessageForm","TMessageForm")
557
+ if confirm_pop_up["IsOpened"] == True:
558
+ app_confirm = Application().connect(
559
+ class_name="TMessageForm"
560
+ )
561
+ main_window_confirm = app_confirm["TMessageForm"]
562
+
563
+ btn_yes = main_window_confirm["&Yes"]
564
+ try:
565
+ btn_yes.click()
566
+ await worker_sleep(3)
567
+ console.print("O botão Yes foi clicado com sucesso.", style="green")
568
+ main_window.close()
569
+ except:
570
+ return RpaRetornoProcessoDTO(
571
+ sucesso=False,
572
+ retorno=f"Não foi possivel clicar em Yes durante a alteração da tributação IPI",
573
+ status=RpaHistoricoStatusEnum.Falha,
574
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
575
+ )
576
+ except Exception as e:
577
+ retorno = f"Erro ao trabalhar nas alterações dos itens, erro: {e} \nEtapas Executadas:\n{steps}"
578
+ return RpaRetornoProcessoDTO(
579
+ sucesso=False,
580
+ retorno=retorno,
581
+ status=RpaHistoricoStatusEnum.Falha,
582
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
583
+ )
584
+
585
+ await worker_sleep(5)
586
+ console.print("Navegando pela Janela de Nota Fiscal de Entrada - Acessando a Janela de Pagamento...\n")
587
+ app = Application().connect(class_name="TFrmNotaFiscalEntrada")
588
+ main_window = app["TFrmNotaFiscalEntrada"]
589
+
590
+ main_window.set_focus()
591
+ console.log("Seleciona Pagamento", style="bold yellow")
592
+ try:
593
+ pyautogui.click(623, 374)
594
+ await worker_sleep(1)
595
+ send_keys("{DOWN " + ("4") + "}")
596
+ except Exception as e:
597
+ panel_TPage = main_window.child_window(class_name="TPage", title="Formulario")
598
+ panel_TTabSheet = panel_TPage.child_window(class_name="TcxCustomInnerTreeView")
599
+ panel_TTabSheet.wait("visible")
600
+ panel_TTabSheet.click()
601
+ send_keys("{DOWN " + ("2") + "}")
602
+
603
+
604
+ if nota.get("cliente_fidc").lower() == 'não':
605
+ try:
606
+ panel_TPage = main_window.child_window(class_name="TPage", title="Formulario")
607
+ panel_TTabSheet = panel_TPage.child_window(class_name="TPageControl")
608
+ panel_TabPagamento = panel_TTabSheet.child_window(class_name="TTabSheet")
609
+ panel_TabPagamentoCaixa = panel_TTabSheet.child_window(title="Pagamento Pelo Caixa")
610
+ tipo_cobranca = panel_TabPagamentoCaixa.child_window(class_name="TDBIComboBox", found_index=0)
611
+
612
+ console.print(f"Selecionando a Especie de Caixa... \n")
613
+ tipo_cobranca.click()
614
+ await worker_sleep(1)
615
+ set_combobox("||List", "13 - DEVOLUCAO DE VENDA")
616
+
617
+ await worker_sleep(2)
618
+
619
+ console.print(f"Capturando o valor em Valores Restante... \n")
620
+ tab_valores = panel_TabPagamento.child_window(title="Valores")
621
+ valores_restantes = tab_valores.child_window(
622
+ class_name="TDBIEditNumber", found_index=1
623
+ )
624
+ valores_restantes_text = valores_restantes.window_text()
625
+ valor_nota_fiscal = valores_restantes_text
626
+ console.print(f"Valor capturado {valores_restantes_text}, inserindo no campo Valor em Pagamento pelo Caixa... \n")
627
+
628
+ valor = panel_TabPagamentoCaixa.child_window(class_name="TDBIEditNumber", found_index=0)
629
+ valor.set_edit_text(valores_restantes_text)
630
+ except Exception as e:
631
+ retorno = f"Não foi possivel realizar as atividades na aba de 'Pagamento', erro: {e} \nEtapas Executadas:\n{steps}"
632
+ return RpaRetornoProcessoDTO(
633
+ sucesso=False,
634
+ retorno=retorno,
635
+ status=RpaHistoricoStatusEnum.Falha,
636
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
637
+ )
638
+ else:
639
+ try:
640
+ panel_TPage = main_window.child_window(class_name="TPage", title="Formulario")
641
+ panel_TTabSheet = panel_TPage.child_window(class_name="TPageControl")
642
+ panel_TabPagamento = panel_TTabSheet.child_window(class_name="TTabSheet")
643
+ panel_TabParcelamento = panel_TTabSheet.child_window(title="Parcelamento")
644
+ tipo_cobranca = panel_TabParcelamento.child_window(class_name="TDBIComboBox", found_index=0)
645
+
646
+ console.print("Verificando o tipo de cobrança selecionado... \n")
647
+ tipo_selecionado = tipo_cobranca.window_text()
648
+ if "boleto" in tipo_selecionado.lower():
649
+ console.print(f"Tipo de cobrança corretamente selecionado {tipo_selecionado}... \n")
650
+ else:
651
+ console.print(f"Tipo de cobrança não foi selecionado corretamente, interagindo com o campo para selecionar o campo corretamente... \n")
652
+ tipo_cobranca.click()
653
+ await worker_sleep(1)
654
+ set_combobox("||List", "BANCO DO BRASIL BOLETO")
655
+
656
+
657
+ tab_valores = panel_TabPagamento.child_window(title="Valores")
658
+ valores_restantes = tab_valores.child_window(class_name="TDBIEditNumber", found_index=1)
659
+ valores_informado = tab_valores.child_window(class_name="TDBIEditNumber", found_index=2)
660
+
661
+ vencimento = panel_TabParcelamento.child_window(class_name="TDBIEditDate")
662
+ data_hoje_obj = datetime.strptime(data_hoje, '%d/%m/%Y')
663
+ nova_data = data_hoje_obj + timedelta(days=5)
664
+ data_vencimento = nova_data.strftime('%d/%m/%Y')
665
+ console.print(f'Data de Vencimento a ser inserida: {data_vencimento}')
666
+ vencimento.set_edit_text(data_vencimento)
667
+
668
+ await worker_sleep(2)
669
+ console.print(f"Inserindo o valor {valores_restantes_text}... \n")
670
+ valor = panel_TabParcelamento.child_window(class_name="TDBIEditNumber", found_index=3)
671
+ valor.set_edit_text(valores_restantes_text)
672
+
673
+ await worker_sleep(2)
674
+ console.print(f"Adicionando o pagamento... \n")
675
+ btn_add = panel_TabParcelamento.child_window(class_name="TDBIBitBtn", found_index=1)
676
+ btn_add.click()
677
+
678
+ await worker_sleep(4)
679
+ console.print(f"Verificando se o pagamento foi adicionado com sucesso... \n")
680
+ valores_informado = tab_valores.child_window(class_name="TDBIEditNumber", found_index=2)
681
+ valores_informado_text = valores_informado.window_text()
682
+ if '0,00' in valores_informado_text and len(valores_informado_text) == 3:
683
+ return RpaRetornoProcessoDTO(
684
+ sucesso=False,
685
+ retorno=f"Erro ao adicionar o pagamento, valor informado {valores_informado_text}.",
686
+ status=RpaHistoricoStatusEnum.Falha,
687
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
688
+ )
689
+ console.print(f"Processo de incluir pagamento realizado com sucesso... \n")
690
+
691
+ except Exception as e:
692
+ retorno = f"Erro ao processar tela 'Pagamento', erro: {e} \nEtapas Executadas:\n{steps}"
693
+ return RpaRetornoProcessoDTO(
694
+ sucesso=False,
695
+ retorno=retorno,
696
+ status=RpaHistoricoStatusEnum.Falha,
697
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
698
+ )
699
+
700
+ # Inclui registro
701
+ console.print(f"Incluindo registro...\n")
702
+ try:
703
+ ASSETS_PATH = "assets"
704
+ inserir_registro = pyautogui.locateOnScreen(ASSETS_PATH + "\\entrada_notas\\IncluirRegistro.png", confidence=0.8)
705
+ pyautogui.click(inserir_registro)
706
+ except Exception as e:
707
+ console.print(
708
+ f"Não foi possivel incluir o registro utilizando reconhecimento de imagem, Error: {e}...\n tentando inserir via posição...\n"
709
+ )
710
+ await incluir_registro()
711
+
712
+
713
+ await worker_sleep(5)
714
+ console.print("Verificando a existencia de POP-UP de Itens que Ultrapassam a Variação Máxima de Custo ...\n")
715
+ itens_variacao_maxima = await is_window_open_by_class("TFrmTelaSelecao", "TFrmTelaSelecao")
716
+ if itens_variacao_maxima["IsOpened"] == True:
717
+ app = Application().connect(class_name="TFrmTelaSelecao")
718
+ main_window = app["TFrmTelaSelecao"]
719
+ send_keys("%o")
720
+
721
+
722
+ #VERIFICANDO SE A NOTA FOI INCLUIDA COM SUCESSO
723
+ console.print("Verificando a se a Nota foi incluida com sucesso... \n")
724
+ try:
725
+ app = Application().connect(title="Information", timeout=180)
726
+ main_window = app["Information"]
727
+ main_window.set_focus()
728
+
729
+ #EXTRAINDO O NUMERO DA NOTA
730
+ window_rect = main_window.rectangle()
731
+ screenshot = pyautogui.screenshot(
732
+ region=(
733
+ window_rect.left,
734
+ window_rect.top,
735
+ window_rect.width(),
736
+ window_rect.height(),
737
+ )
738
+ )
739
+ username = getpass.getuser()
740
+ short_uuid = str(uuid.uuid4()).replace('-', '')[:6]
741
+ path_to_png = f"C:\\Users\\{username}\\Downloads\\aviso_popup_{short_uuid}.png"
742
+ screenshot.save(path_to_png)
743
+ console.print(f"Print salvo em {path_to_png}...\n")
744
+
745
+ console.print(
746
+ f"Preparando a imagem para maior resolução e assertividade no OCR...\n"
747
+ )
748
+ image = Image.open(path_to_png)
749
+ image = image.convert("L")
750
+ enhancer = ImageEnhance.Contrast(image)
751
+ image = enhancer.enhance(2.0)
752
+ image.save(path_to_png)
753
+ console.print(f"Imagem preparada com sucesso...\n")
754
+ console.print(f"Realizando OCR...\n")
755
+ captured_text = pytesseract.image_to_string(Image.open(path_to_png))
756
+ console.print(
757
+ f"Texto Full capturado {captured_text}...\n"
758
+ )
759
+ os.remove(path_to_png)
760
+ pattern = r"sequ[êe]ncia:\s*(\d+)"
761
+ match = re.search(pattern, captured_text)
762
+
763
+ if match:
764
+ numero_nota_fiscal = match.group(1)
765
+
766
+
767
+ btn_ok = main_window.child_window(class_name="TButton", found_index=0)
768
+ btn_ok.click()
769
+ await worker_sleep(3)
770
+ steps += 'ETAPA 02 - Nota fiscal de Entrada Incluida com sucesso'
771
+ except Exception as e:
772
+ retorno = f"Não foi possivel obter a confirmação de Nota fiscal incluida com sucesso \nEtapas Executadas:\n{steps}"
773
+ return RpaRetornoProcessoDTO(
774
+ sucesso=False,
775
+ retorno=retorno,
776
+ status=RpaHistoricoStatusEnum.Falha,
777
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
778
+ )
779
+ else:
780
+ retorno = f"Não foi possivel obter a confirmação de Nota fiscal incluida com sucesso \nEtapas Executadas:\n{steps}"
781
+ return RpaRetornoProcessoDTO(
782
+ sucesso=False,
783
+ retorno=f"Não foi possivel abrir a tela de Pesquisar Venda para Devolução, erro: {e}",
784
+ status=RpaHistoricoStatusEnum.Falha,
785
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
786
+ )
787
+
788
+ app = Application().connect(class_name="TFrmNotaFiscalEntrada")
789
+ main_window = app["TFrmNotaFiscalEntrada"]
790
+ main_window.close()
791
+
792
+ #STEP 3
793
+ type_text_into_field("Gerenciador de Notas Fiscais", app["TFrmMenuPrincipal"]["Edit"], True, "50")
794
+ pyautogui.press("enter")
795
+ await worker_sleep(2)
796
+ pyautogui.press("enter")
797
+ console.print(f"\nPesquisa: 'Gerenciador de Notas Fiscais' realizada com sucesso",style="bold green")
798
+ pesquisar_venda_devolucao = await is_window_open_by_class("TFrmGerenciadorNFe2", "TFrmGerenciadorNFe2")
799
+ if pesquisar_venda_devolucao["IsOpened"] == True:
800
+ selecionar_itens_gerenciador_nfe = await gerenciador_nf_header(data_hoje, cod_cliente_incorreto)
801
+ if selecionar_itens_gerenciador_nfe.sucesso:
802
+ console.print("PROCESSO EXECUTADO COM SUCESSO, SEGUINDO COM O PROCESSO PARA TRANSMITIR A NF-E...\n")
803
+ app = Application().connect(class_name="TFrmGerenciadorNFe2", timeout=60)
804
+ main_window = app["TFrmGerenciadorNFe2"]
805
+ main_window.set_focus()
806
+
807
+ tpanel_footer = main_window.child_window(class_name="TPanel", found_index=1)
808
+ btn_transmitir = tpanel_footer.child_window(class_name="TBitBtn", found_index=5)
809
+ btn_transmitir.click()
810
+ await worker_sleep(3)
811
+
812
+ max_attempts = 10
813
+ i = 0
814
+
815
+ while i < max_attempts:
816
+ try:
817
+ app = Application().connect(class_name="TFrmProcessamentoFEe2", timeout=60)
818
+ main_window = app["TFrmProcessamentoFEe2"]
819
+
820
+ await worker_sleep(15)
821
+
822
+ information_operacao_concluida = main_window.child_window(class_name="TMessageForm")
823
+ btn_ok = information_operacao_concluida.child_window(class_name="TButton")
824
+ btn_ok.click()
825
+ await worker_sleep(4)
826
+ main_window.close()
827
+ break
828
+ except Exception as e:
829
+ pass
830
+
831
+
832
+ i += 1
833
+ await worker_sleep(10)
834
+
835
+
836
+ if i == max_attempts:
837
+ console.print("Número máximo de tentativas atingido. Encerrando...")
838
+ retorno = f"Tempo esgotado e numero de tentativas atingido, não foi possivel obter o retorno de conclusão para transmissão na tela de Gerenciador NF-e \nEtapas Executadas:\n{steps}"
839
+ return RpaRetornoProcessoDTO(
840
+ sucesso=False,
841
+ retorno=retorno,
842
+ status=RpaHistoricoStatusEnum.Falha,
843
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
844
+ )
845
+
846
+
847
+ #PROCESSO DE IMPRESSÃO
848
+ app = Application().connect(class_name="TFrmGerenciadorNFe2", timeout=60)
849
+ main_window = app["TFrmGerenciadorNFe2"]
850
+ main_window.set_focus()
851
+ tpanel_footer = main_window.child_window(class_name="TPanel", found_index=1)
852
+ btn_imprimir_danfe = tpanel_footer.child_window(class_name="TBitBtn", found_index=0)
853
+ btn_imprimir_danfe.click()
854
+ await worker_sleep(5)
855
+
856
+ app = Application().connect(class_name="TFrmConfigurarTemplateDANF2", timeout=60)
857
+ main_window = app["TFrmGerenciadorNFe2"]
858
+ main_window.set_focus()
859
+ btn_selecionar_pdf = main_window.child_window(class_name="TRadioButton", found_index=1)
860
+ btn_selecionar_pdf.click()
861
+ await worker_sleep(2)
862
+
863
+ btn_gerar = main_window.child_window(class_name="TBitBtn", found_index=1)
864
+ btn_gerar.click()
865
+ await worker_sleep(2)
866
+ steps += 'ETAPA 03 - PROCESSO DE TRANSMITIR NF-e EXECUTADO COM SUCESSO '
867
+
868
+
869
+ app = Application().connect(title="Salvar par arquivo")
870
+ main_window = app["Salvar"]
871
+ console.print("Tela 'Salvar' encontrada!")
872
+
873
+ console.print("Interagindo com a tela 'Salvar'...\n")
874
+ username = getpass.getuser()
875
+ path_to_txt = f"C:\\Users\\{username}\\Downloads\\DEVOLUÇÃO PRAZO A FATURAR {numero_cupom_fiscal}"
876
+
877
+ main_window.type_keys("%n")
878
+ pyautogui.write(path_to_txt)
879
+ await worker_sleep(1)
880
+ main_window.type_keys("%l")
881
+ console.print("Arquivo salvo com sucesso...\n")
882
+ await worker_sleep(6)
883
+
884
+ with open(path_to_txt, 'rb') as file:
885
+ file_bytes = io.BytesIO(file.read())
886
+
887
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
888
+ desArquivo = f"DEVOLUÇÃO PRAZO A FATURAR {numero_cupom_fiscal}.pdf"
889
+ try:
890
+ await send_file(historico_id, desArquivo, "pdf", file_bytes, file_extension="pdf")
891
+ os.remove(path_to_txt)
892
+ except Exception as e:
893
+ result = f"Arquivo DEVOLUÇÃO PRAZO A FATURAR 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}! \nEtapas Executadas:\n{steps}"
894
+ console.print(result, style="bold red")
895
+ return RpaRetornoProcessoDTO(
896
+ sucesso=False,
897
+ retorno=result,
898
+ status=RpaHistoricoStatusEnum.Falha,
899
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
900
+ )
901
+
902
+ app = Application().connect(class_name="TFrmConfigurarTemplateDANF2", timeout=60)
903
+ main_window = app["TFrmGerenciadorNFe2"]
904
+ main_window.close()
905
+
906
+ app = Application().connect(class_name="TFrmGerenciadorNFe2", timeout=60)
907
+ main_window = app["TFrmGerenciadorNFe2"]
908
+ main_window.close()
909
+
910
+
911
+ else:
912
+ retorno = f"{selecionar_itens_gerenciador_nfe} \nEtapas Executadas:\n{steps}"
913
+ return RpaRetornoProcessoDTO(
914
+ sucesso=False,
915
+ retorno=retorno,
916
+ status=RpaHistoricoStatusEnum.Falha,
917
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
918
+ )
919
+ else:
920
+ retorno = f"Não foi possivel abrir a tela de Gerenciador de Notas Fiscais \nEtapas Executadas:\n{steps}"
921
+ return RpaRetornoProcessoDTO(
922
+ sucesso=False,
923
+ retorno=retorno,
924
+ status=RpaHistoricoStatusEnum.Falha,
925
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
926
+ )
927
+
928
+
929
+ #STEP 4
930
+ #PRE VENDA
931
+ type_text_into_field("Cadastro Pré venda", app["TFrmMenuPrincipal"]["Edit"], True, "50")
932
+ pyautogui.press("enter")
933
+ await worker_sleep(2)
934
+ pyautogui.press("enter")
935
+ console.print(f"\nPesquisa: 'Cadastro Pré venda' realizada com sucesso",style="bold green")
936
+ cadastro_pre_venda = await is_window_open_by_class("TFrmPreVenda", "TFrmPreVenda")
937
+ if cadastro_pre_venda["IsOpened"] == True:
938
+ preenchimento_header_pre_venda = await cadastro_pre_venda_header("5656 - VENDA DE COMB OU LUB ADQ DE TERCEIRO C/ FIN S/ ESTOQUE", cod_cliente_correto, "21 DIAS")
939
+ if preenchimento_header_pre_venda.sucesso:
940
+ try:
941
+ cidade_cliente = preenchimento_header_pre_venda.retorno
942
+ console.print(f"\nPreenchimento cabeçalho da pre venda preenchido com sucesso, seguindo com o processo.. ",style="bold green")
943
+ app = Application().connect(class_name="TFrmPreVenda", timeout=60)
944
+ main_window = app["TFrmPreVenda"]
945
+ main_window.set_focus()
946
+
947
+ console.print("Navegando nos elementos...\n")
948
+ panel_TPage= main_window.child_window(class_name="TPage", found_index=0)
949
+ panel_menu_itens= main_window.child_window(class_name="TcxCustomInnerTreeView", found_index=0)
950
+
951
+ console.print("Acessando a janela de Itens...\n")
952
+ panel_menu_itens.click()
953
+ await worker_sleep(1)
954
+ send_keys("^({HOME})")
955
+ await worker_sleep(1)
956
+ pyautogui.press('down')
957
+ console.print(nota.get('itens'))
958
+
959
+ for item in nota.get('itens'):
960
+ quantidade = item['novaQuantidade']
961
+ preco = item['novoPreco']
962
+ descricao = item['descricao']
963
+
964
+ if 'arla' in descricao.lower():
965
+ item_arla = True
966
+
967
+ app = Application().connect(class_name="TFrmPreVenda", timeout=60)
968
+ main_window = app["TFrmPreVenda"]
969
+ main_window.set_focus()
970
+
971
+ console.print("Itens acessado com sucesso, clicando em Incluir...\n")
972
+ panel_TGroup_Box= panel_TPage.child_window(class_name="TGroupBox", found_index=0)
973
+ btn_incluir = panel_TGroup_Box.child_window(class_name="TDBIBitBtn", found_index=4)
974
+ btn_incluir.click()
975
+ await worker_sleep(2)
976
+ console.print("Incluir clicado com sucesso...\n")
977
+
978
+ #VERIFICANDO A EXISTENCIA DE WARNINGS
979
+ console.print("Verificando a existência de Warning... \n")
980
+ warning_pop_up = await is_window_open("Warning")
981
+ if warning_pop_up["IsOpened"] == True:
982
+ console.print("possui Pop-up de Warning, analisando... \n")
983
+ ocr_pop_warning = await ocr_warnings(numero_cupom_fiscal)
984
+ if ocr_pop_warning.sucesso == True:
985
+ return RpaRetornoProcessoDTO(
986
+ sucesso=False,
987
+ retorno=f"POP UP Warning não mapeado para seguimento do processo, mensagem: {ocr_pop_warning.retorno}",
988
+ status=RpaHistoricoStatusEnum.Falha,
989
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
990
+ )
991
+ else:
992
+ return RpaRetornoProcessoDTO(
993
+ sucesso=False,
994
+ retorno=f"POP UP Warning não mapeado para seguimento do processo",
995
+ status=RpaHistoricoStatusEnum.Falha,
996
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
997
+ )
998
+
999
+
1000
+ console.print("Clicando sobre a lupa para inserir o almoxarifado...\n")
1001
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1002
+ main_window = app["TFrmIncluiItemPreVenda"]
1003
+ main_window.set_focus()
1004
+ panel_TGroup_Box= panel_TPage.child_window(class_name="TPanel", found_index=2)
1005
+ lupa_almoxarifaco = panel_TPage.child_window(class_name="TDBIBitBtn", found_index=1)
1006
+ lupa_almoxarifaco.click()
1007
+ console.print("Lupa clicado com sucesso inserindo a descrição do almoxarifado...\n")
1008
+
1009
+ app = Application().connect(class_name="TfrmDialogBuscaGeral", timeout=60)
1010
+ main_window = app["TfrmDialogBuscaGeral"]
1011
+ main_window.set_focus()
1012
+
1013
+ field_descricao_almoxarifado = main_window.child_window(class_name="TEdit", found_index=0)
1014
+ field_descricao_almoxarifado.set_edit_text(descricao)
1015
+ await worker_sleep(2)
1016
+
1017
+ btn_lupa_pesquisar = main_window.child_window(class_name="TBitBtn", found_index=0)
1018
+ btn_lupa_pesquisar.click()
1019
+ await worker_sleep(2)
1020
+
1021
+ main_window.set_focus()
1022
+ send_keys("%o")
1023
+ console.print("Processo finalizado com sucesso, seguindo com a seleção da natureza...\n")
1024
+
1025
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1026
+ main_window = app["TFrmIncluiItemPreVenda"]
1027
+ main_window.set_focus()
1028
+ panel_TGroup_Box= panel_TPage.child_window(class_name="TPanel", found_index=2)
1029
+ natureza_oper_select = panel_TPage.child_window(class_name="TDBIComboBox", found_index=0)
1030
+ natureza_oper_select.click()
1031
+ await worker_sleep(1)
1032
+ set_combobox("||List", "5656 - VENDA DE COMB OU LUB ADQ DE TERCEIRO C/ FIN S/ ESTOQUE")
1033
+ await worker_sleep(1)
1034
+ console.print("Natureza da operação selecionado com sucesso, preenchendo os itens...\n")
1035
+
1036
+ #INSERINDO A QUANTIDADE
1037
+ main_window.set_focus()
1038
+ panel_TPage_Control= main_window.child_window(class_name="TcxPageControl", found_index=0)
1039
+ panel_tabSheet = panel_TPage_Control.child_window(class_name="TcxTabSheet", found_index=0)
1040
+
1041
+ field_quantidade = panel_tabSheet.child_window(class_name="TDBIEditNumber", found_index=9)
1042
+ console.print("Inserindo a quantidade de Itens...\n")
1043
+ field_quantidade.set_edit_text(quantidade)
1044
+ await worker_sleep(1)
1045
+
1046
+ #INSERINDO O VALOR INDIVIDUAL DO ITEM
1047
+ console.print("Inserindo o valor indivual do Item...\n")
1048
+ btn_valor_unitario = panel_tabSheet.child_window(class_name="TDBIBitBtn", found_index=0)
1049
+ btn_valor_unitario.click()
1050
+ await worker_sleep(2)
1051
+
1052
+ app = Application().connect(class_name="TFrmInputBoxNumero", timeout=60)
1053
+ main_window = app["TFrmInputBoxNumero"]
1054
+ main_window.set_focus()
1055
+
1056
+ field_valor = main_window.child_window(class_name="TDBIEditNumber", found_index=0)
1057
+ field_valor.set_edit_text(preco)
1058
+ await worker_sleep(2)
1059
+
1060
+ main_window.set_focus()
1061
+ send_keys("%o")
1062
+
1063
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1064
+ main_window = app["TFrmIncluiItemPreVenda"]
1065
+ main_window.set_focus()
1066
+ send_keys("%i")
1067
+ await worker_sleep(2)
1068
+ main_window.close()
1069
+
1070
+
1071
+ # Inclui registro
1072
+ console.print(f"Incluindo registro...\n")
1073
+ try:
1074
+ ASSETS_PATH = "assets"
1075
+ inserir_registro = pyautogui.locateOnScreen(ASSETS_PATH + "\\entrada_notas\\IncluirRegistro.png", confidence=0.8)
1076
+ pyautogui.click(inserir_registro)
1077
+ except Exception as e:
1078
+ console.print(
1079
+ f"Não foi possivel incluir o registro utilizando reconhecimento de imagem, Error: {e}...\n tentando inserir via posição...\n"
1080
+ )
1081
+ await incluir_registro()
1082
+
1083
+
1084
+ #VERIFICANDO A EXISTENCIA DE WARNINGS
1085
+ console.print("Verificando a existência de Warning... \n")
1086
+ warning_pop_up = await is_window_open("Warning")
1087
+ if warning_pop_up["IsOpened"] == True:
1088
+ console.print("possui Pop-up de Warning, analisando... \n")
1089
+ ocr_pop_warning = await ocr_warnings(numero_cupom_fiscal)
1090
+ if ocr_pop_warning.sucesso == True:
1091
+ retorno = f"POP UP Warning não mapeado para seguimento do processo, mensagem: {ocr_pop_warning.retorno} \nEtapas Executadas:\n{steps}"
1092
+ return RpaRetornoProcessoDTO(
1093
+ sucesso=False,
1094
+ retorno=retorno,
1095
+ status=RpaHistoricoStatusEnum.Falha,
1096
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
1097
+ )
1098
+ else:
1099
+ retorno = f"POP UP Warning não mapeado para seguimento do processo \nEtapas Executadas:\n{steps}"
1100
+ return RpaRetornoProcessoDTO(
1101
+ sucesso=False,
1102
+ retorno=retorno,
1103
+ status=RpaHistoricoStatusEnum.Falha,
1104
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
1105
+ )
1106
+
1107
+ steps += 'ETAPA 04 - PRE VENDA INCLUIDA COM SUCESSO'
1108
+ #VERIFICANDO SE A PRÉ VENDA FOI INCLUIDA COM SUCESSO
1109
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1110
+ main_window = app["Informação"]
1111
+ main_window.set_focus()
1112
+
1113
+ btn_ok = main_window.child_window(class_name="Button")
1114
+ btn_ok.click()
1115
+
1116
+ #CONFIRMANDO POP UP DE PRÉ VENDA
1117
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1118
+ main_window = app["Confirm"]
1119
+ main_window.set_focus()
1120
+
1121
+ btn_yes = main_window.child_window(class_name="TButton", found_index=1)
1122
+ btn_yes.click()
1123
+
1124
+ #CONFIRMANDO NA TELA DE PRE VENDA
1125
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1126
+ main_window = app["TFrmIncluiItemPreVenda"]
1127
+ main_window.set_focus()
1128
+
1129
+ panel_Tnotebook = main_window.child_window(class_name="TNotebook", found_index=0)
1130
+ panel_Tnotebook = panel_Tnotebook.child_window(class_name="TPage", found_index=0)
1131
+ btn_confirmar = panel_Tnotebook.child_window(class_name="TBitBtn", found_index=11)
1132
+ btn_confirmar.click()
1133
+ await worker_sleep(3)
1134
+
1135
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1136
+ main_window = app["Confirm"]
1137
+ main_window.set_focus()
1138
+
1139
+ btn_yes = main_window.child_window(class_name="TButton", found_index=1)
1140
+ btn_yes.click()
1141
+ await worker_sleep(3)
1142
+
1143
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1144
+ main_window = app["Warning"]
1145
+ main_window.set_focus()
1146
+
1147
+ btn_ok = main_window.child_window(class_name="TButton", found_index=0)
1148
+ btn_ok.click()
1149
+ await worker_sleep(3)
1150
+
1151
+
1152
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1153
+ main_window = app["Confirm"]
1154
+ main_window.set_focus()
1155
+
1156
+ btn_yes = main_window.child_window(class_name="TButton", found_index=1)
1157
+ btn_yes.click()
1158
+ await worker_sleep(3)
1159
+
1160
+ #APROVAR CREDITO
1161
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1162
+ main_window = app["TFrmIncluiItemPreVenda"]
1163
+ main_window.set_focus()
1164
+
1165
+ panel_Tnotebook = main_window.child_window(class_name="TNotebook", found_index=0)
1166
+ panel_Tnotebook = panel_Tnotebook.child_window(class_name="TPage", found_index=0)
1167
+ btn_aprovar_credito = panel_Tnotebook.child_window(class_name="TBitBtn", found_index=8)
1168
+ btn_aprovar_credito.click()
1169
+ await worker_sleep(2)
1170
+
1171
+
1172
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1173
+ main_window = app["Confirm"]
1174
+ main_window.set_focus()
1175
+
1176
+ btn_yes = main_window.child_window(class_name="TButton", found_index=1)
1177
+ btn_yes.click()
1178
+ await worker_sleep(3)
1179
+
1180
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1181
+ main_window = app["Informação"]
1182
+ main_window.set_focus()
1183
+
1184
+ btn_ok = main_window.child_window(class_name="Button")
1185
+ btn_ok.click()
1186
+
1187
+
1188
+ #FATURAR
1189
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1190
+ main_window = app["TFrmIncluiItemPreVenda"]
1191
+ main_window.set_focus()
1192
+
1193
+ panel_Tnotebook = main_window.child_window(class_name="TNotebook", found_index=0)
1194
+ panel_Tnotebook = panel_Tnotebook.child_window(class_name="TPage", found_index=0)
1195
+ btn_faturar = panel_Tnotebook.child_window(class_name="TBitBtn", found_index=1)
1196
+ btn_faturar.click()
1197
+ await worker_sleep(2)
1198
+
1199
+ app = Application().connect(class_name="TFrmIncluiItemPreVenda", timeout=60)
1200
+ main_window = app["Confirm"]
1201
+ main_window.set_focus()
1202
+
1203
+ btn_no = main_window.child_window(class_name="TButton", found_index=0)
1204
+ btn_no.click()
1205
+ await worker_sleep(3)
1206
+
1207
+ app = Application().connect(title="Parcelas - Nota Fiscal Saída", timeout=60)
1208
+ main_window = app.window(title="Parcelas - Nota Fiscal Saída")
1209
+ main_window.set_focus()
1210
+ send_keys("%n")
1211
+ await worker_sleep(3)
1212
+
1213
+ information_pop_up = await is_window_open("Information")
1214
+ if information_pop_up["IsOpened"] == True:
1215
+ app = Application().connect(title="Information", timeout=180)
1216
+ main_window = app["Information"]
1217
+ main_window.set_focus()
1218
+ btn_ok = main_window.child_window(class_name="TButton", found_index=0)
1219
+ btn_ok.click()
1220
+
1221
+ await worker_sleep(30)
1222
+
1223
+ #FATURAMENTO PRÉ-VENDA
1224
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1225
+ main_window = app["TFrmDadosFaturamentoPreVenda"]
1226
+ main_window.set_focus()
1227
+
1228
+ #VERIFICANDO SE POSSUI POP UP WARNING
1229
+ warning_boo = False
1230
+ try:
1231
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1232
+ main_window = app["Warning"]
1233
+ main_window.set_focus()
1234
+ btn_ok = main_window.child_window(class_name="TButton", found_index=0)
1235
+ btn_ok.click()
1236
+ await worker_sleep(3)
1237
+ warning_boo = True
1238
+ except:
1239
+ pass
1240
+
1241
+ #ALTERANDO TRIBUTO DOS ITENS
1242
+ if warning_boo:
1243
+ console.print('Acessando a tela de Itens')
1244
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1245
+ main_window = app["TFrmDadosFaturamentoPreVenda"]
1246
+ main_window.set_focus()
1247
+ send_keys("%i")
1248
+ await worker_sleep(2)
1249
+ send_keys("%g")
1250
+ await worker_sleep(2)
1251
+
1252
+ app = Application().connect(class_name="TFrmDadosTributacaoProdutoPreVenda", timeout=60)
1253
+ main_window = app["TFrmDadosTributacaoProdutoPreVenda"]
1254
+
1255
+ tpanel_dados_tributacao = main_window.child_window(class_name="TPanel", found_index=1)
1256
+ tributacao_icms_select = tpanel_dados_tributacao.child_window(class_name="TDBIComboBox", found_index=3)
1257
+
1258
+
1259
+ if not item_arla:
1260
+ tributacao_icms_select.click()
1261
+ await worker_sleep(1)
1262
+ set_combobox("||List", "061 - 061- MONOFASICO")
1263
+ else:
1264
+ aliquota = None
1265
+ for item in conconfig_aliquota_icms:
1266
+ if cidade_cliente in item["estado"]:
1267
+ aliquota = item["aliquota"]
1268
+ break
1269
+
1270
+ if aliquota:
1271
+ console.print(f"A alíquota para o estado {cidade_cliente} é: {aliquota}")
1272
+ tributacao_icms_select.click()
1273
+ await worker_sleep(1)
1274
+ tributacao = f"000 - 000- ICMS - {aliquota}%"
1275
+ set_combobox("||List", tributacao)
1276
+ else:
1277
+ retorno = f"Estado {cidade_cliente} não encontrado \nEtapas Executadas:\n{steps}"
1278
+ return RpaRetornoProcessoDTO(
1279
+ sucesso=False,
1280
+ retorno=retorno,
1281
+ status=RpaHistoricoStatusEnum.Falha,
1282
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
1283
+ )
1284
+
1285
+ send_keys("%o")
1286
+
1287
+
1288
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1289
+ main_window = app["TFrmDadosFaturamentoPreVenda"]
1290
+ main_window.set_focus()
1291
+ send_keys("%m")
1292
+ await worker_sleep(2)
1293
+ pyautogui.hotkey('shift', 'left')
1294
+
1295
+ panel_tab_sheet = main_window.child_window(class_name="TcxTabSheet", found_index=0)
1296
+ field_observacao = panel_tab_sheet.child_window(class_name="TDBIMemo")
1297
+ text_campo_observacao = f"Nome do Motorista: {nota.get("nomeMotorista")} - Placa: {nota.get("placaClienteCorreto")} - Quilometragem do Veículo: {nota.get("quilometragemVeiculo")}"
1298
+ field_observacao.set_edit_text(text_campo_observacao)
1299
+ send_keys("%o")
1300
+ await worker_sleep(2)
1301
+
1302
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1303
+ main_window = app["Confirm"]
1304
+ main_window.set_focus()
1305
+
1306
+ btn_yes = main_window.child_window(class_name="TButton", found_index=1)
1307
+ btn_yes.click()
1308
+ await worker_sleep(5)
1309
+
1310
+ app = Application().connect(class_name="TFrmDadosFaturamentoPreVenda", timeout=60)
1311
+ main_window = app["TMessageForm"]
1312
+ main_window.set_focus()
1313
+ send_keys("%i")
1314
+ await worker_sleep(15)
1315
+
1316
+ app = Application().connect(class_name="TFrmAguarde", timeout=60)
1317
+ main_window = app["TppPrintDialog"]
1318
+ tpanel_btn_ok = main_window.child_window(class_name="TPanel", found_index=1)
1319
+ btn_ok_print_screen = tpanel_btn_ok.child_window(class_name="TButton", found_index=1)
1320
+ btn_ok_print_screen.click()
1321
+
1322
+ #NAVEGANDO NA TELA DE SALVAR RELATORIO
1323
+ tpanel_main_window = main_window.child_window(class_name="HWNDView", found_index=0)
1324
+ tpanel_element = tpanel_main_window.child_window(class_name="Element", found_index=0)
1325
+ tpanel_background = tpanel_element.child_window(class_name="PreviewBackground", found_index=0)
1326
+ field_diretorio_path = tpanel_background.child_window(class_name="AppControlHost", found_index=0)
1327
+
1328
+ username = getpass.getuser()
1329
+ path_to_txt = f"C:\\Users\\{username}\\Downloads\\NOVA VENDA {numero_cupom_fiscal}"
1330
+ field_diretorio_path.set_edit_text(path_to_txt)
1331
+
1332
+ main_window.set_focus()
1333
+ send_keys("%l")
1334
+ await worker_sleep(5)
1335
+
1336
+ with open(path_to_txt, 'rb') as file:
1337
+ file_bytes = io.BytesIO(file.read())
1338
+
1339
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1340
+ desArquivo = f"NOVA VENDA {numero_cupom_fiscal}.pdf"
1341
+ try:
1342
+ await send_file(historico_id, desArquivo, "pdf", file_bytes, file_extension="pdf")
1343
+ os.remove(path_to_txt)
1344
+ except Exception as e:
1345
+ result = f"Arquivo NOVA VENDA 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} !"
1346
+ console.print(result, style="bold red")
1347
+ return RpaRetornoProcessoDTO(
1348
+ sucesso=False,
1349
+ retorno=result,
1350
+ status=RpaHistoricoStatusEnum.Falha,
1351
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
1352
+ )
1353
+
1354
+
1355
+ app = Application().connect(class_name="TFrmProcessamentoFEe2", timeout=60)
1356
+ main_window = app["TFrmProcessamentoFEe2"]
1357
+ main_window.close()
1358
+ await worker_sleep(2)
1359
+
1360
+ app = Application().connect(class_name="TFrmGerenciadorNFe2", timeout=60)
1361
+ main_window = app["Confirm"]
1362
+ main_window.set_focus()
1363
+ send_keys("%n")
1364
+
1365
+
1366
+ #GERAR RELATORIO FINAL
1367
+ type_text_into_field("Rel. Boletim Caixa", app["TFrmMenuPrincipal"]["Edit"], True, "50")
1368
+ pyautogui.press("enter")
1369
+ await worker_sleep(2)
1370
+ pyautogui.press("enter")
1371
+ await worker_sleep(5)
1372
+
1373
+
1374
+ app = Application().connect(class_name="TFrmRelBoletimCaixa", timeout=60)
1375
+ main_window = app["TGroupBox"]
1376
+
1377
+ dt_inicio = main_window.child_window(class_name="TDBIEditDate", found_index=0)
1378
+ dt_inicio.set_edit_text(data_hoje)
1379
+ dt_final = main_window.child_window(class_name="TDBIEditDate", found_index=1)
1380
+ dt_final.set_edit_text(data_hoje)
1381
+
1382
+ #SELECIONANDO A ESPECIE
1383
+ select_especie = main_window.child_window(class_name="TDBIComboBox", found_index=0)
1384
+ select_especie.click()
1385
+ set_combobox("||List", "13 - DEVOLUCAO DE VENDA")
1386
+ send_keys("%g")
1387
+
1388
+ #CLICANDO NO ICONE DE IMPRIMIR
1389
+ await worker_sleep(2)
1390
+ screen_width, screen_height = pyautogui.size()
1391
+ x = 10
1392
+ y = screen_height - 280 - (96 * 2) / .254
1393
+ pyautogui.click(x,y)
1394
+
1395
+ #INSERINDO O DIRETORIO E SALVANDO O ARQUIVO
1396
+ app = Application().connect(title="Salvar Saída de Impressão como")
1397
+ main_window = app["Dialog"]
1398
+ console.print("Tela 'Salvar' encontrada!")
1399
+
1400
+ console.print("Interagindo com a tela 'Salvar'...\n")
1401
+ username = getpass.getuser()
1402
+ path_to_txt = f"C:\\Users\\{username}\\Downloads\\CAIXA 13 DEVOLUÇÃO {numero_cupom_fiscal}"
1403
+
1404
+ main_window.type_keys("%n")
1405
+ pyautogui.write(path_to_txt)
1406
+ await worker_sleep(1)
1407
+ main_window.type_keys("%l")
1408
+ console.print("Arquivo salvo com sucesso...\n")
1409
+ await worker_sleep(5)
1410
+
1411
+ txt = ""
1412
+ with open(f"{path_to_txt}.pdf", "rb") as f:
1413
+ reader = PdfReader(f)
1414
+ txt = ""
1415
+ for p in reader.pages:
1416
+ txt += p.extract_text()
1417
+
1418
+ ultimo_valor = txt[-1]
1419
+ penultimo_valor = txt[-2]
1420
+
1421
+ if ultimo_valor == penultimo_valor:
1422
+ console.print("Valores no relatorio corretamente gerados...\n")
1423
+ with open(path_to_txt, 'rb') as file:
1424
+ file_bytes = io.BytesIO(file.read())
1425
+
1426
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1427
+ desArquivo = f"CAIXA 13 DEVOLUÇÃO {numero_cupom_fiscal}.pdf"
1428
+ try:
1429
+ await send_file(historico_id, desArquivo, "pdf", file_bytes, file_extension="pdf")
1430
+ os.remove(path_to_txt)
1431
+ retorno = f"Processo de devolução executado com sucesso \nEtapas Executadas:\n{steps}"
1432
+
1433
+ try:
1434
+ url_retorno = nota.get("urlRetorno")
1435
+ identificador = nota.get("identificador")
1436
+
1437
+ if url_retorno and identificador:
1438
+ await post_partner(url_retorno, identificador, numero_nota_fiscal, valor_nota_fiscal)
1439
+ else:
1440
+ console.print("Não foi possivel obter o valor de urlRetorno/identificador")
1441
+ except:
1442
+ console.print(f"Erro ao obter os dados ou enviar a requisição: {e}")
1443
+
1444
+ return RpaRetornoProcessoDTO(
1445
+ sucesso=True,
1446
+ retorno=retorno,
1447
+ status=RpaHistoricoStatusEnum.Sucesso)
1448
+ except Exception as e:
1449
+ result = f"Arquivo CAIXA 13 DEVOLUÇÃO 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} !"
1450
+ console.print(result, style="bold red")
1451
+ return RpaRetornoProcessoDTO(
1452
+ sucesso=False,
1453
+ retorno=result,
1454
+ status=RpaHistoricoStatusEnum.Falha,
1455
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
1456
+ )
1457
+ else:
1458
+ return RpaRetornoProcessoDTO(
1459
+ sucesso=False,
1460
+ retorno=f"O valor de entrada {penultimo_valor} não esta batendo com o valor de saída {ultimo_valor}, por favor verificar. \nEtapas Executadas:\n{steps}",
1461
+ status=RpaHistoricoStatusEnum.Falha,
1462
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)]
1463
+ )
1464
+ except Exception as e:
1465
+ retorno = f"Não foi possivel concluir o processo de pré venda {e} \nEtapas Executadas:\n{steps}"
1466
+ return RpaRetornoProcessoDTO(
1467
+ sucesso=False,
1468
+ retorno=retorno,
1469
+ status=RpaHistoricoStatusEnum.Falha,
1470
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
1471
+ )
1472
+ else:
1473
+ retorno = f"{preenchimento_header_pre_venda.retorno} \nEtapas Executadas:\n{steps}"
1474
+ return RpaRetornoProcessoDTO(
1475
+ sucesso=False,
1476
+ retorno=retorno,
1477
+ status=RpaHistoricoStatusEnum.Falha,
1478
+ tags=[RpaTagDTO(descricao=RpaTagEnum.Tecnico)]
1479
+ )
1480
+ except Exception as ex:
1481
+ retorno = f"Erro Processo Devolução Prazo a Faturar: {str(ex)} \nEtapas Executadas:\n{steps}"
1482
+ logger.error(retorno)
1483
+ console.print(retorno, style="bold red")
1484
+ return RpaRetornoProcessoDTO(
1485
+ sucesso=False,
1486
+ retorno=retorno,
1487
+ status=RpaHistoricoStatusEnum.Falha,
1488
+ )