Brak zmian w kodzie.

This commit is contained in:
2025-03-11 17:54:39 +01:00
parent a49f7248f4
commit 9bb837d5fc
2 changed files with 614 additions and 402 deletions

405
apilo-bck
View File

@@ -1,130 +1,339 @@
static public function apilo_product_search()
{
global $mdb, $settings, $config;
$sku = $mdb -> get( 'pp_shop_products', 'sku', [ 'id' => \S::get( 'product_id' ) ] );
$ean = $mdb -> get( 'pp_shop_products', 'ean', [ 'id' => \S::get( 'product_id' ) ] );
if ( !$sku and !$ean )
{
echo json_encode( [ 'status' => 'error', 'msg' => 'Podany produkt nie posiada kodu SKU ani EAN.' ] );
exit;
}
$url = "https://projectpro.apilo.com/rest/api/warehouse/product/";
$params = [];
if ($sku) {
$params['sku'] = $sku;
const currentUrl = window.location.href;
console.log(currentUrl);
const patterns = [
/^https:\/\/projectpro\.apilo\.com\/order\/order\/news\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/in-progress\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/to-send\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/completed\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/all\/?$/
];
if (patterns.some(pattern => pattern.test(currentUrl))) {
waitForTableAndSetImage();
attachTableReloadListener();
} }
// if ($ean) {
// $params['ean'] = $ean;
// }
$url .= '?' . http_build_query($params); 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');
$ch = curl_init($url); if (rows.length > 0) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); clearInterval(intervalId);
curl_setopt($ch, CURLOPT_HTTPHEADER, [ setImageToProduct();
"Authorization: Bearer " . $config['apilo']['access-token'], }
"Accept: application/json" }
]); }, 100);
}
$response = curl_exec($ch); function attachTableReloadListener() {
$responseData = json_decode($response, true); const table = document.querySelector('.dataTables_scrollBody table');
if (table) {
if (curl_errno($ch)) { const observer = new MutationObserver((mutationsList, observer) => {
echo 'Błąd cURL: ' . curl_error($ch); for (const mutation of mutationsList) {
} else { if (mutation.type === 'childList') {
if ($responseData && isset($responseData['products'])) { waitForTableAndSetImage();
foreach ($responseData['products'] as $product) { break;
echo "Nazwa produktu: " . $product['name'] . "<br>";
echo "SKU: " . $product['sku'] . "<br>";
echo "EAN: " . $product['ean'] . "<br><hr>";
} }
} else { }
echo "Brak wyników dla podanego SKU lub EAN."; });
}
observer.observe(table.querySelector('tbody'), { childList: true });
}
} }
curl_close($ch); function setImageToProduct(img = '') {
exit; 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');
// $refreshUrl = "https://projectpro.apilo.com/rest/auth/token/?grant_type=refresh_token&refresh_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwcm9qZWN0cHJvLmFwaWxvLmNvbSIsImV4cCI6MTcwNDA2NDE3MywianRpIjoiZTJjZDI4MWItZmU3NS01YTIyLWI4MGYtM2MyNTI3MmViZjVjIiwidHlwZSI6InJlZnJlc2hfdG9rZW4iLCJjbGllbnRfaWQiOjIsInBsYXRmb3JtX2lkIjoyLCJpYXQiOjE2OTg3OTM3NzN9.QUXHq9_9ERSrTqtbx50ZE_h_uN32ai112k-JqmSD9TZg4RsJxyzA13PeIulAWVa2ZeEJolvB-X2XyU7Ok__dhRYtNEUs-2HQgoa9sX1LAUlnUyABkY5hXOMpRNztrZ_BJMl_Ttj4GkwEOGlP8Ze0JNXaqmio0d1Bbbc6DtYfzHtkqgzl_mImIBtIXmBpypP3nVgz9GtKq9eOxfczQsWsUv5OBmCBDSF3O6yJA9r7jLOgSo1_MOH1MYai6xd_23FFlTcOvQUUwmnI6EMe3ytIpfuegEPuhXMPY8FCa0tWGhuBx2jtPBzQRQdJW7dzk3rEQX495lhE3cwK_T0PPjDBJ6HaYUoA5sTiF-9S1JfysS5D-Jd7z-m2KNVW8FPz1Zz200U2k2wfAs64NT9NeDPVkEcBJ5GFmOFvCGw4ywosWuQVQx0YxfzF65becLKxddPRS1MC9_-NxxL4ergClbPA2_e2Qwkg2EXWhil6cAwGy2G7C80t2NGN5aP1UL_uH2FQZ8VBdW_R5KvAXZDJsWSJqvn7pinLqTollMoMipbyQA02jaUvIk7senIF-h3f4DHbj90I97dekyzUUcbppKVhBfF6ZsfeFUojbT-GUapjakOwz3uL2dNEXOENUQMn3bsnQmkQABsGQrhQZjnPc-mdEm0PJJz0rK8QdZ2cQHYgo4g"; for (let i = 0; i < rows.length; i++) {
let cells = rows[i].getElementsByTagName('td');
// $ch = curl_init($refreshUrl); if (cells.length > 1) {
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); let secondCellText = cells[1].textContent.trim();
// curl_setopt($ch, CURLOPT_HTTPHEADER, [ let domain;
// "Authorization: Basic " . base64_encode($config['apilo']['client-id'] . ":" . $config['apilo']['client-secret']),
// "Accept: application/json"
// ]);
// $refreshResponse = curl_exec($ch); if (secondCellText.includes('marianek.pl')) {
domain = 'marianek.pl';
} else if (secondCellText.includes('pomysloweprezenty.pl')) {
domain = 'pomysloweprezenty.pl';
} else {
continue;
}
// if (curl_errno($ch)) { if (cells.length >= 5) {
// echo 'Błąd cURL: ' . curl_error($ch); let fifthCell = cells[4];
// } else { let divsInFifthCell = fifthCell.children;
// $newTokens = json_decode($refreshResponse, true);
// echo "Nowy access token: " . $newTokens['accessToken'];
// // Zapisz nowy access token i refresh token w sesji lub bazie danych for (let i = 0; i < divsInFifthCell.length; i++) {
// // $_SESSION['accessToken'] = $newTokens['accessToken']; let currentDiv = divsInFifthCell[i];
// // $_SESSION['refreshToken'] = $newTokens['refreshToken']; let imgDiv = currentDiv.getElementsByTagName('div')[0];
// } let dataDiv = currentDiv.getElementsByTagName('div')[1];
// curl_close($ch); if (dataDiv) {
// exit; let skuText = dataDiv.innerHTML.match(/SKU:\s*([A-Za-z0-9-]+)/);
// $url = "https://projectpro.apilo.com/rest/auth/token/?grant_type=authorization_code&code=" . $config['apilo']['authorization-code']; if (skuText && skuText[1]) {
getProductData(skuText[1], domain).then(data => {
if (!data) {
console.log('Product not found:', skuText[1]);
return;
}
// $ch = curl_init( $url ); console.log('Product found:', skuText[1]);
// curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); imgDiv.innerHTML = '';
// curl_setopt( $ch, CURLOPT_HTTPHEADER, [ const imgElement = makeImg(data);
// "Authorization: Basic " . base64_encode( $config['apilo']['client-id'] . ":" . $config['apilo']['client-secret'] ), imgDiv.appendChild(imgElement);
// "Accept: application/json"
// ] );
// $response = curl_exec($ch); imgElement.addEventListener('mouseover', function() {
showLargeImage(data, imgElement);
});
// if( curl_errno( $ch ) ) { imgElement.addEventListener('mouseout', function() {
// echo 'Błąd cURL: ' . curl_error( $ch ); hideLargeImage();
// } else { });
// echo $response; });
// } }
}
}
}
}
}
}
}
// curl_close( $ch ); function makeImg(src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') {
const img = document.createElement('img');
img.src = src;
img.alt = 'image';
img.className = 'img-fluid center-block';
img.style.maxWidth = '48px';
img.style.maxHeight = '48px';
// $data = json_decode($response, true); return img;
}
// $currentDateTime = new DateTime(); function showLargeImage(src, imgElement) {
// $tokenExpiryDateTime = DateTime::createFromFormat( DateTime::ATOM, $data['accessTokenExpireAt']); const largeImg = document.createElement('img');
largeImg.src = src;
largeImg.style.position = 'absolute';
largeImg.style.maxWidth = '400px';
largeImg.style.maxHeight = '400px';
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.id = 'largeImagePreview';
// // Sprawdzamy czy accessToken wygasł document.body.appendChild(largeImg);
// if ( $tokenExpiryDateTime <= $currentDateTime) { }
// // Token wygasł, odświeżamy go używając refreshToken
// // $refreshUrl = "https://projectpro.apilo.com/rest/auth/token/?grant_type=refresh_token&refresh_token=" . $data['refreshToken'];
// // curl_setopt( $ch, CURLOPT_URL, $refreshUrl ); function hideLargeImage() {
// // curl_setopt( $ch, CURLOPT_HTTPHEADER, [ const largeImg = document.getElementById('largeImagePreview');
// // "Authorization: Basic " . base64_encode( $config['apilo']['client-id'] . ":" . $config['apilo']['client-secret'] ), if (largeImg) {
// // "Accept: application/json" largeImg.remove();
// // ] ); }
}
// // $refreshResponse = curl_exec($ch); async function getProductData(sku, domain) {
let url;
if (domain === 'marianek.pl') {
url = `https://marianek.pl/api/v1/product.php?sku=${sku}`;
} else if (domain === 'pomysloweprezenty.pl') {
url = `https://pomysloweprezenty.pl/api/v1/product.php?sku=${sku}`;
} else {
console.error('Unsupported domain:', domain);
return null;
}
// // if (curl_errno($ch)) { try {
// // echo 'Błąd cURL podczas odświeżania: ' . curl_error($ch); const response = await fetch(url);
// // exit; if (!response.ok) {
// // } throw new Error(`HTTP error! status: ${response.status}`);
}
// // $refreshedData = json_decode($refreshResponse, true); const data = await response.json(); console.log(data);
// echo "Odświeżony token: " . $refreshedData['accessToken']; return data.img;
// } else { } catch (error) {
// echo "Token jest ważny."; console.error('Error fetching product data: ' + url, error);
// } return null;
}
}
// curl_close($ch); const currentUrl2 = window.location.href;
exit; 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);
}
}
function createButton(text, backgroundColor, method, dropoffPoint = null) {
const button = document.createElement('button');
button.textContent = text;
button.style.background = backgroundColor;
button.style.display = 'inline-flex';
button.style.width = '200px';
button.style.height = '40px';
button.style.alignItems = 'center';
button.style.justifyContent = 'center';
button.style.color = '#FFF';
button.style.border = 'none';
button.style.cursor = 'pointer';
button.addEventListener('click', () => handleShipment(method, dropoffPoint));
return button;
}
async function handleShipment(method, dropoffPoint = null) {
try {
await selectPackageType();
await setShipmentMethod(method);
if (dropoffPoint) {
await setDropoffPoint(dropoffPoint);
}
await setParcelWeight('1');
await submitShipment();
} catch (error) {
console.error('Wystąpił błąd: ', 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() {
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);
resolve();
} else {
reject('Nie znaleziono elementu packageType');
}
});
});
}
function setShipmentMethod(method) {
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);
resolve();
} else {
reject('Nie znaleziono elementu shipment_method');
}
});
});
}
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');
}
});
});
}
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');
}
});
});
}
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');
}
});
});
}

611
apilo.js
View File

@@ -1,336 +1,339 @@
// ==UserScript==
// @name A
// @version 1
// @grant none
// ==/UserScript==
const currentUrl = window.location.href;
const patterns = [
/^https:\/\/projectpro\.apilo\.com\/order\/order\/news\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/in-progress\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/to-send\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/completed\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/all\/?$/
];
if (patterns.some(pattern => pattern.test(currentUrl))) {
waitForTableAndSetImage();
attachTableReloadListener();
const currentUrl = window.location.href;
console.log(currentUrl);
const patterns = [
/^https:\/\/projectpro\.apilo\.com\/order\/order\/news\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/in-progress\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/to-send\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/completed\/?$/,
/^https:\/\/projectpro\.apilo\.com\/order\/order\/all\/?$/
];
if (patterns.some(pattern => pattern.test(currentUrl))) {
waitForTableAndSetImage();
attachTableReloadListener();
}
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');
if (rows.length > 0) {
clearInterval(intervalId);
setImageToProduct();
}
}
}, 100);
}
function attachTableReloadListener() {
const table = document.querySelector('.dataTables_scrollBody table');
if (table) {
const observer = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
waitForTableAndSetImage();
break;
}
}
});
observer.observe(table.querySelector('tbody'), { childList: true });
} }
}
function waitForTableAndSetImage() { function setImageToProduct(img = '') {
const intervalId = setInterval(() => { let dataTables_scrollBody = document.getElementsByClassName('dataTables_scrollBody');
let dataTables_scrollBody = document.getElementsByClassName('dataTables_scrollBody'); if (dataTables_scrollBody.length > 0) {
if (dataTables_scrollBody.length > 0) { let dataTables_tbody = dataTables_scrollBody[0].getElementsByTagName('tbody')[0];
let dataTables_tbody = dataTables_scrollBody[0].getElementsByTagName('tbody')[0]; let rows = dataTables_tbody.getElementsByTagName('tr');
let rows = dataTables_tbody.getElementsByTagName('tr');
if (rows.length > 0) { for (let i = 0; i < rows.length; i++) {
clearInterval(intervalId); // Zatrzymanie dalszego wykonywania setInterval let cells = rows[i].getElementsByTagName('td');
setImageToProduct();
if (cells.length > 1) {
let secondCellText = cells[1].textContent.trim();
let domain;
if (secondCellText.includes('marianek.pl')) {
domain = 'marianek.pl';
} else if (secondCellText.includes('pomysloweprezenty.pl')) {
domain = 'pomysloweprezenty.pl';
} else {
continue;
}
if (cells.length >= 5) {
let fifthCell = cells[4];
let 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];
if (dataDiv) {
let skuText = dataDiv.innerHTML.match(/SKU:\s*([A-Za-z0-9-]+)/);
if (skuText && skuText[1]) {
getProductData(skuText[1], domain).then(data => {
if (!data) {
console.log('Product not found:', skuText[1]);
return;
}
console.log('Product found:', skuText[1]);
imgDiv.innerHTML = '';
const imgElement = makeImg(data);
imgDiv.appendChild(imgElement);
imgElement.addEventListener('mouseover', function() {
showLargeImage(data, imgElement);
});
imgElement.addEventListener('mouseout', function() {
hideLargeImage();
});
});
} }
} }
}, 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
} }
} }
}); }
// Konfiguracja obserwatora do nasłuchiwania zmian w zawartości tabeli
observer.observe(table.querySelector('tbody'), { childList: true });
} }
} }
}
function setImageToProduct(img = '') { function makeImg(src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') {
let dataTables_scrollBody = document.getElementsByClassName('dataTables_scrollBody'); const img = document.createElement('img');
if (dataTables_scrollBody.length > 0) { img.src = src;
let dataTables_tbody = dataTables_scrollBody[0].getElementsByTagName('tbody')[0]; img.alt = 'image';
let rows = dataTables_tbody.getElementsByTagName('tr'); img.className = 'img-fluid center-block';
img.style.maxWidth = '48px';
img.style.maxHeight = '48px';
for (let i = 0; i < rows.length; i++) { return img;
let cells = rows[i].getElementsByTagName('td'); }
if (cells.length > 1) { function showLargeImage(src, imgElement) {
let secondCellText = cells[1].textContent.trim(); const largeImg = document.createElement('img');
let domain; largeImg.src = src;
largeImg.style.position = 'absolute';
largeImg.style.maxWidth = '400px';
largeImg.style.maxHeight = '400px';
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.id = 'largeImagePreview';
if (secondCellText.includes('marianek.pl')) { document.body.appendChild(largeImg);
domain = 'marianek.pl'; }
} else if (secondCellText.includes('pomysloweprezenty.pl')) {
domain = 'pomysloweprezenty.pl';
} else {
continue;
}
if (cells.length >= 5) { function hideLargeImage() {
let fifthCell = cells[4]; const largeImg = document.getElementById('largeImagePreview');
let divsInFifthCell = fifthCell.children; if (largeImg) {
largeImg.remove();
}
}
for (let i = 0; i < divsInFifthCell.length; i++) { async function getProductData(sku, domain) {
let currentDiv = divsInFifthCell[i]; let url;
let imgDiv = currentDiv.getElementsByTagName('div')[0]; if (domain === 'marianek.pl') {
let dataDiv = currentDiv.getElementsByTagName('div')[1]; url = `https://marianek.pl/api/v1/product.php?sku=${sku}`;
} else if (domain === 'pomysloweprezenty.pl') {
url = `https://pomysloweprezenty.pl/api/v1/product.php?sku=${sku}`;
} else {
console.error('Unsupported domain:', domain);
return null;
}
if (dataDiv) { try {
let skuText = dataDiv.innerHTML.match(/SKU:\s*([A-Za-z0-9-]+)/); const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (skuText && skuText[1]) { const data = await response.json(); console.log(data);
getProductData(skuText[1], domain).then(data => { return data.img;
if (!data) { } catch (error) {
console.log('Product not found:', skuText[1]); console.error('Error fetching product data: ' + url, error);
return; return null;
} }
}
console.log('Product found:', skuText[1]); const currentUrl2 = window.location.href;
imgDiv.innerHTML = ''; const pattern = /^https:\/\/projectpro\.apilo\.com\/warehouse\/shipment\/new-for-order\/.+/;
const imgElement = makeImg(data);
imgDiv.appendChild(imgElement);
// Dodanie eventu na hover if (pattern.test(currentUrl2)) {
imgElement.addEventListener('mouseover', function() { const portletBody = document.querySelector('.kt-portlet__body');
showLargeImage(data, imgElement); 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);
imgElement.addEventListener('mouseout', function() { const buttonP2D = createButton('Inpost P2D', '#007bff', 'P2D.inpost', 'RZE14N||RZE14N');
hideLargeImage(); 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);
} }
}
function createButton(text, backgroundColor, method, dropoffPoint = null) {
const button = document.createElement('button');
button.textContent = text;
button.style.background = backgroundColor;
button.style.display = 'inline-flex';
button.style.width = '200px';
button.style.height = '40px';
button.style.alignItems = 'center';
button.style.justifyContent = 'center';
button.style.color = '#FFF';
button.style.border = 'none';
button.style.cursor = 'pointer';
button.addEventListener('click', () => handleShipment(method, dropoffPoint));
return button;
}
async function handleShipment(method, dropoffPoint = null) {
try {
await selectPackageType();
await setShipmentMethod(method);
if (dropoffPoint) {
await setDropoffPoint(dropoffPoint);
}
await setParcelWeight('1');
await submitShipment();
} catch (error) {
console.error('Wystąpił błąd: ', 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 makeImg(src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') { function selectPackageType() {
const img = document.createElement('img'); return retryUntilSuccess(() => {
img.src = src; return new Promise((resolve, reject) => {
img.alt = 'image'; const selectElement = document.getElementById('warehousebundle_shipment_packageType');
img.className = 'img-fluid center-block'; if (selectElement) {
img.style.maxWidth = '48px'; selectElement.value = 'package';
img.style.maxHeight = '48px'; const event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
return img; selectElement.dispatchEvent(event);
} resolve();
function showLargeImage(src, imgElement) {
const largeImg = document.createElement('img');
largeImg.src = src;
largeImg.style.position = 'absolute';
largeImg.style.maxWidth = '400px';
largeImg.style.maxHeight = '400px';
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.id = 'largeImagePreview';
document.body.appendChild(largeImg);
}
function hideLargeImage() {
const largeImg = document.getElementById('largeImagePreview');
if (largeImg) {
largeImg.remove();
}
}
async function getProductData(sku, domain) {
let url;
if (domain === 'marianek.pl') {
url = `https://marianek.pl/api/v1/product.php?sku=${sku}`;
} else if (domain === 'pomysloweprezenty.pl') {
url = `https://pomysloweprezenty.pl/api/v1/product.php?sku=${sku}`;
} else { } else {
console.error('Unsupported domain:', domain); reject('Nie znaleziono elementu packageType');
return null;
} }
});
});
}
try { function setShipmentMethod(method) {
const response = await fetch(url); return retryUntilSuccess(() => {
if (!response.ok) { return new Promise((resolve, reject) => {
throw new Error(`HTTP error! status: ${response.status}`); const methodElement = document.getElementById('warehousebundle_shipment_method');
} if (methodElement) {
methodElement.value = method;
const data = await response.json(); console.log(data); const methodEvent = document.createEvent('HTMLEvents');
return data.img; methodEvent.initEvent('change', true, false);
} catch (error) { methodElement.dispatchEvent(methodEvent);
console.error('Error fetching product data: ' + url, error); resolve();
return null; } else {
reject('Nie znaleziono elementu shipment_method');
} }
} });
});
}
const currentUrl2 = window.location.href; function setDropoffPoint(dropoffPoint) {
const pattern = /^https:\/\/projectpro\.apilo\.com\/warehouse\/shipment\/new-for-order\/.+/; return retryUntilSuccess(() => {
return new Promise((resolve, reject) => {
if (pattern.test(currentUrl2)) { const dropoffPointElement = document.getElementById('warehousebundle_shipment_preferences_dropoffPoint');
const portletBody = document.querySelector('.kt-portlet__body'); if (dropoffPointElement) {
if (portletBody) { dropoffPointElement.value = dropoffPoint;
const buttonContainer = document.createElement('div'); const dropoffPointEvent = document.createEvent('HTMLEvents');
buttonContainer.className = 'custom-button-container'; dropoffPointEvent.initEvent('change', true, false);
buttonContainer.style.display = 'flex'; dropoffPointElement.dispatchEvent(dropoffPointEvent);
buttonContainer.style.gap = '10px'; resolve();
buttonContainer.style.marginBottom = '15px'; } else {
portletBody.parentNode.insertBefore(buttonContainer, portletBody); reject('Nie znaleziono elementu dropoffPoint');
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);
} }
} });
});
}
function createButton(text, backgroundColor, method, dropoffPoint = null) { function setParcelWeight(weight) {
const button = document.createElement('button'); return retryUntilSuccess(() => {
button.textContent = text; return new Promise((resolve, reject) => {
button.style.background = backgroundColor; const weightElement = document.getElementById('warehousebundle_shipment_shipmentParcels_0_weight');
button.style.display = 'inline-flex'; if (weightElement) {
button.style.width = '200px'; weightElement.value = weight;
button.style.height = '40px'; const weightEvent = document.createEvent('HTMLEvents');
button.style.alignItems = 'center'; weightEvent.initEvent('change', true, false);
button.style.justifyContent = 'center'; weightElement.dispatchEvent(weightEvent);
button.style.color = '#FFF'; resolve();
button.style.border = 'none'; } else {
button.style.cursor = 'pointer'; reject('Nie znaleziono elementu shipmentParcels_0_weight');
button.addEventListener('click', () => handleShipment(method, dropoffPoint));
return button;
}
async function handleShipment(method, dropoffPoint = null) {
try {
await selectPackageType();
await setShipmentMethod(method);
if (dropoffPoint) {
await setDropoffPoint(dropoffPoint);
}
await setParcelWeight('1');
await submitShipment();
} catch (error) {
console.error('Wystąpił błąd: ', error);
} }
} });
});
}
function retryUntilSuccess(fn, interval = 500, retries = 10) { function submitShipment() {
return new Promise((resolve, reject) => { return retryUntilSuccess(() => {
const attempt = async () => { return new Promise((resolve, reject) => {
try { const submitButton = document.getElementById('warehousebundle_shipment_buttons_submit');
const result = await fn(); if (submitButton) {
resolve(result); submitButton.click();
} catch (err) { resolve();
if (retries === 0) { } else {
reject(err); reject('Nie znaleziono przycisku submit');
} else { }
setTimeout(() => { });
retries--; });
attempt(); }
}, interval);
}
}
};
attempt();
});
}
function selectPackageType() {
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);
resolve();
} else {
reject('Nie znaleziono elementu packageType');
}
});
});
}
function setShipmentMethod(method) {
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);
resolve();
} else {
reject('Nie znaleziono elementu shipment_method');
}
});
});
}
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');
}
});
});
}
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');
}
});
});
}
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');
}
});
});
}