worker-automate-hub 0.5.831__py3-none-any.whl → 0.5.833__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.
@@ -2,6 +2,7 @@ import asyncio
2
2
  import warnings
3
3
  from datetime import datetime
4
4
  import json
5
+ import ast
5
6
  import io
6
7
  import pyautogui
7
8
  from pywinauto.application import Application
@@ -127,7 +128,7 @@ def normalize_config_entrada(cfg: dict) -> dict:
127
128
  for k in chaves_remover:
128
129
  cfg.pop(k, None)
129
130
  return cfg
130
-
131
+
131
132
 
132
133
  # --- fim do normalizador ---
133
134
 
@@ -148,6 +149,7 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
148
149
  descricao_fornecedor = nota.get("descricaoFornecedor", "")
149
150
  historico_id = task.historico_id
150
151
  cod_fornecedor = descricao_fornecedor.split(" - ")[0]
152
+ fornecedor = descricao_fornecedor.split(" - ")[1]
151
153
  identificador = nota.get("identificador", "")
152
154
  url_retorno = nota.get("urlRetorno", "")
153
155
  multiplicador_timeout = int(float(task.sistemas[0].timeout))
@@ -158,12 +160,40 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
158
160
  res = await get_notas_produtos(int(cod_fornecedor), int(empresa), itens)
159
161
  by_code = res.get("por_codigo", {}) or {} # dict dinâmico por código
160
162
 
163
+ # ========= EXTRAÇÃO DE UM CFOP (PRIMEIRO ENCONTRADO) =========
164
+ cfop = None # Apenas um CFOP em variável
165
+ for info in by_code.values():
166
+ notas_raw = info.get("notas") or []
167
+ # garante que seja lista
168
+ if isinstance(notas_raw, (str, int)):
169
+ notas_raw = [notas_raw]
170
+
171
+ achou = False
172
+ for n in notas_raw:
173
+ try:
174
+ # Caso venha como string de dict: "{'nota': '1401414', 'cfop': '1102'}"
175
+ if isinstance(n, str) and n.strip().startswith("{"):
176
+ nota_dict = ast.literal_eval(n)
177
+ elif isinstance(n, dict):
178
+ nota_dict = n
179
+ else:
180
+ nota_dict = None
181
+
182
+ if isinstance(nota_dict, dict) and "cfop" in nota_dict:
183
+ cfop = nota_dict["cfop"]
184
+ achou = True
185
+ break
186
+ except Exception:
187
+ continue
188
+ if achou:
189
+ break
190
+
161
191
  # Constrói os itens na estrutura usada no fluxo de UI
162
192
  itens_ui = []
163
- notas_encontradas = [] # acumula notas para deduplicar depois
193
+ notas_encontradas = [] # acumula apenas os números das notas (strings) para deduplicar depois
164
194
 
165
195
  for it in itens:
166
- # aceita "codigoProduto"/"quantidade" e "codigo"/"qtd"
196
+ # aceita "descricaoProduto" contendo o código, ou "codigo"/"codigoProduto"
167
197
  desc = it.get("descricaoProduto", "") or ""
168
198
  nums = re.findall(r"\d+", desc)
169
199
  if not nums:
@@ -178,7 +208,7 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
178
208
  else:
179
209
  cod = int(nums[0])
180
210
 
181
- # quantidade (como int)
211
+ # quantidade (como int > 0)
182
212
  qtd_raw = it.get("quantidade", it.get("qtd"))
183
213
  try:
184
214
  qtd = int(qtd_raw)
@@ -190,14 +220,35 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
190
220
  info = by_code.get(cod) or {}
191
221
  valor_unit = float(info.get("valorUnitario", 0) or 0)
192
222
 
193
- # Normaliza "notas" para lista de strings
194
- notas_item = info.get("notas") or []
195
- if isinstance(notas_item, (str, int)):
196
- notas_item = [notas_item]
197
- notas_item = [str(n) for n in notas_item]
223
+ # Normaliza "notas" para lista com os números das notas (strings)
224
+ notas_item_raw = info.get("notas") or []
225
+ if isinstance(notas_item_raw, (str, int)):
226
+ notas_item_raw = [notas_item_raw]
227
+
228
+ notas_item_nums = []
229
+ for n in notas_item_raw:
230
+ # 1) se já vier dict
231
+ if isinstance(n, dict):
232
+ nota_num = n.get("nota")
233
+ if nota_num is not None:
234
+ notas_item_nums.append(str(nota_num))
235
+ continue
236
+
237
+ # 2) se vier string de dict "{'nota': '1401414', 'cfop': '1102'}"
238
+ if isinstance(n, str) and n.strip().startswith("{"):
239
+ try:
240
+ d = ast.literal_eval(n)
241
+ if isinstance(d, dict) and d.get("nota") is not None:
242
+ notas_item_nums.append(str(d["nota"]))
243
+ continue
244
+ except Exception:
245
+ pass
246
+
247
+ # 3) fallback: manter como string (pode ser já o número)
248
+ notas_item_nums.append(str(n))
198
249
 
199
250
  # Acumula para a lista geral (será deduplicada depois)
200
- notas_encontradas.extend(notas_item)
251
+ notas_encontradas.extend(notas_item_nums)
201
252
 
202
253
  itens_ui.append(
203
254
  {
@@ -205,7 +256,7 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
205
256
  "quantidade": qtd,
206
257
  "valor_unitario": valor_unit,
207
258
  "valor_total_item": round(valor_unit * qtd, 2),
208
- "notas": notas_item, # mantém vínculo item↔notas
259
+ "notas": notas_item_nums, # vínculo item números das notas
209
260
  }
210
261
  )
211
262
 
@@ -220,11 +271,12 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
220
271
 
221
272
  data = {
222
273
  "nf_referencia": nf_ref, # ex.: ['1418727', '1410744']
223
- "itens": itens_ui, # cada item com suas notas
274
+ "itens": itens_ui, # cada item com suas notas (apenas números)
224
275
  "totais": {
225
276
  "valor_final": round(sum(i["valor_total_item"] for i in itens_ui), 2)
226
277
  },
227
278
  "itens_por_nota": itens_por_nota, # para uso direto no fluxo de UI
279
+ "cfop": cfop, # <<< CFOP único extraído e disponível no payload
228
280
  }
229
281
  # ========= FIM DA MONTAGEM DO DATA =========
230
282
 
@@ -316,11 +368,13 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
316
368
  app = Application().connect(class_name="TFrmPreVenda")
317
369
  main_window = app["TFrmPreVenda"]
318
370
  console.print("Verificar estado...")
319
- if estado != "RS":
320
- modelo = "DEVOLUÇÃO DE COMPRA DE MERCADORIAS SC"
371
+ cfop_dentro = ["5101", "5102", "5103", "5104", "1102"]
372
+ if cfop not in cfop_dentro:
373
+ modelo = "DEVOLUCAO DE COMPRA DE MERCADORIAS SC"
321
374
  else:
322
375
  modelo = "DEVOLUCAO DE COMPRA DE MERCADORIAS - TRIBUTADO"
323
376
 
377
+
324
378
  # Inserir modelo
325
379
  console.print("Inserir modelo...")
326
380
  select_modelo = main_window.child_window(
@@ -401,7 +455,22 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
401
455
  await worker_sleep(1)
402
456
  input_codigo.type_keys(codigo, with_spaces=True, set_foreground=True)
403
457
  keyboard.send_keys("{TAB}")
404
- await worker_sleep(1)
458
+ await worker_sleep(5)
459
+ try:
460
+ # Verificar item sem saldo
461
+ app_item_ss = Application().connect(class_name="TFrmPesquisaItem")
462
+ item_ss = app_item_ss["TFrmPesquisaItem"]
463
+ btn_ss = item_ss.child_window(
464
+ title="&Cancela", class_name="TDBIBitBtn").click_input()
465
+ # adiciona no dicionário de erros
466
+ itens_sem_saldo[codigo] = {
467
+ "quantidade": quantidade,
468
+ "valor_unitario": val_unitario,
469
+ }
470
+ continue
471
+
472
+ except:
473
+ pass
405
474
 
406
475
  # --- Unidade (UNI) ---
407
476
  console.print("Selecionar Unidade...")
@@ -471,7 +540,7 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
471
540
  had_saldo = True
472
541
  try:
473
542
  console.print("Verificar mensagem de saldo menor....")
474
- # img_saldo = r"C:\Users\automatehub\Documents\GitHub\worker-assets\emsys\saldo_menor.png"
543
+ # img_saldo = r"C:\Users\automatehub\Desktop\img_leo\saldo_menor.png"
475
544
  img_saldo = "assets\\devolucao_produtos\\saldo_menor.png"
476
545
  img_saldo_bool = False
477
546
 
@@ -885,7 +954,6 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
885
954
 
886
955
  # Inserir mensagem padrão
887
956
  console.print("Inserir mensagem...")
888
- fornecedor = "Disbal"
889
957
  lista_fornecedores = ["Disbal", "Pepsico", "Punta Balena"]
890
958
  mensagem = (
891
959
  "PRODUTOS VENCIDOS"
@@ -929,24 +997,33 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
929
997
  app = Application().connect(class_name="TFrmDadosTributacaoProdutoPreVenda")
930
998
  trib = app["TFrmDadosTributacaoProdutoPreVenda"]
931
999
 
932
- if estado == "RS":
1000
+ if "disbal" in fornecedor.lower():
1001
+ select_trib.select("020 - 020 - ICMS 12% RED. BASE 41,667")
1002
+
1003
+ elif "punta balena" in fornecedor.lower():
1004
+ select_trib.select("000 - 000 - ICMS - 12%")
1005
+
1006
+ elif "vitrola" in fornecedor.lower():
1007
+ select_trib.select("041 - 041 - ICMS - NAO INCIDENTE ")
1008
+
1009
+ elif estado == "RS" and "pepsico" in fornecedor.lower():
933
1010
  select_trib = trib.child_window(class_name="TDBIComboBox", found_index=4)
934
1011
  select_trib.select("051 - 051 - ICMS 17% RED BC 29,4118% - TRIBUT.CORRETA")
935
1012
  print("Selecionado: 051 - 051 - ICMS 17% RED BC 29,4118% - TRIBUT.CORRETA")
1013
+
1014
+ elif estado == "RS":
1015
+ select_trib = trib.child_window(class_name="TDBIComboBox", found_index=4)
1016
+ select_trib.select("051 - 051 - ICMS 17% RED BC 29,4118% - TRIBUT.CORRETA")
1017
+ print("Selecionado: 051 - 051 - ICMS 17% RED BC 29,4118% - TRIBUT.CORRETA")
1018
+
936
1019
  elif estado == "SC":
937
1020
  select_trib = trib.child_window(class_name="TDBIComboBox", found_index=4)
938
1021
  select_trib.select("000 - 000 - ICMS - 12%")
939
1022
  print("Selecionado: 000 - 000 - ICMS - 12%")
1023
+
940
1024
  else:
941
1025
  print("Estado diferente dos mapeados")
942
1026
 
943
- if fornecedor == "Disbal":
944
- select_trib.select("020 - 020 - ICMS 12% RED. BASE 41,667")
945
- elif fornecedor == "Punta Balena":
946
- select_trib.select("000 - 000 - ICMS - 12%")
947
- elif fornecedor == "Vitrola":
948
- select_trib.select("041 - 041 - ICMS - NAO INCIDENTE ")
949
-
950
1027
  await worker_sleep(2)
951
1028
 
952
1029
  trib.child_window(title="&OK", class_name="TBitBtn").click_input()
@@ -1109,3 +1186,4 @@ async def devolucao_produtos(task: RpaProcessoEntradaDTO) -> RpaRetornoProcessoD
1109
1186
  status=RpaHistoricoStatusEnum.Sucesso,
1110
1187
  tags=[RpaTagDTO(descricao=RpaTagEnum.Negocio)],
1111
1188
  )
1189
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: worker-automate-hub
3
- Version: 0.5.831
3
+ Version: 0.5.833
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
@@ -45,7 +45,7 @@ worker_automate_hub/tasks/jobs/descartes.py,sha256=wIi8n4vZrNE-03C5_lr4FmxuKoWSY
45
45
  worker_automate_hub/tasks/jobs/devolucao_ctf.py,sha256=7tdUihaDqjIf7POjM79EqKG0w-qqXbhC6jq6hteavkw,250822
46
46
  worker_automate_hub/tasks/jobs/devolucao_ctf_35.py,sha256=e9t5k2mtZcUcEGKPWysbWzsH_gqrK-6aBXjWe2jWfTg,253948
47
47
  worker_automate_hub/tasks/jobs/devolucao_prazo_a_faturar.py,sha256=kzPJazDRbz2CLn8tKja2Lg1N4UzTRF1V4Nc1elIqTGY,272145
48
- worker_automate_hub/tasks/jobs/devolucao_produtos.py,sha256=vL-bSlfQkT860EfeHgeXl5bXo5pSMu8KAQhyy9LxYAg,43342
48
+ worker_automate_hub/tasks/jobs/devolucao_produtos.py,sha256=0fhq7i4pxF-owwK8Lj3dWEsmIESMVweRpQU3Zt4c0cc,46688
49
49
  worker_automate_hub/tasks/jobs/ecac_estadual_go.py,sha256=dKkf22nH5gp3RErq5u0UzRsKyJ81fc6ZZ4vLtUuMwHA,21002
50
50
  worker_automate_hub/tasks/jobs/ecac_estadual_main.py,sha256=8WmKe4-MRtzHobXz2S4YBDNN8alfawkC-BBlRY-mn1g,1726
51
51
  worker_automate_hub/tasks/jobs/ecac_estadual_mt.py,sha256=C26zmpGQGUq6sP9lU9nanM3Fje-rkyx5tjwmRy4lyL8,25300
@@ -105,7 +105,7 @@ worker_automate_hub/utils/updater.py,sha256=en2FCGhI8aZ-JNP3LQm64NJDc4awCNW7UhbV
105
105
  worker_automate_hub/utils/util.py,sha256=rDp5h36I_kMfaCDD9xgcxibRXe5AYaImlXKhGbQ7DHE,211273
106
106
  worker_automate_hub/utils/utils_nfe_entrada.py,sha256=F7jk95LpDwl5WfaQXahCA5yDdnySnWdctDqczHXwGqE,38195
107
107
  worker_automate_hub/worker.py,sha256=zEnYUrm5kY2cHbbee15QJkwkx4euD2SB2zRvUIbjS90,6850
108
- worker_automate_hub-0.5.831.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
109
- worker_automate_hub-0.5.831.dist-info/METADATA,sha256=6pNtOIHZoutHosQh1yS12DN5KZpKB3sHCwqMMRFGTYg,3142
110
- worker_automate_hub-0.5.831.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
111
- worker_automate_hub-0.5.831.dist-info/RECORD,,
108
+ worker_automate_hub-0.5.833.dist-info/entry_points.txt,sha256=sddyhjx57I08RY8X7UxcTpdoOsWULAWNKN9Xr6pp_Kw,54
109
+ worker_automate_hub-0.5.833.dist-info/METADATA,sha256=qVom8MIpTMS_auXAR-oaAHDQWmAlQ_XRDl7ZKxbZq5Q,3142
110
+ worker_automate_hub-0.5.833.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
111
+ worker_automate_hub-0.5.833.dist-info/RECORD,,