worker-automate-hub 0.5.749__py3-none-any.whl → 0.5.912__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.
Files changed (36) hide show
  1. worker_automate_hub/api/client.py +186 -68
  2. worker_automate_hub/api/rpa_historico_service.py +1 -0
  3. worker_automate_hub/cli.py +91 -111
  4. worker_automate_hub/tasks/jobs/abertura_livros_fiscais.py +112 -229
  5. worker_automate_hub/tasks/jobs/descartes.py +91 -77
  6. worker_automate_hub/tasks/jobs/devolucao_produtos.py +1386 -0
  7. worker_automate_hub/tasks/jobs/entrada_de_notas_15.py +3 -46
  8. worker_automate_hub/tasks/jobs/entrada_de_notas_22.py +833 -0
  9. worker_automate_hub/tasks/jobs/entrada_de_notas_36.py +29 -9
  10. worker_automate_hub/tasks/jobs/entrada_de_notas_37.py +619 -0
  11. worker_automate_hub/tasks/jobs/entrada_de_notas_39.py +1 -1
  12. worker_automate_hub/tasks/jobs/entrada_de_notas_9.py +63 -16
  13. worker_automate_hub/tasks/jobs/extracao_dados_nielsen.py +504 -0
  14. worker_automate_hub/tasks/jobs/extracao_saldo_estoque.py +242 -108
  15. worker_automate_hub/tasks/jobs/extracao_saldo_estoque_fiscal.py +688 -0
  16. worker_automate_hub/tasks/jobs/fidc_gerar_nosso_numero.py +2 -2
  17. worker_automate_hub/tasks/jobs/fidc_remessa_cobranca_cnab240.py +25 -16
  18. worker_automate_hub/tasks/jobs/geracao_balancetes_filial.py +330 -0
  19. worker_automate_hub/tasks/jobs/importacao_extratos.py +538 -0
  20. worker_automate_hub/tasks/jobs/importacao_extratos_748.py +800 -0
  21. worker_automate_hub/tasks/jobs/inclusao_pedidos_ipiranga.py +222 -0
  22. worker_automate_hub/tasks/jobs/inclusao_pedidos_raizen.py +174 -0
  23. worker_automate_hub/tasks/jobs/inclusao_pedidos_vibra.py +327 -0
  24. worker_automate_hub/tasks/jobs/notas_faturamento_sap.py +438 -157
  25. worker_automate_hub/tasks/jobs/opex_capex.py +540 -326
  26. worker_automate_hub/tasks/jobs/sped_fiscal.py +8 -8
  27. worker_automate_hub/tasks/jobs/transferencias.py +52 -41
  28. worker_automate_hub/tasks/task_definitions.py +46 -1
  29. worker_automate_hub/tasks/task_executor.py +11 -0
  30. worker_automate_hub/utils/util.py +252 -215
  31. worker_automate_hub/utils/utils_nfe_entrada.py +1 -1
  32. worker_automate_hub/worker.py +1 -9
  33. {worker_automate_hub-0.5.749.dist-info → worker_automate_hub-0.5.912.dist-info}/METADATA +4 -2
  34. {worker_automate_hub-0.5.749.dist-info → worker_automate_hub-0.5.912.dist-info}/RECORD +36 -25
  35. {worker_automate_hub-0.5.749.dist-info → worker_automate_hub-0.5.912.dist-info}/WHEEL +1 -1
  36. {worker_automate_hub-0.5.749.dist-info → worker_automate_hub-0.5.912.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,222 @@
1
+ from worker_automate_hub.models.dto.rpa_historico_request_dto import (
2
+ RpaHistoricoStatusEnum,
3
+ RpaRetornoProcessoDTO,
4
+ RpaTagDTO,
5
+ RpaTagEnum,
6
+ )
7
+ from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
8
+ RpaProcessoEntradaDTO,
9
+ )
10
+ from rich.console import Console
11
+ import asyncio
12
+ from datetime import date, datetime
13
+ import re
14
+ from playwright.async_api import async_playwright
15
+ from worker_automate_hub.api.client import get_config_by_name
16
+ from worker_automate_hub.utils.util import capture_and_send_screenshot, kill_all_emsys
17
+
18
+ logger = Console()
19
+
20
+
21
+ async def inclusao_pedidos_ipiranga(task: RpaRetornoProcessoDTO):
22
+ try:
23
+ config_entrada = task.configEntrada
24
+ await kill_all_emsys()
25
+ # Collect configs
26
+ config_entrada = task.configEntrada
27
+ config = await get_config_by_name("ConsultaPreco")
28
+ config = config.conConfiguracao
29
+ async with async_playwright() as p:
30
+ browser = await p.chromium.launch(
31
+ headless=False,
32
+ args=[
33
+ "--disable-blink-features=AutomationControlled",
34
+ "--no-sandbox",
35
+ "--disable-dev-shm-usage",
36
+ "--disable-gpu",
37
+ "--disable-infobars",
38
+ "--window-size=1920,1080"
39
+ ]
40
+ )
41
+ page = await browser.new_page()
42
+ await page.set_viewport_size({"width": 1850, "height": 900})
43
+
44
+ # Going to Main page
45
+ logger.print(f"Navigating to {config.get('url_ipiranga')}")
46
+ await page.goto(
47
+ config.get("url_ipiranga"), wait_until="load")
48
+ # Wait page load
49
+ await page.wait_for_selector('[title="Login"]', timeout=90000)
50
+
51
+ # Login
52
+ logger.print(f"Logging")
53
+ login = config.get("login_ipiranga2") if config_entrada.get("cnpjEmpresa") == "07473735017661" else config.get("login_ipiranga")
54
+ await page.locator('[title="Login"]').type(login)
55
+ await page.locator('[type="password"]').type(config.get("pass_ipiranga"))
56
+ await page.locator('[type="submit"]').click()
57
+ try:
58
+ await asyncio.sleep(5)
59
+ warn = await page.wait_for_selector(
60
+ "//ul[contains(@style, '#ffd000')]/li[contains(text(), 'Usuário ou senha incorretos.')]",
61
+ timeout=10000,
62
+ )
63
+ if warn:
64
+ logger.print("Login failed. Verify username and password.")
65
+ await capture_and_send_screenshot(task.historico_id, "Erro")
66
+ raise Exception("Falha ao Logar no site.")
67
+ except:
68
+ logger.print("Login successful")
69
+ # Warn to change password
70
+ try:
71
+ await page.wait_for_selector(
72
+ '//*[@id="viewns_Z7_LA04H4G0POLN00QRBOJ72420P5_:form_lembrar:j_id_e"]',
73
+ timeout=5000,
74
+ )
75
+ await page.locator(
76
+ '//*[@id="viewns_Z7_LA04H4G0POLN00QRBOJ72420P5_:form_lembrar:j_id_e"]'
77
+ ).click()
78
+ except:
79
+ logger.print("No warning message.")
80
+
81
+ # Wait and accept cookies
82
+ logger.print("Identifiying cookies message")
83
+ await page.wait_for_selector("#onetrust-accept-btn-container")
84
+ try:
85
+ await page.locator("#onetrust-accept-btn-container").click()
86
+ except:
87
+ logger.print("Cookies already accepted.")
88
+ # Wait and close warning message
89
+ try:
90
+ await page.wait_for_selector(".newclose", timeout=10000)
91
+ await page.locator(".newclose").click()
92
+ except:
93
+ logger.print("No warning message.")
94
+
95
+ try:
96
+ await page.wait_for_selector("img.fechar", timeout=10000)
97
+ await page.locator("img.fechar").click()
98
+ except:
99
+ logger.print("No Ads message.")
100
+ cnpj_atual = await page.locator(".usuario_cnpj.mb-0").first.text_content()
101
+ if not config_entrada.get("cnpjEmpresa") in cnpj_atual:
102
+ # Select Gas Station
103
+ await page.wait_for_selector(".usuario_img", timeout=90000)
104
+ await page.locator(".usuario_img").first.click()
105
+ # Fill the station
106
+ logger.print("Selecting gas station")
107
+ change_station = page.locator('//*[@id="trocaMuitosPostosModal"]/div[2]/div/div')
108
+ await change_station.locator('[type="text"]').first.type(config_entrada.get("cnpjEmpresa"))
109
+ # cnpj = config_entrada.get("cnpjEmpresa")
110
+ # await page.locator(f'li[data-cdpessptoecli="{cnpj}"]').click()
111
+ await change_station.get_by_text("Trocar", exact=True).locator("visible=true").click()
112
+
113
+
114
+ await asyncio.sleep(5)
115
+ logger.print("Going to order page")
116
+ await page.goto(
117
+ "https://www.redeipiranga.com.br/wps/myportal/redeipiranga/pedidos/combustivel/registrarpedido/",
118
+ wait_until="load",
119
+ )
120
+ await asyncio.sleep(5)
121
+ # Get Iframe to collect locators
122
+ iframe = page.frame_locator('//*[@id="ns_Z7_LA04H4G0P0FDB061C74LHG2G17__content-frame"]')
123
+ await asyncio.sleep(20)
124
+ bases = await get_config_by_name("ipirangaBasesValue")
125
+ bases = bases.conConfiguracao
126
+ # Change Base
127
+ try:
128
+ base = bases[config_entrada["baseNome"]]
129
+ # await page.locator('//*[@id="frmPedido"]/section[1]/div[3]/div[1]/select').select_option(value=base)
130
+ await iframe.locator("select[name='codigoDependencia']").select_option(value=base)
131
+ await asyncio.sleep(2)
132
+
133
+ except:
134
+ await capture_and_send_screenshot(task.historico_id, "Erro")
135
+ raise Exception("Base não encontrada")
136
+ # Fill Fuels
137
+ logger.print("Filling Fuels")
138
+ await asyncio.sleep(2)
139
+ combusutiveis_ids = await get_config_by_name("ConsultaPrecoCombustiveisIds")
140
+ combusutiveis_ids = combusutiveis_ids.conConfiguracao["CombustiveisIds"]
141
+ xpath_ids = await get_config_by_name("ipirangaXpathCombustiveis")
142
+ xpath_ids = xpath_ids.conConfiguracao
143
+ for combustivel in config_entrada["combustiveis"]:
144
+ for id in combusutiveis_ids:
145
+ if id["uuid"] == combustivel["uuidItem"]:
146
+ fuel = iframe.locator(
147
+ f'.combustivel_box.clTrProdutos:has-text("{id['descricaoIpiranga']}")'
148
+ )
149
+ try:
150
+ indisponivel = await fuel.locator(
151
+ ".texto-indisponivel", timemout=5000
152
+ ).text_content()
153
+ if indisponivel:
154
+ await capture_and_send_screenshot(task.historico_id, "Erro")
155
+ raise Exception(f"{indisponivel}")
156
+ except:
157
+ pass
158
+ await fuel.locator(f'input[name="quantidade"]').fill(
159
+ str(combustivel["quantidade"])
160
+ )
161
+ await fuel.locator(f'input[name="quantidade"]').press("Tab")
162
+
163
+ # Next
164
+ logger.print("Going to next page")
165
+ await iframe.locator(
166
+ 'a[href="javascript:avancar()"]:has-text("Avançar")'
167
+ ).click()
168
+ await asyncio.sleep(5)
169
+ # Finish Order
170
+ logger.print("Finishing order")
171
+ await page.wait_for_selector(
172
+ "iframe#ns_Z7_LA04H4G0P0FDB061C74LHG2G17__content-frame"
173
+ )
174
+ iframe_final = page.frame_locator(
175
+ "iframe#ns_Z7_LA04H4G0P0FDB061C74LHG2G17__content-frame"
176
+ )
177
+ btn_finish = iframe_final.locator('button:has-text("Finalizar pedido")')
178
+ await btn_finish.scroll_into_view_if_needed()
179
+ await btn_finish.click(force=True)
180
+
181
+ await asyncio.sleep(30)
182
+ finish_iframe = page.frame_locator(
183
+ '//*[@id="ns_Z7_LA04H4G0P0FDB061C74LHG2G17__content-frame"]'
184
+ )
185
+ element = finish_iframe.locator(".titulo.titulo-area")
186
+ await element.scroll_into_view_if_needed()
187
+ text = await element.text_content()
188
+ text = " ".join(text.split())
189
+ numero_pedido = re.findall(r"\d+", text)
190
+ date = config_entrada["dataRetirada"]
191
+ date = datetime.fromisoformat(date)
192
+ if "sucesso" in text:
193
+ bof = {
194
+ "numero_pedido": numero_pedido[0],
195
+ "cnpj": config_entrada["cnpjEmpresa"],
196
+ "data": date.strftime("%d/%m/%Y"),
197
+ }
198
+ await capture_and_send_screenshot(
199
+ task.historico_id, "Sucesso ao realizar pedido!"
200
+ )
201
+ return RpaRetornoProcessoDTO(
202
+ sucesso=True,
203
+ retorno=str(bof),
204
+ status=RpaHistoricoStatusEnum.Sucesso,
205
+ )
206
+ else:
207
+ await capture_and_send_screenshot(task.historico_id, "Erro")
208
+ raise Exception(f"Erro ao realizar pedido: {text}")
209
+ except Exception as e:
210
+ logger.print(f"An error occurred: {e}")
211
+ await capture_and_send_screenshot(task.historico_id, "Erro")
212
+ return RpaRetornoProcessoDTO(
213
+ sucesso=False,
214
+ retorno=f"An error occurred: {e}",
215
+ status=RpaHistoricoStatusEnum.Falha,
216
+ tags=[
217
+ RpaTagDTO(descricao=RpaTagEnum.Tecnico),
218
+ RpaTagDTO(descricao=RpaTagEnum.Negocio),
219
+ ],
220
+ )
221
+ finally:
222
+ await browser.close()
@@ -0,0 +1,174 @@
1
+ from worker_automate_hub.models.dto.rpa_historico_request_dto import (
2
+ RpaHistoricoStatusEnum,
3
+ RpaRetornoProcessoDTO,
4
+ RpaTagDTO,
5
+ RpaTagEnum,
6
+ )
7
+ from worker_automate_hub.models.dto.rpa_processo_entrada_dto import (
8
+ RpaProcessoEntradaDTO,
9
+ )
10
+ from rich.console import Console
11
+ import asyncio
12
+ from datetime import date, datetime
13
+ import re
14
+ from playwright.async_api import async_playwright
15
+ from worker_automate_hub.api.client import get_config_by_name, get_mfa_code
16
+ from worker_automate_hub.utils.util import capture_and_send_screenshot, kill_all_emsys
17
+
18
+ logger = Console()
19
+
20
+ async def inclusao_pedidos_raizen(task: RpaRetornoProcessoDTO):
21
+ try:
22
+ await kill_all_emsys()
23
+ config_entrada = task.configEntrada
24
+ #Collect configs
25
+ config = await get_config_by_name("ConsultaPreco")
26
+ config = config.conConfiguracao
27
+ async with async_playwright() as p:
28
+ browser = await p.chromium.launch(headless=False, args=[
29
+ "--disable-blink-features=AutomationControlled",
30
+ "--no-sandbox",
31
+ "--disable-dev-shm-usage",
32
+ "--disable-gpu",
33
+ "--disable-infobars",
34
+ "--window-size=1920,1080"
35
+ ])
36
+
37
+ page = await browser.new_page()
38
+ await page.set_viewport_size({"width": 1850, "height": 900})
39
+ #Going to Main page
40
+ logger.print(f"Navigating to {config.get('url_raizen')}")
41
+ await page.goto(config.get('url_raizen'), wait_until="networkidle")
42
+
43
+ #Login
44
+ logger.print(f"Logging")
45
+ await page.locator("#signInName").type(config.get('login_raizen'))
46
+ await page.locator("#password").type(config.get('pass_raizen'))
47
+ await page.locator("#next").click()
48
+
49
+ logger.print("Waiting for verification code")
50
+ logger.print("Sending verification code")
51
+ await page.locator("#readOnlyEmail_ver_but_send").click()
52
+
53
+ await asyncio.sleep(60)
54
+ #chamar endpoint com código retornado
55
+ code = await get_mfa_code('mfa-raizen')
56
+ if code['status_code'] == 200:
57
+ await page.locator('//*[@id="readOnlyEmail_ver_input"]').type(str(code['code']))
58
+ await page.locator('//*[@id="readOnlyEmail_ver_but_verify"]').click()
59
+ else:
60
+ raise Exception("Failed to retrieve MFA code")
61
+
62
+ # Select Company
63
+ logger.print("Selecting company")
64
+ relacao_cod_raizen = await get_config_by_name("RelacaoCodigosRaizen")
65
+ relacao_cod_raizen = relacao_cod_raizen.conConfiguracao
66
+ await page.wait_for_selector('//*[@id="api"]/div/form/div[2]/app-select/div/div', state="visible")
67
+ await page.locator('//*[@id="api"]/div/form/div[2]/app-select/div/div').click()
68
+ cod_cnpj = str(relacao_cod_raizen[config_entrada['cnpjEmpresa']]).lstrip('0')
69
+ element = page.locator(f'text="{cod_cnpj} - SIM REDE DE POSTOS LTDA"')
70
+ await element.scroll_into_view_if_needed()
71
+ await element.click()
72
+ await page.locator('//*[@id="undefined"]').click()
73
+ await page.wait_for_load_state('load')
74
+ try:
75
+ await asyncio.sleep(5)
76
+ await page.locator("label.cso-radio-option:has-text('Combustíveis Claros')").click()
77
+ await page.locator("button span:has-text('Acessar')").click()
78
+ except:
79
+ logger.print("Radio button already selected or not available")
80
+ await asyncio.sleep(10)
81
+
82
+ await asyncio.sleep(15)
83
+ try:
84
+ await page.locator(".messages__popup__button_ok").click()
85
+ except:
86
+ pass
87
+ logger.print("Navegating to orders page")
88
+ await page.goto('https://portal.csonline.com.br/#/ordersfuels', wait_until="load")
89
+ await asyncio.sleep(5)
90
+ #Select Liters
91
+ logger.print("Selecting Liters")
92
+ litro_radio = page.locator("#orders-fuels-input-radio-L")
93
+ await litro_radio.wait_for(state='visible')
94
+ if not await litro_radio.is_checked():
95
+ await litro_radio.click()
96
+ await page.wait_for_timeout(10000)
97
+ await page.locator('//*[@id="undefined"]').click()
98
+ # Base
99
+ logger.print("Selecting base")
100
+ rel_base_raizen = await get_config_by_name("relacaoBaseRaizen")
101
+ rel_base_raizen = rel_base_raizen.conConfiguracao
102
+ base_nome = rel_base_raizen[config_entrada['baseNome']]
103
+ await page.locator('//*[@id="orders-fuels-div-dropdown-withdrawal-place"]').click()
104
+ await page.locator(f'//*[contains(text(), "{base_nome}")]').click()
105
+ # Date
106
+ logger.print("Selecting date")
107
+ date = config_entrada['dataRetirada']
108
+ date = datetime.fromisoformat(date)
109
+ date = date.strftime("%d/%m/%Y")
110
+ input_elem = page.locator("#orders-fuels-div-calendar-datepicker")
111
+ await input_elem.evaluate("(el, value) => { el.removeAttribute('readonly'); el.value = value; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); }", date)
112
+ # Veichle Sign
113
+ logger.print("Selecting vehicle sign")
114
+ await page.locator('//*[@id="orders-fuels-div-dropdown-plate-place-button"]').click()
115
+ await page.locator('//*[@id="orders-fuels-div-dropdown-plate-place-button"]').fill(config_entrada["placaVeiculo"].upper())
116
+ await page.locator(f'//*[contains(text(), "{config_entrada["placaVeiculo"]}")]').click()
117
+
118
+ #Fill Fuels
119
+ logger.print("Filling Fuels")
120
+ combusutiveis_ids = await get_config_by_name('ConsultaPrecoCombustiveisIds')
121
+ combusutiveis_ids = combusutiveis_ids.conConfiguracao
122
+ xpath_ids = await get_config_by_name('raizenXpathCombustiveis')
123
+ xpath_ids = xpath_ids.conConfiguracao
124
+ for combustivel in config_entrada['combustiveis']:
125
+ combustivel_uuid = combustivel['uuidItem']
126
+ xpath = xpath_ids[combustivel_uuid]
127
+ await page.locator(xpath).fill(str(combustivel['quantidade']))
128
+ await page.locator(xpath).click()
129
+
130
+ # Save order
131
+ logger.print("Saving order")
132
+ await asyncio.sleep(2)
133
+ await page.locator('//*[@id="orders-fuels-button-save"]').click()
134
+ try:
135
+ logger.print("Confirming order")
136
+ await page.get_by_text("Continuar mesmo assim").click()
137
+ except:
138
+ pass
139
+ await page.wait_for_load_state('load')
140
+ #Get order number
141
+ await asyncio.sleep(10)
142
+ numero_elem = page.locator('//span[contains(@class, "status__order-number__value")]')
143
+ numero_pedido = ( await numero_elem.inner_text()).strip()
144
+ if not numero_pedido:
145
+ await capture_and_send_screenshot(task.historico_id,"Número do pedido não encontrado!")
146
+ raise Exception("Número do pedido não encontrado!")
147
+ date = config_entrada["dataRetirada"]
148
+ date = datetime.fromisoformat(date)
149
+ bof = {
150
+ "numero_pedido": numero_pedido,
151
+ "cnpj": config_entrada["cnpjEmpresa"],
152
+ "data": date.strftime("%d/%m/%Y"),
153
+ }
154
+ await capture_and_send_screenshot(task.historico_id, "Sucesso ao realizar pedido!")
155
+ return RpaRetornoProcessoDTO(
156
+ sucesso=True,
157
+ retorno=str(bof),
158
+ status=RpaHistoricoStatusEnum.Sucesso,
159
+ )
160
+
161
+ except Exception as e:
162
+ logger.print(f"An error occurred: {e}")
163
+ await capture_and_send_screenshot(task.historico_id, "Erro ao realizar pedido!")
164
+ return RpaRetornoProcessoDTO(
165
+ sucesso=False,
166
+ retorno=f"An error occurred: {e}",
167
+ status=RpaHistoricoStatusEnum.Falha,
168
+ tags=[
169
+ RpaTagDTO(descricao=RpaTagEnum.Tecnico),
170
+ RpaTagDTO(descricao=RpaTagEnum.Negocio),
171
+ ],
172
+ )
173
+ finally:
174
+ await browser.close()