From a9b111bb8696cb6766e96c543f006aebfc71b497 Mon Sep 17 00:00:00 2001 From: Jacek Pyziak Date: Wed, 23 Oct 2024 16:10:32 +0200 Subject: [PATCH] Update code changes --- apilo.js | 587 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 423 insertions(+), 164 deletions(-) diff --git a/apilo.js b/apilo.js index 4849339..ed1f92f 100644 --- a/apilo.js +++ b/apilo.js @@ -1,10 +1,12 @@ // ==UserScript== // @name A -// @version 1 +// @version 2.0 // @grant none // ==/UserScript== -window.onload = function() { +(function() { + 'use strict'; + const currentUrl = window.location.href; const patterns = [ @@ -15,57 +17,212 @@ window.onload = function() { /^https:\/\/projectpro\.apilo\.com\/order\/order\/all\/?$/ ]; - if (patterns.some(pattern => pattern.test(currentUrl))) { - waitForTableAndSetImage(); - attachTableReloadListener(); + const orderDetailUrlPattern = /https:\/\/projectpro\.apilo\.com\/order\/order\/detail\/.*\?static=shipment/; + if (orderDetailUrlPattern.test(currentUrl)) { + handlePrintButton(); } - function waitForTableAndSetImage() { - const intervalId = setInterval(() => { - let dataTables_scrollBody = document.getElementsByClassName('dataTables_scrollBody'); - if (dataTables_scrollBody.length > 0) { - let dataTables_tbody = dataTables_scrollBody[0].getElementsByTagName('tbody')[0]; - let rows = dataTables_tbody.getElementsByTagName('tr'); + function handlePrintButton() { + const checkInterval = 250; + const maxRetries = 20; + let attempts = 0; - if (rows.length > 0) { - clearInterval(intervalId); // Zatrzymanie dalszego wykonywania setInterval - setImageToProduct(); + const intervalId = setInterval(() => { + const alertElevateElements = document.querySelectorAll('.alert-elevate'); + if (alertElevateElements.length > 0) { + let printButtons = []; + alertElevateElements.forEach(alert => { + const buttons = Array.from(alert.querySelectorAll('a')).filter(button => button.textContent.trim() === "Drukuj"); + printButtons = printButtons.concat(buttons); + }); + + if (printButtons.length > 0) { + clearInterval(intervalId); + const lastPrintButton = printButtons[printButtons.length - 1]; + lastPrintButton.click(); + waitForModalAndClickXprinter(); } } - }, 100); // Sprawdza co 100ms, można dostosować czas - } - function attachTableReloadListener() { - const table = document.querySelector('.dataTables_scrollBody table'); - if (table) { - // Tworzymy obserwatora zmian w DOM - const observer = new MutationObserver((mutationsList, observer) => { - for (const mutation of mutationsList) { - if (mutation.type === 'childList') { - // Wykonaj kod po zmianie w tabeli (dodanie/usunięcie wierszy) - console.log('Table content changed'); - waitForTableAndSetImage(); - break; // Zatrzymujemy iterację po pierwszej znalezionej zmianie + attempts++; + if (attempts > maxRetries) { + clearInterval(intervalId); + console.error("Nie znaleziono przycisku 'Drukuj' po maksymalnej liczbie prób."); } - } - }); - - // Konfiguracja obserwatora do nasłuchiwania zmian w zawartości tabeli - observer.observe(table.querySelector('tbody'), { childList: true }); - } + }, checkInterval); } + function waitForModalAndClickXprinter() { + const modalCheckInterval = 250; + const maxModalRetries = 20; + let modalAttempts = 0; + + const modalIntervalId = setInterval(() => { + const modal = document.querySelector('.modal'); + if (modal) { + const xprinterButton = Array.from(modal.querySelectorAll('a')).find(button => button.textContent.trim() === "Xprinter XP-420B"); + if (xprinterButton) { + clearInterval(modalIntervalId); + xprinterButton.click(); + } + } + + modalAttempts++; + if (modalAttempts > maxModalRetries) { + clearInterval(modalIntervalId); + console.error("Nie znaleziono przycisku 'Xprinter XP-420B' po maksymalnej liczbie prób."); + } + }, modalCheckInterval); + } + + if (patterns.some(pattern => pattern.test(currentUrl))) { + waitForElement('.dataTables_scrollBody').then(() => { + waitForTableAndSetImage(); + attachTableReloadListener(); + }).catch(error => { + console.error('Nie udało się znaleźć elementu .dataTables_scrollBody:', error); + }); + } + + const currentUrl2 = window.location.href; + const patternWarehouse = /^https:\/\/projectpro\.apilo\.com\/warehouse\/shipment\/new-for-order\/.+/; + + if (patternWarehouse.test(currentUrl2)) { + waitForElement('.kt-portlet__body').then(portletBody => { + const buttonContainer = createButtonContainer(); + portletBody.parentNode.insertBefore(buttonContainer, portletBody); + + const buttons = [ + createButton('Apaczka D2D Inpost', '#7039df', 'ApaczkaD2D'), + createButton('Furgonetka P2D Inpost', '#007bff', 'P2D.inpost', 'RZE14N||RZE14N'), + createButton('Furgonetka D2P Inpost', '#28a745', 'D2P.inpost'), + createButton('Furgonetka D2D Inpost', '#ff7800', 'D2D.inpostkurier'), + createButton('Furgonetka P2P Inpost', '#ffc107', 'P2P.inpost', 'RZE14N||RZE14N') + ]; + + buttons.forEach(button => buttonContainer.appendChild(button)); + }).catch(error => { + console.error('Nie udało się znaleźć elementu .kt-portlet__body:', error); + }); + } + + /** + * Funkcja oczekująca na pojawienie się elementu w DOM. + * @param {string|Element} selector - Selektor CSS lub bezpośredni element. + * @param {number} interval - Czas oczekiwania między próbami w ms. + * @param {number} retries - Maksymalna liczba prób. + * @returns {Promise} - Obietnica z elementem lub odrzucenie. + */ + function waitForElement(selector, interval = 500, retries = 10) { + return retryUntilSuccess(() => { + return new Promise((resolve, reject) => { + let element; + if (typeof selector === 'string') { + element = document.querySelector(selector); + } else if (selector instanceof Element) { + element = selector; + } + + if (element) { + resolve(element); + } else { + reject(`Element nie znaleziony: ${selector}`); + } + }); + }, interval, retries); + } + + /** + * Funkcja retryUntilSuccess próbuje wykonać funkcję do skutku z określonymi interwałami i limitami prób. + * @param {Function} fn - Funkcja zwracająca obietnicę. + * @param {number} interval - Czas oczekiwania między próbami w ms. + * @param {number} retries - Maksymalna liczba prób. + * @returns {Promise} - Obietnica rozwiązana lub odrzucona. + */ + function retryUntilSuccess(fn, interval = 500, retries = 10) { + return new Promise((resolve, reject) => { + const attempt = async () => { + try { + console.log(`Próba wykonania funkcji. Pozostało prób: ${retries}`); + const result = await fn(); + resolve(result); + } catch (err) { + if (retries === 0) { + console.error('Maksymalna liczba prób osiągnięta. Funkcja nie powiodła się:', err); + reject(err); + } else { + console.warn(`Nie znaleziono elementu. Próba ponowna za ${interval} ms. Pozostało prób: ${retries}`); + setTimeout(() => { + retries--; + attempt(); + }, interval); + } + } + }; + attempt(); + }); + } + + /** + * Funkcja oczekująca na pojawienie się tabeli i ustawiająca obrazki. + */ + function waitForTableAndSetImage() { + waitForElement('.dataTables_scrollBody').then(() => { + const dataTables_tbody = document.querySelector('.dataTables_scrollBody tbody'); + const rows = dataTables_tbody ? dataTables_tbody.getElementsByTagName('tr') : []; + + if (rows.length > 0) { + setImageToProduct(); + } else { + console.warn('Brak wierszy w tabeli. Czekam na pojawienie się danych...'); + // Można dodać dodatkowe logiki tutaj, jeśli potrzebne + } + }).catch(error => { + console.error('Nie udało się znaleźć tabeli .dataTables_scrollBody:', error); + }); + } + + /** + * Funkcja dołączająca nasłuchiwacz na zmiany w tabeli. + */ + function attachTableReloadListener() { + waitForElement('.dataTables_scrollBody table').then(table => { + const observer = new MutationObserver((mutationsList, observer) => { + for (const mutation of mutationsList) { + if (mutation.type === 'childList') { + console.log('Zawartość tabeli została zmieniona.'); + waitForTableAndSetImage(); + break; + } + } + }); + + const tbody = table.querySelector('tbody'); + if (tbody) { + observer.observe(tbody, { childList: true, subtree: true }); + console.log('Obserwator zmian w tabeli został ustawiony.'); + } else { + console.warn('Nie znaleziono tbody w tabeli.'); + } + }).catch(error => { + console.error('Nie udało się znaleźć tabeli do dołączenia obserwatora:', error); + }); + } + + /** + * Funkcja ustawiająca obrazki do produktów. + * @param {string} img - URL obrazka (opcjonalny). + */ function setImageToProduct(img = '') { - let dataTables_scrollBody = document.getElementsByClassName('dataTables_scrollBody'); - if (dataTables_scrollBody.length > 0) { - let dataTables_tbody = dataTables_scrollBody[0].getElementsByTagName('tbody')[0]; - let rows = dataTables_tbody.getElementsByTagName('tr'); + waitForElement('.dataTables_scrollBody').then(dataTablesScrollBody => { + const dataTables_tbody = dataTablesScrollBody.querySelector('tbody'); + const rows = dataTables_tbody ? dataTables_tbody.getElementsByTagName('tr') : []; for (let i = 0; i < rows.length; i++) { - let cells = rows[i].getElementsByTagName('td'); + const cells = rows[i].getElementsByTagName('td'); if (cells.length > 1) { - let secondCellText = cells[1].textContent.trim(); + const secondCellText = cells[1].textContent.trim(); let domain; if (secondCellText.includes('marianek.pl')) { @@ -77,37 +234,38 @@ window.onload = function() { } if (cells.length >= 5) { - let fifthCell = cells[4]; - let divsInFifthCell = fifthCell.children; + const fifthCell = cells[4]; + const divsInFifthCell = fifthCell.children; - for (let i = 0; i < divsInFifthCell.length; i++) { - let currentDiv = divsInFifthCell[i]; - let imgDiv = currentDiv.getElementsByTagName('div')[0]; - let dataDiv = currentDiv.getElementsByTagName('div')[1]; + for (let j = 0; j < divsInFifthCell.length; j++) { + const currentDiv = divsInFifthCell[j]; + const imgDiv = currentDiv.getElementsByTagName('div')[0]; + const dataDiv = currentDiv.getElementsByTagName('div')[1]; if (dataDiv) { - let skuText = dataDiv.innerHTML.match(/SKU:\s*([A-Za-z0-9-]+)/); + const skuMatch = dataDiv.innerHTML.match(/SKU:\s*([A-Za-z0-9-]+)/); - if (skuText && skuText[1]) { - getProductData(skuText[1], domain).then(data => { + if (skuMatch && skuMatch[1]) { + const sku = skuMatch[1]; + getProductData(sku, domain).then(data => { if (!data) { - console.log('Product not found:', skuText[1]); + console.log('Produkt nie znaleziony:', sku); return; } - console.log('Product found:', skuText[1]); + console.log('Produkt znaleziony:', sku); imgDiv.innerHTML = ''; const imgElement = makeImg(data); imgDiv.appendChild(imgElement); // Dodanie eventu na hover - imgElement.addEventListener('mouseover', function() { + imgElement.addEventListener('mouseover', () => { showLargeImage(data, imgElement); }); - imgElement.addEventListener('mouseout', function() { - hideLargeImage(); - }); + imgElement.addEventListener('mouseout', hideLargeImage); + }).catch(error => { + console.error('Błąd podczas pobierania danych produktu:', error); }); } } @@ -115,9 +273,16 @@ window.onload = function() { } } } - } + }).catch(error => { + console.error('Nie udało się ustawić obrazków do produktów:', error); + }); } + /** + * Funkcja tworząca element obrazka. + * @param {string} src - URL obrazka. + * @returns {HTMLImageElement} - Element img. + */ function makeImg(src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') { const img = document.createElement('img'); img.src = src; @@ -125,11 +290,22 @@ window.onload = function() { img.className = 'img-fluid center-block'; img.style.maxWidth = '48px'; img.style.maxHeight = '48px'; + img.style.cursor = 'pointer'; return img; } + /** + * Funkcja pokazująca powiększony obrazek przy najechaniu kursorem. + * @param {string} src - URL dużego obrazka. + * @param {HTMLImageElement} imgElement - Element img, na którym najechano. + */ function showLargeImage(src, imgElement) { + const existingLargeImg = document.getElementById('largeImagePreview'); + if (existingLargeImg) { + existingLargeImg.remove(); + } + const largeImg = document.createElement('img'); largeImg.src = src; largeImg.style.position = 'absolute'; @@ -138,13 +314,16 @@ window.onload = function() { largeImg.style.border = '1px solid #ccc'; largeImg.style.background = '#fff'; largeImg.style.zIndex = '1000'; - largeImg.style.top = imgElement.getBoundingClientRect().top + window.scrollY + 'px'; - largeImg.style.left = imgElement.getBoundingClientRect().left + imgElement.offsetWidth + 10 + 'px'; + largeImg.style.top = (imgElement.getBoundingClientRect().top + window.scrollY) + 'px'; + largeImg.style.left = (imgElement.getBoundingClientRect().left + imgElement.offsetWidth + 10) + 'px'; largeImg.id = 'largeImagePreview'; document.body.appendChild(largeImg); } + /** + * Funkcja ukrywająca powiększony obrazek. + */ function hideLargeImage() { const largeImg = document.getElementById('largeImagePreview'); if (largeImg) { @@ -152,6 +331,12 @@ window.onload = function() { } } + /** + * Funkcja pobierająca dane produktu na podstawie SKU i domeny. + * @param {string} sku - SKU produktu. + * @param {string} domain - Domena (marianek.pl lub pomysloweprezenty.pl). + * @returns {Promise} - URL obrazka lub null w przypadku błędu. + */ async function getProductData(sku, domain) { let url; if (domain === 'marianek.pl') { @@ -159,49 +344,46 @@ window.onload = function() { } else if (domain === 'pomysloweprezenty.pl') { url = `https://pomysloweprezenty.pl/api/v1/product.php?sku=${sku}`; } else { - console.error('Unsupported domain:', domain); + console.error('Niewspierana domena:', domain); return null; } try { const response = await fetch(url); if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); + throw new Error(`Błąd HTTP! status: ${response.status}`); } - const data = await response.json(); console.log(data); - return data.img; + const data = await response.json(); + console.log('Dane produktu:', data); + return data.img || null; } catch (error) { - console.error('Error fetching product data: ' + url, error); + console.error('Błąd podczas pobierania danych produktu:', url, error); return null; } } - const currentUrl2 = window.location.href; - const pattern = /^https:\/\/projectpro\.apilo\.com\/warehouse\/shipment\/new-for-order\/.+/; - - if (pattern.test(currentUrl2)) { - const portletBody = document.querySelector('.kt-portlet__body'); - if (portletBody) { - const buttonContainer = document.createElement('div'); - buttonContainer.className = 'custom-button-container'; - buttonContainer.style.display = 'flex'; - buttonContainer.style.gap = '10px'; - buttonContainer.style.marginBottom = '15px'; - portletBody.parentNode.insertBefore(buttonContainer, portletBody); - - const buttonP2D = createButton('Inpost P2D', '#007bff', 'P2D.inpost', 'RZE14N||RZE14N'); - const buttonD2D = createButton('Inpost D2D', '#ff7800', 'D2D.inpostkurier'); - const buttonD2P = createButton('Inpost D2P', '#28a745', 'D2P.inpost'); - const buttonP2P = createButton('Inpost P2P', '#ffc107', 'P2P.inpost', 'RZE14N||RZE14N'); - - buttonContainer.appendChild(buttonP2D); - buttonContainer.appendChild(buttonD2D); - buttonContainer.appendChild(buttonD2P); - buttonContainer.appendChild(buttonP2P); - } + /** + * Funkcja tworząca kontener na przyciski. + * @returns {HTMLDivElement} - Kontener z przyciskami. + */ + function createButtonContainer() { + const buttonContainer = document.createElement('div'); + buttonContainer.className = 'custom-button-container'; + buttonContainer.style.display = 'flex'; + buttonContainer.style.gap = '10px'; + buttonContainer.style.marginBottom = '15px'; + return buttonContainer; } + /** + * Funkcja tworząca przycisk. + * @param {string} text - Tekst na przycisku. + * @param {string} backgroundColor - Kolor tła przycisku. + * @param {string} method - Metoda wysyłki. + * @param {string|null} dropoffPoint - Punkt odbioru (opcjonalny). + * @returns {HTMLButtonElement} - Element przycisku. + */ function createButton(text, backgroundColor, method, dropoffPoint = null) { const button = document.createElement('button'); button.textContent = text; @@ -214,126 +396,203 @@ window.onload = function() { button.style.color = '#FFF'; button.style.border = 'none'; button.style.cursor = 'pointer'; + button.style.borderRadius = '4px'; + button.style.fontSize = '14px'; button.addEventListener('click', () => handleShipment(method, dropoffPoint)); return button; } + /** + * Funkcja obsługująca kliknięcie przycisku wysyłki. + * @param {string} method - Metoda wysyłki. + * @param {string|null} dropoffPoint - Punkt odbioru (opcjonalny). + */ async function handleShipment(method, dropoffPoint = null) { try { - await selectPackageType(); - await setShipmentMethod(method); - if (dropoffPoint) { - await setDropoffPoint(dropoffPoint); + if (method.startsWith('Apaczka')) { + console.log('Ustawianie wysyłki Apaczka...'); + await setCarrierAccount(); + await setPackageTypeApaczka(); + await setShipmentMethodApaczka(); + await setPreferencesContentApaczka(); + await setParcelWeight('1'); + await submitShipment(); + } else { + console.log(`Ustawianie wysyłki metodą: ${method}`); + await selectPackageType(); + await setShipmentMethod(method); + if (dropoffPoint) { + await setDropoffPoint(dropoffPoint); + } + await setParcelWeight('1'); + await submitShipment(); } - await setParcelWeight('1'); - await submitShipment(); + console.log('Wysyłka została pomyślnie ustawiona.'); } catch (error) { - console.error('Wystąpił błąd: ', error); + console.error('Wystąpił błąd podczas ustawiania wysyłki:', error); } } - function retryUntilSuccess(fn, interval = 500, retries = 10) { - return new Promise((resolve, reject) => { - const attempt = async () => { - try { - const result = await fn(); - resolve(result); - } catch (err) { - if (retries === 0) { - reject(err); - } else { - setTimeout(() => { - retries--; - attempt(); - }, interval); - } - } - }; - attempt(); - }); - } - - function selectPackageType() { + /** + * Funkcja ustawiająca konto przewoźnika. + * @returns {Promise} + */ + function setCarrierAccount() { return retryUntilSuccess(() => { return new Promise((resolve, reject) => { - const selectElement = document.getElementById('warehousebundle_shipment_packageType'); - if (selectElement) { - selectElement.value = 'package'; - const event = document.createEvent('HTMLEvents'); - event.initEvent('change', true, false); - selectElement.dispatchEvent(event); + const carrierAccountElement = document.getElementById('warehousebundle_shipment_carrierAccount'); + if (carrierAccountElement) { + carrierAccountElement.value = '17'; + const event = new Event('change', { bubbles: true }); + carrierAccountElement.dispatchEvent(event); + console.log('Konto przewoźnika ustawione na 17.'); resolve(); } else { - reject('Nie znaleziono elementu packageType'); + reject('Nie znaleziono elementu warehousebundle_shipment_carrierAccount'); } }); }); } - function setShipmentMethod(method) { + /** + * Funkcja ustawiająca typ paczki na "PACZKA" dla Apaczki. + * @returns {Promise} + */ + function setPackageTypeApaczka() { + return waitForElement('#warehousebundle_shipment_packageType').then(packageTypeElement => { + packageTypeElement.value = 'PACZKA'; + const event = new Event('change', { bubbles: true }); + packageTypeElement.dispatchEvent(event); + console.log('Typ paczki ustawiony na PACZKA.'); + }).catch(error => { + console.error('Nie udało się ustawić typu paczki:', error); + throw error; + }); + } + + /** + * Funkcja ustawiająca metodę wysyłki na "42" dla Apaczki. + * @returns {Promise} + */ + function setShipmentMethodApaczka() { return retryUntilSuccess(() => { return new Promise((resolve, reject) => { const methodElement = document.getElementById('warehousebundle_shipment_method'); if (methodElement) { - methodElement.value = method; - const methodEvent = document.createEvent('HTMLEvents'); - methodEvent.initEvent('change', true, false); - methodElement.dispatchEvent(methodEvent); + methodElement.value = '42'; + const event = new Event('change', { bubbles: true }); + methodElement.dispatchEvent(event); + console.log('Metoda wysyłki ustawiona na 42 (Apaczka).'); resolve(); } else { - reject('Nie znaleziono elementu shipment_method'); + reject('Nie znaleziono elementu warehousebundle_shipment_method'); } }); }); } + /** + * Funkcja ustawiająca preferencje zawartości na "prezent" dla Apaczki. + * @returns {Promise} + */ + function setPreferencesContentApaczka() { + return retryUntilSuccess(() => { + return new Promise((resolve, reject) => { + const contentElement = document.getElementById('warehousebundle_shipment_preferences_content'); + if (contentElement) { + contentElement.value = 'prezent'; + const event = new Event('input', { bubbles: true }); + contentElement.dispatchEvent(event); + console.log('Preferencje zawartości ustawione na "prezent".'); + resolve(); + } else { + reject('Nie znaleziono elementu warehousebundle_shipment_preferences_content'); + } + }); + }); + } + + /** + * Funkcja ustawiająca typ paczki dla innych metod niż Apaczka. + * @returns {Promise} + */ + function selectPackageType() { + return waitForElement('#warehousebundle_shipment_packageType').then(selectElement => { + selectElement.value = 'package'; + const event = new Event('change', { bubbles: true }); + selectElement.dispatchEvent(event); + console.log('Typ paczki ustawiony na package.'); + }).catch(error => { + console.error('Nie udało się ustawić typu paczki:', error); + throw error; + }); + } + + /** + * Funkcja ustawiająca metodę wysyłki. + * @param {string} method - Metoda wysyłki do ustawienia. + * @returns {Promise} + */ + function setShipmentMethod(method) { + return waitForElement('#warehousebundle_shipment_method').then(methodElement => { + methodElement.value = method; + const event = new Event('change', { bubbles: true }); + methodElement.dispatchEvent(event); + console.log(`Metoda wysyłki ustawiona na ${method}.`); + }).catch(error => { + console.error('Nie udało się ustawić metody wysyłki:', error); + throw error; + }); + } + + /** + * Funkcja ustawiająca punkt odbioru. + * @param {string} dropoffPoint - Punkt odbioru do ustawienia. + * @returns {Promise} + */ function setDropoffPoint(dropoffPoint) { - return retryUntilSuccess(() => { - return new Promise((resolve, reject) => { - const dropoffPointElement = document.getElementById('warehousebundle_shipment_preferences_dropoffPoint'); - if (dropoffPointElement) { - dropoffPointElement.value = dropoffPoint; - const dropoffPointEvent = document.createEvent('HTMLEvents'); - dropoffPointEvent.initEvent('change', true, false); - dropoffPointElement.dispatchEvent(dropoffPointEvent); - resolve(); - } else { - reject('Nie znaleziono elementu dropoffPoint'); - } - }); + return waitForElement('#warehousebundle_shipment_preferences_dropoffPoint').then(dropoffPointElement => { + dropoffPointElement.value = dropoffPoint; + const event = new Event('change', { bubbles: true }); + dropoffPointElement.dispatchEvent(event); + console.log(`Punkt odbioru ustawiony na ${dropoffPoint}.`); + }).catch(error => { + console.error('Nie udało się ustawić punktu odbioru:', error); + throw error; }); } + /** + * Funkcja ustawiająca wagę paczki. + * @param {string} weight - Waga paczki do ustawienia. + * @returns {Promise} + */ function setParcelWeight(weight) { - return retryUntilSuccess(() => { - return new Promise((resolve, reject) => { - const weightElement = document.getElementById('warehousebundle_shipment_shipmentParcels_0_weight'); - if (weightElement) { - weightElement.value = weight; - const weightEvent = document.createEvent('HTMLEvents'); - weightEvent.initEvent('change', true, false); - weightElement.dispatchEvent(weightEvent); - resolve(); - } else { - reject('Nie znaleziono elementu shipmentParcels_0_weight'); - } - }); + return waitForElement('#warehousebundle_shipment_shipmentParcels_0_weight').then(weightElement => { + weightElement.value = weight; + const event = new Event('change', { bubbles: true }); + weightElement.dispatchEvent(event); + console.log(`Waga paczki ustawiona na ${weight}.`); + }).catch(error => { + console.error('Nie udało się ustawić wagi paczki:', error); + throw error; }); } + /** + * Funkcja wysyłająca formularz wysyłki. + * @returns {Promise} + */ function submitShipment() { - return retryUntilSuccess(() => { - return new Promise((resolve, reject) => { - const submitButton = document.getElementById('warehousebundle_shipment_buttons_submit'); - if (submitButton) { - submitButton.click(); - resolve(); - } else { - reject('Nie znaleziono przycisku submit'); - } - }); + return waitForElement('#warehousebundle_shipment_buttons_submit').then(submitButton => { + submitButton.click(); + console.log('Przycisk submit został kliknięty.'); + }).catch(error => { + console.error('Nie udało się znaleźć przycisku submit:', error); + throw error; }); } -} + +})();