// ==UserScript==
// @name Štenko Bot - Auto Košík v3.8
// @namespace http://tampermonkey.net/
// @version 3.8
// @description Osekané vyhľadávanie, blokovanie slangu a ASP.NET scraping
// @match *://*.mipa-shop.sk/*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @connect *
// ==/UserScript==
(function() {
'use strict';
if (window.top !== window.self) return;
// URL NA TVOJE API
const API_URL = 'https://api.stenko.sk/bot/api.php';
let toggleBtn = document.createElement('div');
toggleBtn.id = 'stenko-bot-toggle';
toggleBtn.innerHTML = '?? Bot';
document.body.appendChild(toggleBtn);
let panel = document.createElement('div');
panel.id = 'stenko-bot-panel';
panel.innerHTML = `
?? Záznam operácií
`;
document.body.appendChild(panel);
// CSS
GM_addStyle(`
:root {
--brand-primary: #35bdc8;
--brand-primary-hover: #29a0aa;
--brand-dark: #0a1128;
--brand-darker: #050814;
--text-light: #ffffff;
--success: #27ae60;
--danger: #e74c3c;
--warning: #f39c12;
}
#stenko-bot-toggle { position: fixed; top: 15px; right: 15px; background: var(--brand-primary); color: var(--brand-darker); padding: 12px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; z-index: 999999; box-shadow: 0 4px 6px rgba(0,0,0,0.3); font-family: sans-serif; font-size: 16px; transition: 0.2s; }
#stenko-bot-toggle:hover { background: var(--brand-primary-hover); transform: scale(1.05); }
#stenko-bot-panel { position: fixed; right: -100vw; top: 0; width: 100vw; height: 100vh; background: var(--brand-dark); color: var(--text-light); padding: 20px; box-sizing: border-box; z-index: 1000000; font-family: sans-serif; border-left: 3px solid var(--brand-primary); display: flex; flex-direction: row; gap: 20px; transition: right 0.3s ease-out; }
#stenko-bot-panel.open { right: 0; }
#bot-left-col { flex: 2; display: flex; flex-direction: column; height: 100%; overflow: hidden; }
#bot-right-col { flex: 1; display: flex; flex-direction: column; height: 100%; border-left: 1px solid #333; padding-left: 20px; }
#bot-header h2 { margin: 0; color: var(--brand-primary); font-size: 24px; }
#bot-close { background: var(--danger); color: white; border: none; padding: 8px 12px; cursor: pointer; border-radius: 3px; font-weight: bold; }
#bot-close:hover { background: #c0392b; }
#bot-input { width: 100%; height: 120px; flex-shrink: 0; background: var(--brand-darker); color: var(--text-light); border: 1px solid var(--brand-primary); padding: 10px; box-sizing: border-box; font-family: monospace; resize: vertical; margin-bottom: 10px; }
#bot-input:focus { outline: none; box-shadow: 0 0 5px var(--brand-primary); }
#bot-start { background: var(--brand-primary); color: var(--brand-darker); border: none; padding: 14px; cursor: pointer; font-weight: bold; border-radius: 4px; font-size: 15px; width: 100%; flex-shrink: 0; transition: 0.2s; }
#bot-start:hover { background: var(--brand-primary-hover); }
#pairing-box { display: none; background: #1a2533; padding: 15px; margin-top: 10px; border-radius: 4px; border: 1px solid var(--warning); flex-shrink: 0; }
#btn-save-pairing { background: var(--brand-primary); color: var(--brand-darker); border: none; padding: 12px; cursor: pointer; font-weight: bold; border-radius: 3px; transition: 0.2s; }
#btn-save-pairing:hover { background: var(--brand-primary-hover); }
#btn-skip-pairing { background: #7f8c8d; color: white; border: none; padding: 12px; cursor: pointer; font-weight: bold; border-radius: 3px;}
#btn-skip-pairing:hover { background: #95a5a6; }
#bot-work-frame { width: 100%; flex-grow: 1; background: #fff; border: 2px solid var(--brand-primary); margin-top: 15px; border-radius: 4px; }
#bot-results { flex-grow: 1; overflow-y: auto; font-size: 13px; padding-right: 5px; }
.bot-item { padding: 10px; margin-bottom: 8px; border-radius: 3px; background: var(--brand-darker); }
.st-green { border-left: 4px solid var(--success); }
.st-red { border-left: 4px solid var(--danger); }
.st-orange { border-left: 4px solid var(--warning); color: #ccc; }
`);
// --- LOGIKA UI ---
document.getElementById('stenko-bot-toggle').addEventListener('click', () => {
document.getElementById('stenko-bot-panel').classList.add('open');
document.body.style.overflow = 'hidden';
});
document.getElementById('bot-close').addEventListener('click', () => {
if (queue.length > 0 || currentTask !== null) {
if (!confirm('Pozor! Bot ešte neskončil. Naozaj chceš panel zavrieť a prerušiť proces?')) return;
}
document.getElementById('stenko-bot-panel').classList.remove('open');
document.body.style.overflow = '';
});
let queue = [];
let currentTask = null;
let iframeAction = 'idle';
let popupInterval = null;
let globalQtyType = 'ks';
const iframe = document.getElementById('bot-work-frame');
window.addEventListener('beforeunload', function (e) {
if (queue.length > 0 || currentTask !== null) {
e.preventDefault();
e.returnValue = '';
}
});
document.getElementById('bot-start').addEventListener('click', () => {
globalQtyType = document.querySelector('input[name="bot_qty_type"]:checked').value;
let lines = document.getElementById('bot-input').value.split('\n');
queue = [];
lines.forEach(line => {
line = line.trim();
if (!line) return;
let match = line.match(/^(.*?)(?:[\s\tx]+(\d+))?$/);
if (!match) return;
let ean = match[1].trim();
let qty = 1;
if (match[2]) {
let parsedQty = parseInt(match[2]);
if (!isNaN(parsedQty) && parsedQty > 0) {
qty = parsedQty;
}
}
queue.push({ ean: ean, qty: qty, type: globalQtyType });
});
document.getElementById('bot-results').innerHTML = '';
processNext();
});
function processNext() {
if (queue.length === 0) {
logResult("? Hotovo! Zoznam bol spracovaný.", "st-green");
currentTask = null;
return;
}
currentTask = queue.shift();
checkEanApi(currentTask.ean);
}
function checkEanApi(ean) {
GM_xmlhttpRequest({
method: "GET",
url: API_URL + '?action=check_ean&ean=' + encodeURIComponent(ean),
onload: function(response) {
let res;
try {
res = JSON.parse(response.responseText);
} catch(e) {
logResult(`? Vstup "${ean}" - Chyba servera (Neplatný JSON).`, "st-red");
processNext();
return;
}
// Kontrola chýb z Google AI
if (res.error) {
logResult(`? API Chyba: ${res.error}`, "st-red");
processNext();
return;
}
if (res.found) {
// AI alebo databáza tovar NAŠLA!
if (res.data.supplier_url) {
// Máme aj URL, ideme rovno nakupovať (bager priamo do košíka)
currentTask.dbData = res.data;
iframeAction = 'loading_product';
iframe.src = res.data.supplier_url;
} else {
// Tovar sme síce našli, ale nemá URL.
// Keďže sa našiel v tvojej DB, nevadí, že to bol slang. Ideme párovať!
let query = res.data.my_name.replace(/\s*\(.*?\)\s*/g, '').trim();
showPairingBox(ean, currentTask.qty, query);
}
} else {
// Tovar sa NENAŠIEL vôbec (AI ho nespoznala alebo nemáš taký EAN).
let isNumericEan = /^\d+$/.test(ean);
if (!isNumericEan) {
// Bol to slang, ktorý nepoznala ani AI. Potichu preskakujeme.
logResult(`? Vstup "${ean}" - AI nenašla zhodu (slang preskočený).`, "st-orange");
iframeAction = 'idle';
processNext();
} else {
// Bol to čistý EAN (napr. z čítačky), takže vyhodíme okno na párovanie.
showPairingBox(ean, currentTask.qty, ean);
}
}
}
});
}
iframe.addEventListener('load', function() {
if (iframeAction === 'loading_product') {
let doc = iframe.contentWindow.document;
let qtyInput = null;
let qtyLabel = currentTask.type === 'bal' ? 'BAL' : 'KS';
let tbPocet = doc.querySelector('input[id$="TB_pocet"]');
let tbBalenie = doc.querySelector('input[id$="TB_balenie"]');
if (currentTask.type === 'bal') {
if (tbBalenie) {
qtyInput = tbBalenie;
} else if (tbPocet) {
qtyInput = tbPocet;
qtyLabel = 'KS (Balenie nenašlo)';
}
} else {
qtyInput = tbPocet;
}
if (qtyInput) {
qtyInput.value = currentTask.qty;
currentTask.finalLabel = qtyLabel;
}
let buyBtn = doc.querySelector('.det-buy a.VB-bt');
if (buyBtn) {
iframeAction = 'waiting_for_popup';
buyBtn.click();
scanForPopup();
} else {
logResult(`? Vstup "${currentTask.ean}" - Tlačidlo Kúpiť nenájdené.`, "st-red");
iframeAction = 'idle';
processNext();
}
} else if (iframeAction === 'waiting_for_popup') {
scanForPopup();
} else if (iframeAction === 'popup_clicked') {
completeTask();
}
});
function scanForPopup() {
if (popupInterval) clearInterval(popupInterval);
let attempts = 0;
popupInterval = setInterval(() => {
attempts++;
try {
let doc = iframe.contentWindow.document;
let continueBtn = doc.querySelector('input[value="Pokračovať v nákupe"]') || doc.querySelector('[id*="Bt_oznamOK"]');
if (continueBtn) {
clearInterval(popupInterval);
iframeAction = 'popup_clicked';
continueBtn.click();
setTimeout(() => {
if (iframeAction === 'popup_clicked') {
completeTask();
}
}, 2000);
}
} catch(e) {}
if (attempts > 30) {
clearInterval(popupInterval);
if (iframeAction === 'waiting_for_popup') {
logResult(`? Vstup "${currentTask.ean}" - Popup sa neukázal. Ideme ďalej.`, "st-orange");
completeTask();
}
}
}, 500);
}
function completeTask() {
let label = currentTask.finalLabel || (currentTask.type === 'bal' ? 'BAL' : 'KS');
logResult(`? [${currentTask.qty} ${label}] ${currentTask.dbData.my_name} pridaný.`, "st-green");
iframeAction = 'idle';
processNext();
}
function showPairingBox(ean, qty, searchQuery) {
document.getElementById('pairing-ean').innerText = ean;
document.getElementById('pairing-qty').innerText = qty;
document.getElementById('pairing-type').innerText = globalQtyType.toUpperCase();
document.getElementById('pairing-name').innerText = searchQuery;
document.getElementById('pairing-box').style.display = 'block';
iframeAction = 'pairing';
iframe.src = '/Hladanie/-/strana-1/?filter=' + encodeURIComponent(searchQuery);
}
document.getElementById('btn-save-pairing').addEventListener('click', () => {
let doc = iframe.contentWindow.document;
let newUrl = iframe.contentWindow.location.href;
// ASP.NET SCRAPING - Hľadáme ID končiace na špecifický text a mažeme dlhé medzery
let nameElem = doc.querySelector('[id$="_popis1"]');
let scrapedName = nameElem ? nameElem.innerText.replace(/\s+/g, ' ').trim() : "Neznámy tovar";
let skuElem = doc.querySelector('[id$="__objcis"]');
let scrapedSku = skuElem ? skuElem.innerText.replace(/\s+/g, ' ').trim() : '';
document.getElementById('pairing-box').style.display = 'none';
GM_xmlhttpRequest({
method: "POST",
url: API_URL + '?action=save_mapping',
data: JSON.stringify({
ean: currentTask.ean,
supplier_url: newUrl,
my_name: scrapedName,
supplier_sku: scrapedSku
}),
onload: function() {
logResult(`?? Vstup "${currentTask.ean}" spárovaný. Pridávam...`, "st-green");
currentTask.dbData = { my_name: scrapedName, supplier_sku: scrapedSku };
iframeAction = 'loading_product';
iframe.src = newUrl;
}
});
});
document.getElementById('btn-skip-pairing').addEventListener('click', () => {
document.getElementById('pairing-box').style.display = 'none';
logResult(`? Vstup "${currentTask.ean}" preskočený používateľom.`, "st-orange");
iframeAction = 'idle';
processNext();
});
function logResult(text, cssClass) {
let div = document.createElement('div');
div.className = 'bot-item ' + cssClass;
div.innerHTML = text;
let resultsDiv = document.getElementById('bot-results');
resultsDiv.appendChild(div);
resultsDiv.scrollTop = resultsDiv.scrollHeight;
}
})();