/* ags 92 – B2B reklamačný modul (SK/CZ/HU)
* Umiestnenie: /buxus/docs/reklamacia.js.txt (BUXUS neprijíma .js, text/plain sa v prehliadačoch spúšťa), načítané v pätičke (Content after kontajnera 22)
* Čo robí:
* 1. Presmerovanie po prihlásení: URL ?goto=reklamacia&zdroj=...&objednavka=... sa uloží (30 min)
* a po prihlásení sa partner presmeruje na stránku Reklamácie (page_id 652491).
* 2. Na stránke Reklamácie (div#ags-reklamacia-app): značka → produkt (z XML feedu) → kód + EAN,
* vyhľadanie faktúry v PDF faktúrach partnera (24 mesiacov, na vyžiadanie 48) → otvorenie Tally formulára s predvyplnenými poľami.
*/
(function () {
'use strict';
if (window.__agsReklamaciaLoaded) { return; }
window.__agsReklamaciaLoaded = true;
var PAGE_ID_REKLAMACIE = 652491;
var PAGE_ID_FAKTURY = 257;
var PAGE_ID_UCET = 220;
var MONTHS_BACK = 24; /* predvolene */
var MONTHS_MAX = 48; /* na vyžiadanie tlačidlom „staršie faktúry“ */
var MAX_INVOICES = 1000;
var GOTO_KEY = 'ags_rekl_goto';
var GOTO_TTL = 30 * 60 * 1000;
var FEED_TTL = 24 * 60 * 60 * 1000;
var PDFJS = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js';
var PDFJS_WORKER = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
var CFG = {
sk: { formId: '9qV4YY', feed: 'https://data.ags92.com/xml/sk/all111/SK_VO_NEW_ALL.xml', brandTag: 'BRAND', codeTag: 'CODE', country: 'Slovensko', trh: 'SK' },
cz: { formId: 'gD2zPd', feed: 'https://data.ags92.com/data/all02/CZ_VO_NEW_ALL.xml', brandTag: 'ZNACKA', codeTag: 'CODE', country: 'Česká republika', trh: 'CZ' },
hu: { formId: 'GxWoGL', feed: 'https://data.ags92.com/xml/hu/hu_vo/HU_VO_NEW_ALL.xml', brandTag: 'BRAND', codeTag: 'ITEM_ID', country: 'Magyarország', trh: 'HU' }
};
var T = {
sk: {
step1: '1. Vyberte reklamovaný produkt', srcInv: 'Z vašich faktúr', srcCat: 'Z aktuálneho katalógu', srcManual: 'Zadať ručne',
boughtFilterPh: 'Hľadať v nakúpených produktoch (názov alebo kód)…', boughtLoading: 'Načítavam vaše faktúry…', boughtParsing: 'Načítavam položky z faktúr… {n}/{m} (zostáva cca {eta} min, zoznam sa priebežne dopĺňa; nabudúce už okamžite)', first400: 'zobrazených prvých 400 – spresnite hľadanie', more: 'Nenašli ste produkt? Prehľadať aj staršie faktúry (25 – 48 mesiacov)', moreLoading: 'Načítavam staršie faktúry…', moreDone: 'Prehľadané faktúry za posledných 48 mesiacov.', boughtEmpty: 'Za posledných 24 mesiacov nemáte faktúry – vyberte z katalógu alebo zadajte ručne.',
step2: '2. Vyberte produkt', filterPh: 'Hľadať podľa názvu, kódu alebo EAN…', productPh: '– vyberte produkt –', brandPh: '– všetky značky –',
count: '{n} produktov', code: 'Katalógový kód', ean: 'EAN kód', name: 'Presný názov produktu', brand: 'Značka',
notFound: 'Produkt som nenašiel – zadám ho ručne', backToList: 'Späť na výber zo zoznamu',
step3: '3. Faktúra', pickProductFirst: 'Najprv vyberte produkt.',
searching: 'Prehľadávam vaše faktúry za posledných {mo} mesiacov… {n}/{m}',
found: 'Produkt sme našli na týchto faktúrach – vyberte tú správnu:',
none: 'Produkt sme na vašich faktúrach za posledných {mo} mesiacov nenašli. Zadajte číslo faktúry ručne.',
invoicesError: 'Faktúry sa nepodarilo načítať – číslo faktúry zadajte ručne.',
manualInvoice: 'Iná faktúra – zadajte číslo:', invoiceDate: 'zo dňa',
feedLoading: 'Načítavam zoznam produktov…', feedError: 'Zoznam produktov sa nepodarilo načítať. Zadajte údaje ručne.',
cont: 'Pokračovať na reklamačný formulár', validation: 'Vyplňte značku, názov produktu a katalógový kód.',
openNew: 'Otvoriť formulár v novom okne', change: 'Zmeniť údaje'
},
cz: {
step1: '1. Vyberte reklamovaný produkt', srcInv: 'Z vašich faktur', srcCat: 'Z aktuálního katalogu', srcManual: 'Zadat ručně',
boughtFilterPh: 'Hledat v nakoupených produktech (název nebo kód)…', boughtLoading: 'Načítám vaše faktury…', boughtParsing: 'Načítám položky z faktur… {n}/{m} (zbývá cca {eta} min, seznam se průběžně doplňuje; příště už okamžitě)', first400: 'zobrazeno prvních 400 – upřesněte hledání', more: 'Nenašli jste produkt? Prohledat i starší faktury (25 – 48 měsíců)', moreLoading: 'Načítám starší faktury…', moreDone: 'Prohledány faktury za posledních 48 měsíců.', boughtEmpty: 'Za posledních 24 měsíců nemáte faktury – vyberte z katalogu nebo zadejte ručně.',
step2: '2. Vyberte produkt', filterPh: 'Hledat podle názvu, kódu nebo EAN…', productPh: '– vyberte produkt –', brandPh: '– všechny značky –',
count: '{n} produktů', code: 'Katalogové číslo', ean: 'EAN kód', name: 'Přesný název produktu', brand: 'Značka',
notFound: 'Produkt jsem nenašel – zadám ho ručně', backToList: 'Zpět na výběr ze seznamu',
step3: '3. Faktura', pickProductFirst: 'Nejprve vyberte produkt.',
searching: 'Prohledávám vaše faktury za posledních {mo} měsíců… {n}/{m}',
found: 'Produkt jsme našli na těchto fakturách – vyberte tu správnou:',
none: 'Produkt jsme na vašich fakturách za posledních {mo} měsíců nenašli. Zadejte číslo faktury ručně.',
invoicesError: 'Faktury se nepodařilo načíst – číslo faktury zadejte ručně.',
manualInvoice: 'Jiná faktura – zadejte číslo:', invoiceDate: 'ze dne',
feedLoading: 'Načítám seznam produktů…', feedError: 'Seznam produktů se nepodařilo načíst. Zadejte údaje ručně.',
cont: 'Pokračovat na reklamační formulář', validation: 'Vyplňte značku, název produktu a katalogové číslo.',
openNew: 'Otevřít formulář v novém okně', change: 'Změnit údaje'
},
hu: {
step1: '1. Válassza ki a reklamált terméket', srcInv: 'A számláiból', srcCat: 'Az aktuális katalógusból', srcManual: 'Kézi megadás',
boughtFilterPh: 'Keresés a vásárolt termékek között (név vagy cikkszám)…', boughtLoading: 'Számlák betöltése…', boughtParsing: 'Számlatételek betöltése… {n}/{m} (kb. {eta} perc van hátra, a lista folyamatosan bővül; legközelebb már azonnal)', first400: 'az első 400 látható – pontosítsa a keresést', more: 'Nem találja a terméket? Keresés a régebbi számlákban is (25–48 hónap)', moreLoading: 'Régebbi számlák betöltése…', moreDone: 'Az elmúlt 48 hónap számlái átnézve.', boughtEmpty: 'Az elmúlt 24 hónapban nincs számlája – válasszon a katalógusból vagy adja meg kézzel.',
step2: '2. Válassza ki a terméket', filterPh: 'Keresés név, cikkszám vagy EAN alapján…', productPh: '– válasszon terméket –', brandPh: '– összes márka –',
count: '{n} termék', code: 'Cikkszám', ean: 'EAN kód', name: 'A termék pontos neve', brand: 'Márka',
notFound: 'Nem találom a terméket – kézzel adom meg', backToList: 'Vissza a listából való választáshoz',
step3: '3. Számla', pickProductFirst: 'Először válassza ki a terméket.',
searching: 'Az elmúlt {mo} hónap számláinak átnézése… {n}/{m}',
found: 'A terméket a következő számlákon találtuk meg – válassza ki a megfelelőt:',
none: 'A terméket nem találtuk az elmúlt {mo} hónap számláin. Adja meg a számlaszámot kézzel.',
invoicesError: 'A számlákat nem sikerült betölteni – adja meg a számlaszámot kézzel.',
manualInvoice: 'Másik számla – adja meg a számot:', invoiceDate: 'kelt',
feedLoading: 'Terméklista betöltése…', feedError: 'A terméklistát nem sikerült betölteni. Adja meg az adatokat kézzel.',
cont: 'Tovább a reklamációs űrlaphoz', validation: 'Töltse ki a márkát, a termék nevét és a cikkszámot.',
openNew: 'Űrlap megnyitása új ablakban', change: 'Adatok módosítása'
}
};
/* ---------- helpers ---------- */
function market() {
var m = location.pathname.match(/^\/(sk|cz|hu)(\/|$)/i);
return m ? m[1].toLowerCase() : 'sk';
}
function txt(s) { return (s || '').replace(/\s+/g, ' ').trim(); }
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
function norm(s) { return String(s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase(); }
function normCode(s) { return txt(s).toUpperCase().replace(/_VO$/, ''); }
function reEsc(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
function fmt(s, o) { return s.replace(/\{(\w+)\}/g, function (_, k) { return o[k] != null ? o[k] : ''; }); }
function lsGet(k) { try { return JSON.parse(localStorage.getItem(k)); } catch (e) { return null; } }
function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} }
function lsDel(k) { try { localStorage.removeItem(k); } catch (e) {} }
function pageUrl(m, id) { return '/' + m + '/buxus/generate_page.php?page_id=' + id; }
function isLoggedIn() {
var h = document.querySelector('.header-basic-info h3');
if (h && txt(h.textContent)) { return true; }
var links = document.querySelectorAll('a[href]');
for (var i = 0; i < links.length; i++) { if (/logout|odhlas|kijelentkez/i.test(links[i].getAttribute('href') || '')) { return true; } }
return false;
}
function loadScript(src) {
return new Promise(function (res, rej) {
var s = document.createElement('script'); s.src = src; s.async = true;
s.onload = res; s.onerror = function () { rej(new Error('script ' + src)); };
document.head.appendChild(s);
});
}
/* ---------- 1. presmerovanie po prihlásení ---------- */
var m = market();
/* --- faktúry --- */
var MONTHS = { jan: 0, feb: 1, mar: 2, apr: 3, maj: 4, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, sze: 8, okt: 9, oct: 9, nov: 10, dec: 11 };
function parseDate(s) {
var a = s.match(/(\d{4})\s*[.\-\/]\s*(\d{1,2})\s*[.\-\/]\s*(\d{1,2})/);
if (a) { return new Date(+a[1], +a[2] - 1, +a[3]); }
var b = s.match(/(\d{1,2})\s*[.\-\/]\s*(\d{1,2})\s*[.\-\/]\s*(\d{4})/);
if (b) { return new Date(+b[3], +b[2] - 1, +b[1]); }
var c = s.match(/(\d{1,2})\s*[.\-\/ ]\s*([A-Za-z\u00C0-\u017F]{3,})\.?\s*[.\-\/ ]?\s*(\d{4})/); /* 25.Sep.2026 (B2B faktúry) */
if (c) { var mo = MONTHS[norm(c[2]).slice(0, 3)]; if (mo != null) { return new Date(+c[3], mo, +c[1]); } }
return null;
}
function fmtDate(d) { return d ? (d.getDate() + '. ' + (d.getMonth() + 1) + '. ' + d.getFullYear()) : ''; }
function loadPdfJs() {
if (window.pdfjsLib) { return Promise.resolve(); }
var d = window.define; var had = 'define' in window;
try { window.define = undefined; } catch (e) {}
return loadScript(PDFJS).then(function () {
if (had) { window.define = d; }
window.pdfjsLib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
}, function (e) { if (had) { window.define = d; } throw e; });
}
/* PDF → text + položky (riadok: kód | názov | množstvo | ks/db | ceny) */
var UNIT_RE = /^(ks|db\.?|pcs|szt\.?|kus|bal\.?)$/i;
var CODE_RE = /^[A-Z0-9][A-Z0-9\-_.\/]{2,}$/i;
function pdfParse(url) {
return window.pdfjsLib.getDocument({ url: url, withCredentials: true }).promise.then(function (pdf) {
var ps = [];
for (var i = 1; i <= pdf.numPages; i++) {
ps.push(pdf.getPage(i).then(function (p) { return p.getTextContent(); }).then(function (tc) {
var rows = [];
tc.items.forEach(function (it) {
if (!txt(it.str)) { return; }
var y = it.transform[5], x = it.transform[4], row = null;
for (var r = 0; r < rows.length; r++) { if (Math.abs(rows[r].y - y) <= 2) { row = rows[r]; break; } }
if (!row) { row = { y: y, cells: [] }; rows.push(row); }
row.cells.push({ x: x, s: it.str });
});
rows.sort(function (a, b) { return b.y - a.y; });
var items = [], last = null;
rows.forEach(function (row) {
var c = row.cells.sort(function (a, b) { return a.x - b.x; });
var ui = -1;
for (var k = 1; k < c.length; k++) { if (UNIT_RE.test(txt(c[k].s)) && /^\d+([.,]\d+)?$/.test(txt(c[k - 1].s))) { ui = k; break; } }
if (ui >= 2 && c[0].x < 120 && CODE_RE.test(txt(c[0].s))) {
last = { code: txt(c[0].s), name: txt(c.slice(1, ui - 1).map(function (q) { return q.s; }).join(' ')), qty: txt(c[ui - 1].s) };
items.push(last);
} else if (last && c.length === 1 && c[0].x > 100 && c[0].x < 400 && !/^\d{6,}/.test(txt(c[0].s)) && !/[:]/.test(c[0].s)) {
last.name = txt(last.name + ' ' + c[0].s); /* pokračovanie dlhého názvu */
} else { last = null; }
});
return { text: tc.items.map(function (it) { return it.str; }).join(' '), items: items };
}));
}
return Promise.all(ps).then(function (parts) {
var items = [];
parts.forEach(function (pt) { items = items.concat(pt.items); });
return { text: parts.map(function (pt) { return pt.text; }).join('\n').toUpperCase(), items: items };
});
});
}
/* --- cache položiek faktúr (faktúry sa nemenia → bez expirácie, orezané na 48 mesiacov / 1000 ks) --- */
/* kľúč cache podľa účtu (obchodníci sa prihlasujú za viacerých partnerov v jednom prehliadači) */
function acctKey() {
var h = document.querySelector('.header-basic-info h3'), box = document.querySelector('.header-basic-info');
var id = norm((h ? h.textContent : '') + '|' + (((box && box.textContent) || '').match(/[\w.+-]+@[\w-]+(\.[\w-]+)+/) || [''])[0]);
var hsh = 5381; for (var i = 0; i < id.length; i++) { hsh = ((hsh << 5) + hsh + id.charCodeAt(i)) >>> 0; }
return hsh.toString(36);
}
var ACCT = acctKey();
var INV_KEY = 'ags_rekl_inv_' + m + '_' + ACCT;
lsDel('ags_rekl_inv_' + m); lsDel('ags_rekl_invlist_' + m); /* staré kľúče bez účtu */
function dateKey(d) { return d ? (d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2)) : ''; }
function invCache() { var c = lsGet(INV_KEY); return (c && c.inv) ? c : { v: 1, inv: {} }; }
function invCacheGet(no) { var e = invCache().inv[no]; return e ? { date: e.d, items: e.it.map(function (a) { return { code: a[0], name: a[1], qty: a[2] }; }) } : null; }
function invCachePut(no, date, items) {
var c = invCache();
c.inv[no] = { d: dateKey(date), it: items.map(function (it) { return [it.code, it.name, it.qty]; }), t: Date.now() };
var cutoff = new Date(); cutoff.setMonth(cutoff.getMonth() - MONTHS_MAX); var ck = dateKey(cutoff);
var keys = Object.keys(c.inv).filter(function (k) { if (c.inv[k].d && c.inv[k].d < ck) { delete c.inv[k]; return false; } return true; });
if (keys.length > MAX_INVOICES) { keys.sort(function (a, b) { return (c.inv[a].t || 0) - (c.inv[b].t || 0); }).slice(0, keys.length - MAX_INVOICES).forEach(function (k) { delete c.inv[k]; }); }
lsSet(INV_KEY, c);
}
/* --- zoznam faktúr (24 alebo 48 mesiacov): stránka Faktúry má predvolený filter „od 1.1. aktuálneho roka",
preto sa posiela POST s date_from = dnes − N mesiacov; zoznam sa cachuje na 6 h --- */
var INV_LIST_KEY = 'ags_rekl_invlist_' + m + '_' + ACCT, INV_LIST_TTL = 6 * 60 * 60 * 1000;
function ddmmyyyy(d) { return ('0' + d.getDate()).slice(-2) + '.' + ('0' + (d.getMonth() + 1)).slice(-2) + '.' + d.getFullYear(); }
function parseInvoiceRows(doc, baseUrl, list, seen) {
var links = doc.querySelectorAll('a[href*="invoice_id="]'), added = 0, oldest = null;
for (var i = 0; i < links.length; i++) {
var tr = links[i].closest('tr'); if (!tr) { continue; }
var cells = tr.querySelectorAll('td, th');
var no = cells.length ? txt(cells[0].textContent) : '';
if (!no || seen[no]) { continue; }
var d = null;
for (var c = 1; c < cells.length && !d; c++) { d = parseDate(txt(cells[c].textContent)); }
seen[no] = 1; added++;
if (d) { oldest = (!oldest || d < oldest) ? d : oldest; }
list.push({ no: no, date: d, pdf: new URL(links[i].getAttribute('href'), baseUrl).toString(), text: null });
}
return { added: added, oldest: oldest };
}
function loadInvoiceList(force, months) {
months = months || MONTHS_BACK;
var LK = INV_LIST_KEY + '_' + months;
var c = lsGet(LK);
if (!force && c && c.ts && (Date.now() - c.ts) < INV_LIST_TTL && c.list) {
return Promise.resolve(c.list.map(function (x) { return { no: x[0], date: x[1] ? new Date(x[1] + 'T00:00:00') : null, pdf: x[2], text: null }; }));
}
var cutoff = new Date(); cutoff.setMonth(cutoff.getMonth() - months);
var list = [], seen = {};
return fetch(pageUrl(m, PAGE_ID_FAKTURY), { credentials: 'same-origin' }).then(function (r) { return r.text().then(function (h) { return { url: r.url.split('?')[0], html: h }; }); }).then(function (first) {
var doc0 = new DOMParser().parseFromString(first.html, 'text/html');
var inp = doc0.querySelector('input[name="date_from"]'), form = inp ? inp.closest('form') : null;
function body() {
var fd = new FormData();
if (form) { for (var k = 0; k < form.elements.length; k++) { var e = form.elements[k]; if (!e.name) { continue; } fd.append(e.name, e.name === 'date_from' ? ddmmyyyy(cutoff) : (e.name === 'date_to' ? '' : (e.value || ''))); } }
else { fd.append('date_from', ddmmyyyy(cutoff)); }
return fd;
}
function page(n) {
var req = form ? fetch(first.url + '?results_per_page=48&page=' + n, { method: 'POST', body: body(), credentials: 'same-origin' })
: fetch(first.url + '?page=' + n, { credentials: 'same-origin' });
return req.then(function (r) { return r.text(); }).then(function (html) {
var res = parseInvoiceRows(new DOMParser().parseFromString(html, 'text/html'), first.url, list, seen);
var stop = !res.added || list.length >= MAX_INVOICES || (res.oldest && res.oldest < cutoff) || n >= 30;
return stop ? list : page(n + 1);
});
}
return page(1);
}).then(function (l) {
l = l.filter(function (x) { return !x.date || x.date >= cutoff; });
lsSet(LK, { ts: Date.now(), list: l.map(function (x) { return [x.no, dateKey(x.date), x.pdf]; }) });
return l;
});
}
/* --- predbežné načítanie položiek do cache na pozadí (PDF generuje server postupne ~3,5 s/ks, paralelizmus nepomáha) --- */
var prefetchRunning = false;
function prefetchInvoices(max) {
if (prefetchRunning) { return; }
prefetchRunning = true;
loadInvoiceList().then(function (list) {
var queue = list.filter(function (x) { return !invCacheGet(x.no); }).slice(0, max);
if (!queue.length) { prefetchRunning = false; return; }
return loadPdfJs().then(function () {
var idx = 0;
function next() {
if (idx >= queue.length) { prefetchRunning = false; return; }
if (document.visibilityState === 'hidden') { setTimeout(next, 5000); return; }
var inv = queue[idx++];
if (invCacheGet(inv.no)) { return next(); }
return pdfParse(inv.pdf).then(function (res) { invCachePut(inv.no, inv.date, res.items); }, function () {}).then(next);
}
return next();
});
}).catch(function () { prefetchRunning = false; });
}
var qs = new URLSearchParams(location.search);
var hs = new URLSearchParams((location.hash || '').replace(/^#/, ''));
function qp(k) { return qs.get(k) || hs.get(k) || ''; } /* parametre aj v hashi – prežijú server redirect */
var app = document.getElementById('ags-reklamacia-app');
if (qp('goto') === 'reklamacia') {
lsSet(GOTO_KEY, { ts: Date.now(), zdroj: qp('zdroj'), objednavka: qp('objednavka') });
}
var pending = lsGet(GOTO_KEY);
if (pending && (Date.now() - pending.ts) > GOTO_TTL) { lsDel(GOTO_KEY); pending = null; }
if (pending && !app && isLoggedIn()) {
var target = pageUrl(m, PAGE_ID_REKLAMACIE) + '&zdroj=' + encodeURIComponent(pending.zdroj) + '&objednavka=' + encodeURIComponent(pending.objednavka);
lsSet(GOTO_KEY, { ts: pending.ts, zdroj: pending.zdroj, objednavka: pending.objednavka, redirected: 1 });
if (!pending.redirected) { location.replace(target); return; }
}
/* ---------- 1a. Faktúry / Objednávky: klzavých 12 mesiacov namiesto „od 1. 1. aktuálneho roka“
+ stránkovanie, ktoré nezahodí filter (BUXUS pri ?page=N filter zabúda) ---------- */
var DEFAULT_WINDOW = 12;
var autoSubmitting = (function fixListFilter() {
var inp = document.querySelector('input[name="date_from"]');
if (!inp || app) { return false; }
var form = inp.closest('form');
if (!form || String(form.getAttribute('method') || '').toLowerCase() !== 'post') { return false; }
var FLAG = 'ags_filter_' + location.pathname, flag = null;
try { flag = sessionStorage.getItem(FLAG); sessionStorage.removeItem(FLAG); } catch (e) {}
function send(action, why) {
var btn = form.querySelector('[type="submit"][name]');
if (btn && !form.querySelector('input[type="hidden"][name="' + btn.name + '"]')) {
var h = document.createElement('input'); h.type = 'hidden'; h.name = btn.name; h.value = btn.value; form.appendChild(h);
}
try { sessionStorage.setItem(FLAG, why); } catch (e) {}
form.setAttribute('action', action); form.submit();
}
form.addEventListener('submit', function () { try { sessionStorage.setItem(FLAG, 'user'); } catch (e) {} });
document.addEventListener('click', function (e) {
var a = e.target && e.target.closest ? e.target.closest('a[href*="page="], a[href*="results_per_page="]') : null;
if (!a || a.closest('.ags-inv-detail') || e.ctrlKey || e.metaKey) { return; }
e.preventDefault(); send(a.href, 'pager');
});
if (!flag && txt(inp.value) === '01.01.' + new Date().getFullYear()) {
var d = new Date(); d.setMonth(d.getMonth() - DEFAULT_WINDOW); inp.value = ddmmyyyy(d);
send(location.href.split('#')[0], 'auto');
return true;
}
return false;
})();
/* ---------- 1b. stránka Faktúry: rozbalenie položiek + „Reklamovať" + tiché načítanie do cache ---------- */
var invLinks = document.querySelectorAll('a[href*="invoice_id="]');
if (!app && invLinks.length && !autoSubmitting) { enhanceInvoiceList(invLinks); }
function enhanceInvoiceList(links) {
var L = { sk: { items: 'Položky', hide: 'Skryť', claim: 'Reklamovať', loading: 'Načítavam…', none: 'Položky sa nepodarilo načítať.', qty: 'ks' },
cz: { items: 'Položky', hide: 'Skrýt', claim: 'Reklamovat', loading: 'Načítám…', none: 'Položky se nepodařilo načíst.', qty: 'ks' },
hu: { items: 'Tételek', hide: 'Elrejt', claim: 'Reklamáció', loading: 'Betöltés…', none: 'A tételeket nem sikerült betölteni.', qty: 'db' } }[m];
var st = document.createElement('style');
st.textContent = '.ags-inv-btn{margin-left:8px;font-size:12px;white-space:nowrap}.ags-inv-detail td{background:#f7fbff;padding:6px 10px}' +
'.ags-inv-detail table{width:100%;font-size:13px;border-collapse:collapse}.ags-inv-detail th,.ags-inv-detail td{text-align:left;padding:3px 6px;border-bottom:1px solid #e3ecf3;background:none}' +
'.ags-inv-detail .ags-q{text-align:right;white-space:nowrap}.ags-inv-detail a.ags-claim{white-space:nowrap}';
document.head.appendChild(st);
var rows = [];
for (var i = 0; i < links.length; i++) {
var tr = links[i].closest('tr'); if (!tr || tr.getAttribute('data-ags')) { continue; }
tr.setAttribute('data-ags', '1');
var cells = tr.querySelectorAll('td, th');
var no = cells.length ? txt(cells[0].textContent) : ''; if (!no) { continue; }
var d = null; for (var c = 1; c < cells.length && !d; c++) { d = parseDate(txt(cells[c].textContent)); }
var pdf = new URL(links[i].getAttribute('href'), location.href).toString();
var btn = document.createElement('a'); btn.href = '#'; btn.className = 'ags-inv-btn'; btn.textContent = L.items;
cells[cells.length - 1].appendChild(btn);
rows.push({ tr: tr, no: no, date: d, pdf: pdf, btn: btn, detail: null, cols: cells.length });
}
function getItems(row) {
var cached = invCacheGet(row.no);
if (cached) { return Promise.resolve(cached.items); }
return loadPdfJs().then(function () { return pdfParse(row.pdf); }).then(function (res) { invCachePut(row.no, row.date, res.items); return res.items; });
}
function render(row, items) {
var h = '
';
items.forEach(function (it) {
var u = pageUrl(m, PAGE_ID_REKLAMACIE) + '&kod=' + encodeURIComponent(it.code) + '&faktura=' + encodeURIComponent(row.no) + '&zdroj=faktury';
h += '' + esc(it.code) + ' ' + esc(it.name) + ' ' + esc(it.qty) + ' ' + L.qty + ' ' + L.claim + ' ';
});
h += '
';
if (!items.length) { h = '' + L.none + ' '; }
row.detail.firstChild.innerHTML = h;
}
rows.forEach(function (row) {
row.btn.addEventListener('click', function (e) {
e.preventDefault();
if (row.detail) { var open = row.detail.style.display !== 'none'; row.detail.style.display = open ? 'none' : ''; row.btn.textContent = open ? L.items : L.hide; return; }
row.detail = document.createElement('tr'); row.detail.className = 'ags-inv-detail';
row.detail.innerHTML = '' + L.loading + ' ';
row.tr.parentNode.insertBefore(row.detail, row.tr.nextSibling);
row.btn.textContent = L.hide;
getItems(row).then(function (items) { render(row, items); }, function () { row.detail.firstChild.innerHTML = '' + L.none + ' '; });
});
});
/* tiché načítanie do cache na pozadí: najprv faktúry viditeľné na stránke, potom celých 24 mesiacov */
setTimeout(function () {
var queue = rows.filter(function (r) { return !invCacheGet(r.no); }); var idx = 0;
function worker() { if (idx >= queue.length) { prefetchInvoices(MAX_INVOICES); return; } var r = queue[idx++]; return getItems(r).catch(function () {}).then(worker); }
loadPdfJs().then(worker).catch(function () {});
}, 1500);
}
/* Na ostatných stránkach sa zámerne NEprednačítava: server drží PHP session zámok počas generovania PDF (~3,5 s),
partnerovi by sa náhodne spomaľovalo prehliadanie B2B. */
if (!app) { return; }
/* ---------- 2. widget na stránke Reklamácie ---------- */
var cfg = CFG[m], t = T[m];
var state = {
zdroj: qp('zdroj') || (pending && pending.zdroj) || 'menu',
objednavka: qp('objednavka') || (pending && pending.objednavka) || '',
account: { firma: '', email: '', ico: '', dic: '', ulica: '', psc: '', mesto: '', krajina: cfg.country },
items: [], brands: [], feedError: false,
product: null,
invoices: null, invoicesError: false, parsed: 0, invoiceChoice: '', invoiceManual: ''
};
lsDel(GOTO_KEY);
/* --- údaje z účtu --- */
function readHeader() {
var box = document.querySelector('.header-basic-info');
if (!box) { return; }
var h3 = box.querySelector('h3');
state.account.firma = h3 ? txt(h3.textContent) : '';
var em = (box.textContent || '').match(/[\w.+-]+@[\w-]+(\.[\w-]+)+/);
if (em) { state.account.email = em[0]; }
var html = box.innerHTML.replace(/ /gi, '\n').replace(/<\/(p|div|li|h\d|span)>/gi, '\n').replace(/<[^>]+>/g, '');
var tmp = document.createElement('textarea'); tmp.innerHTML = html;
var lines = tmp.value.split('\n').map(txt).filter(Boolean);
var addr = [];
for (var i = 0; i < lines.length; i++) {
var l = lines[i];
if (l === state.account.firma || /@|e-?mail|tel\.?|telef|phone/i.test(l)) { continue; }
addr.push(l);
}
for (var j = 0; j < addr.length; j++) {
var mm = addr[j].match(/^(\d{3}\s?\d{2}|\d{4,5})\s+(.+)$/) || addr[j].match(/^(.+?),?\s+(\d{3}\s?\d{2}|\d{4,5})$/);
if (mm && !state.account.psc) {
if (/^\d/.test(mm[1])) { state.account.psc = mm[1]; state.account.mesto = mm[2]; }
else { state.account.mesto = mm[1]; state.account.psc = mm[2]; }
} else if (!state.account.ulica && /\d/.test(addr[j])) {
state.account.ulica = addr[j];
}
}
if (!state.account.ulica && addr.length) { state.account.ulica = addr[0]; }
}
function grabIds(text) {
var ico = text.match(/(?:IČO|IČ|Cégjegyzékszám|Reg\. ?č\.)\s*:?\s*([0-9]{6,12})/);
var dic = text.match(/(?:DIČ|IČ DPH|Adószám|VAT)\s*:?\s*([A-Z]{0,2}[0-9][0-9\-]{6,14})/);
if (ico && !state.account.ico) { state.account.ico = ico[1]; }
if (dic && !state.account.dic) { state.account.dic = dic[1]; }
}
function readIds() {
grabIds(document.body.textContent || '');
if (state.account.ico && state.account.dic) { return Promise.resolve(); }
return fetch(pageUrl(m, PAGE_ID_UCET), { credentials: 'same-origin' }).then(function (r) { return r.text(); }).then(function (html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
grabIds(doc.body ? doc.body.textContent : '');
}).catch(function () {});
}
/* --- XML feed --- */
var IMG_BASE = 'https://product-images.ags92.com/';
/* položka = [značka, názov, kód, EAN, hlavný obrázok (bez IMG_BASE), galéria]
galéria: "a.jpg|b.jpg" = súbory v priečinku {kód}/ ; "!cesta1;cesta2" = plné cesty bez IMG_BASE */
function packImages(code, image, images) {
var main = image.indexOf(IMG_BASE) === 0 ? image.slice(IMG_BASE.length) : image;
var list = images.split(';').map(txt).filter(Boolean);
var folder = IMG_BASE + code + '/';
var inFolder = list.length && list.every(function (u) { return u.indexOf(folder) === 0 && u.indexOf('/', folder.length) < 0 && u.indexOf('|') < 0; });
var gal = inFolder ? list.map(function (u) { return u.slice(folder.length); }).join('|') :
(list.length ? '!' + list.map(function (u) { return u.indexOf(IMG_BASE) === 0 ? u.slice(IMG_BASE.length) : u; }).join(';') : '');
return [main, gal];
}
function imagesOf(it) {
var main = it[4] ? (/^https?:/.test(it[4]) ? it[4] : IMG_BASE + it[4]) : '';
var gal = it[5] || '', list = [];
if (gal.charAt(0) === '!') { list = gal.slice(1).split(';').map(function (p) { return /^https?:/.test(p) ? p : IMG_BASE + p; }); }
else if (gal) { list = gal.split('|').map(function (f) { return IMG_BASE + it[2] + '/' + f; }); }
return { main: main, list: list };
}
function loadFeed() {
var key = 'ags_rekl_feed2_' + m;
lsDel('ags_rekl_feed_' + m);
var c = lsGet(key);
if (c && c.ts && (Date.now() - c.ts) < FEED_TTL && c.items && c.items.length) { return Promise.resolve(c.items); }
return fetch(cfg.feed).then(function (r) { if (!r.ok) { throw new Error(r.status); } return r.text(); }).then(function (xml) {
var doc = new DOMParser().parseFromString(xml, 'text/xml');
var cards = doc.getElementsByTagName('STORECARD');
var items = [];
function ch(el, tag) { var n = el.getElementsByTagName(tag)[0]; return n ? txt(n.textContent) : ''; }
for (var i = 0; i < cards.length; i++) {
var el = cards[i];
var code = ch(el, cfg.codeTag); if (!code) { continue; }
var im = packImages(code, ch(el, 'IMAGE'), ch(el, 'IMAGES'));
items.push([ch(el, cfg.brandTag) || '–', ch(el, 'NAME'), code, ch(el, 'EAN'), im[0], im[1]]);
}
lsSet(key, { ts: Date.now(), items: items });
return items;
});
}
/* --- faktúry --- */
function parseInvoices(list) {
/* 1) všetko, čo už je v cache, naraz (okamžite); 2) zvyšok postupne z PDF, od najnovších */
var queue = [];
(list || state.invoices).forEach(function (inv) {
var cached = invCacheGet(inv.no);
if (cached) { inv.text = ''; inv.items = cached.items; state.parsed++; } else { queue.push(inv); }
});
rebuildBought(); renderBought(); applyPreselect(); renderInvoices();
if (!queue.length) { return Promise.resolve(); }
var idx = 0;
function worker() {
if (idx >= queue.length) { return Promise.resolve(); }
var inv = queue[idx++];
return pdfParse(inv.pdf).then(function (res) { inv.text = res.text; inv.items = res.items; invCachePut(inv.no, inv.date, res.items); }, function () { inv.text = ''; inv.items = []; }).then(function () {
state.parsed++; rebuildBought(); renderBought(); applyPreselect(); renderInvoices(); return worker();
});
}
return loadPdfJs().then(function () { return Promise.all([worker(), worker()]); });
}
/* nakúpené produkty = položky faktúr zlúčené podľa kódu, zoradené od najnovšej faktúry */
function rebuildBought() {
var map = {};
(state.invoices || []).forEach(function (inv) {
(inv.items || []).forEach(function (it) {
var k = normCode(it.code);
var b = map[k] || (map[k] = { code: it.code, name: it.name, invoices: [], last: null });
if (it.name.length > b.name.length) { b.name = it.name; }
if (!b.invoices.some(function (x) { return x.no === inv.no; })) { b.invoices.push({ no: inv.no, date: inv.date, qty: it.qty }); }
if (inv.date && (!b.last || inv.date > b.last)) { b.last = inv.date; }
});
});
state.bought = Object.keys(map).map(function (k) { return map[k]; }).sort(function (a, b) { return (b.last ? b.last.getTime() : 0) - (a.last ? a.last.getTime() : 0); });
state.bought.forEach(function (b) { b.invoices.sort(function (x, y) { return ((y.date && y.date.getTime()) || 0) - ((x.date && x.date.getTime()) || 0); }); });
}
function invoiceMatches(code, ean) {
var out = [];
if (!state.invoices) { return out; }
var nc = normCode(code);
var rc = code ? new RegExp('(^|[^A-Z0-9])' + reEsc(nc) + '(?![A-Z0-9])') : null;
var re = ean && /^\d{8,14}$/.test(ean) ? new RegExp('(^|[^0-9])' + ean + '(?![0-9])') : null;
for (var i = 0; i < state.invoices.length; i++) {
var inv = state.invoices[i];
var byItem = nc && (inv.items || []).some(function (it) { return normCode(it.code) === nc; });
var byText = inv.text && ((rc && rc.test(inv.text)) || (re && re.test(inv.text))); /* faktúry z cache nemajú text, len položky */
if (byItem || byText) { out.push(inv); }
}
return out;
}
function feedByCode(code) {
var nc = normCode(code);
for (var i = 0; i < state.items.length; i++) { if (normCode(state.items[i][2]) === nc) { return state.items[i]; } }
return null;
}
function guessBrand(name) {
var n = norm(name).replace(/^\d+x\s+/, '');
var best = '';
state.brands.forEach(function (b) { var nb = norm(b); if (n.indexOf(nb) === 0 && nb.length > best.length) { best = b; } });
if (best) { return best; }
var w = name.replace(/^\d+x\s+/, '').split(' ')[0];
return w.replace(/[^A-Za-z0-9&\u00C0-\u017F]/g, '');
}
/* --- UI --- */
var css = '#ags-reklamacia-app{max-width:820px;font-size:15px;line-height:1.5}' +
'#ags-reklamacia-app .ags-step{border:1px solid #e3e3e3;border-radius:6px;padding:14px 16px;margin:0 0 14px}' +
'#ags-reklamacia-app h3{margin:0 0 10px;font-size:17px}' +
'#ags-reklamacia-app label{display:block;font-weight:600;margin:8px 0 3px}' +
'#ags-reklamacia-app select,#ags-reklamacia-app input[type=text]{width:100%;box-sizing:border-box;padding:7px 9px;border:1px solid #bbb;border-radius:4px;font-size:15px;background:#fff}' +
'#ags-reklamacia-app select[size]{height:auto}' +
'#ags-reklamacia-app .ags-muted{color:#666;font-size:13px}' +
'#ags-reklamacia-app .ags-link{background:none;border:0;padding:0;color:#0070d7;text-decoration:underline;cursor:pointer;font-size:14px}' +
'#ags-reklamacia-app .ags-btn{display:inline-block;background:#007aff;color:#fff;border:0;border-radius:4px;padding:10px 18px;font-size:16px;cursor:pointer}' +
'#ags-reklamacia-app .ags-btn[disabled]{opacity:.5;cursor:default}' +
'#ags-reklamacia-app .ags-err{color:#b00020;margin:8px 0}' +
'#ags-reklamacia-app .ags-radio{display:block;font-weight:400;margin:4px 0}' +
'#ags-reklamacia-app .ags-radio input{margin-right:6px}' +
'#ags-reklamacia-app .ags-tabs{display:flex;gap:6px;flex-wrap:wrap;margin:0 0 10px}' +
'#ags-reklamacia-app .ags-tab{border:1px solid #bbb;background:#f7f7f7;border-radius:4px;padding:6px 12px;cursor:pointer;font-size:14px}' +
'#ags-reklamacia-app .ags-tab.on{background:#007aff;border-color:#007aff;color:#fff}' +
'#ags-reklamacia-app .ags-kv{display:flex;gap:16px;flex-wrap:wrap;margin-top:8px}' +
'#ags-reklamacia-app .ags-kv div{flex:1 1 200px}' +
'#ags-reklamacia-app .ags-kv input[readonly]{background:#f4f4f4}' +
'#ags-reklamacia-app .ags-gallery{display:flex;gap:10px;align-items:flex-start;flex-wrap:wrap;margin-top:12px}' +
'#ags-reklamacia-app .ags-gallery a{display:block;border:1px solid #e3e3e3;border-radius:4px;background:#fff;padding:3px;line-height:0}' +
'#ags-reklamacia-app .ags-gallery .ags-main img{width:160px;height:160px;object-fit:contain}' +
'#ags-reklamacia-app .ags-gallery .ags-thumbs{display:flex;gap:6px;flex-wrap:wrap;max-width:560px}' +
'#ags-reklamacia-app .ags-gallery .ags-thumbs img{width:56px;height:56px;object-fit:contain}' +
'#ags-reklamacia-form{margin-top:16px}';
var st = document.createElement('style'); st.textContent = css; document.head.appendChild(st);
app.innerHTML =
'' + esc(t.step1) + ' ' +
'
' + esc(t.srcInv) + ' ' + esc(t.srcCat) + ' ' + esc(t.srcManual) + '
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' + esc(t.more) + '
' +
'
' +
'
' + esc(t.feedLoading) + '
' +
'
' + esc(t.brand) + ' ' + esc(t.brandPh) + ' ' +
'
' + esc(t.name) + ' ' +
'
' +
'
' +
'
' +
'
' +
'' +
'
' +
'' + esc(t.cont) + '
' +
'
';
var $ = function (id) { return document.getElementById(id); };
var elBrand = $('ags-brand'), elFilter = $('ags-filter'), elProduct = $('ags-product'), elCount = $('ags-count');
var elBought = $('ags-bought'), elBoughtFilter = $('ags-bought-filter');
state.source = 'bought'; state.bought = []; state.pickedBought = null; state.months = MONTHS_BACK;
state.preKod = qp('kod'); state.preFak = qp('faktura'); state.preDone = false;
function setSource(src) {
state.source = src; state.product = null; state.pickedBought = null; state.invoiceChoice = '';
['bought', 'catalog', 'manual'].forEach(function (s) { $('ags-src-' + s).style.display = s === src ? '' : 'none'; });
var tabs = app.querySelectorAll('.ags-tab');
for (var i = 0; i < tabs.length; i++) { tabs[i].className = 'ags-tab' + (tabs[i].getAttribute('data-src') === src ? ' on' : ''); }
showPicked(null); renderInvoices();
}
function showPicked(p, it) {
var box = $('ags-picked');
if (!p) { box.style.display = 'none'; renderGallery(null, null); return; }
box.style.display = '';
$('ags-brand-ro').value = p.brand; $('ags-code-ro').value = p.code; $('ags-ean-ro').value = p.ean;
renderGallery(it, p.code);
}
function currentProduct() {
if (state.source === 'manual') {
return { brand: txt($('ags-m-brand').value), name: txt($('ags-m-name').value), code: normCode($('ags-m-code').value), ean: txt($('ags-m-ean').value) };
}
return state.product;
}
function countText(n) {
if (m === 'hu') { return n + ' termék'; }
var w = m === 'cz' ? ['produkt', 'produkty', 'produktů'] : ['produkt', 'produkty', 'produktov'];
return n + ' ' + (n === 1 ? w[0] : (n >= 2 && n <= 4 ? w[1] : w[2]));
}
function renderGallery(it, code) {
var g = $('ags-gallery');
var im = it ? imagesOf(it) : { main: code ? IMG_BASE + 'images/' + code + '.jpg' : '', list: [] }; /* aj ukončený produkt máva hlavnú fotku */
var all = im.list.filter(function (u) { return u !== im.main; });
var thumbs = all.slice(0, 12);
var h = '';
if (im.main) { h += ' '; }
if (thumbs.length) {
h += '' + thumbs.map(function (u) {
return '
';
}).join('') + (all.length > 12 ? '
+' + (all.length - 12) + ' ' : '') + '
';
}
g.innerHTML = h;
}
/* --- tolerantné vyhľadávanie: poradie slov, diakritika, veľkosť písmen, spojené/rozdelené slová a preklepy nevadia --- */
function toks(str) { return norm(str).replace(/[^a-z0-9]+/g, ' ').trim().split(' ').filter(Boolean); }
function wordsOf(str) { /* slová + spojené susedné dvojice (PETITE&MARS → petite, mars, petitemars) */
var w = toks(str), out = w.slice();
for (var i = 0; i + 1 < w.length; i++) { out.push(w[i] + w[i + 1]); }
return out;
}
function lev(a, b, max) { /* Damerau-Levenshtein (prehodené písmená = 1 chyba), s predčasným ukončením */
if (Math.abs(a.length - b.length) > max) { return max + 1; }
var pp = null, prev = [], cur, i, j;
for (j = 0; j <= b.length; j++) { prev[j] = j; }
for (i = 1; i <= a.length; i++) {
cur = [i]; var rowMin = i;
for (j = 1; j <= b.length; j++) {
var cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
if (pp && i > 1 && j > 1 && a.charCodeAt(i - 1) === b.charCodeAt(j - 2) && a.charCodeAt(i - 2) === b.charCodeAt(j - 1)) { cur[j] = Math.min(cur[j], pp[j - 2] + 1); }
if (cur[j] < rowMin) { rowMin = cur[j]; }
}
if (rowMin > max) { return max + 1; }
pp = prev; prev = cur;
}
return prev[b.length];
}
function tokScore(q, words) {
var best = 0, tol = q.length >= 8 ? 2 : (q.length >= 4 ? 1 : 0);
for (var i = 0; i < words.length; i++) {
var w = words[i];
if (w === q) { return 4; }
if (w.indexOf(q) === 0) { best = Math.max(best, 3); continue; }
if (q.length >= 3 && w.indexOf(q) > 0) { best = Math.max(best, 2); continue; }
if (tol && best < 1.5 && (w.charCodeAt(0) === q.charCodeAt(0) || w.charCodeAt(1) === q.charCodeAt(1))) { /* preklep býva zriedka v prvých 2 písmenách */
if (lev(q, w, tol) <= tol || (w.length > q.length && lev(q, w.slice(0, q.length), tol) <= tol)) { best = 1.5; }
}
}
return best;
}
function fuzzyScore(qt, words) { /* 0 = nevyhovuje; každé slovo dopytu musí niekde sedieť */
var sum = 0;
for (var i = 0; i < qt.length; i++) { var sc = tokScore(qt[i], words); if (!sc) { return 0; } sum += sc; }
return sum;
}
function searchList(list, query, wordsFn, keep) {
var qt = toks(query), res = [];
for (var i = 0; i < list.length; i++) {
if (keep && !keep(list[i])) { continue; }
if (!qt.length) { res.push({ i: i, s: 0 }); continue; }
var sc = fuzzyScore(qt, wordsFn(list[i], i));
if (sc) { res.push({ i: i, s: sc }); }
}
if (qt.length) { res.sort(function (a, b) { return (b.s - a.s) || (a.i - b.i); }); }
return res;
}
/* --- zdroj A: nakúpené produkty z faktúr --- */
function renderBought() {
var stEl = $('ags-bought-status');
var total = state.invoices ? state.invoices.length : 0;
if (state.invoicesError) { stEl.textContent = t.invoicesError; }
else if (!state.invoices) { stEl.textContent = t.boughtLoading; }
else if (!total) { stEl.textContent = t.boughtEmpty; }
else if (state.parsed < total) { var left = total - state.parsed; stEl.textContent = fmt(t.boughtParsing, { n: state.parsed, m: total, eta: Math.max(1, Math.ceil(left * 3.5 / 60)) }); }
else { stEl.textContent = ''; }
$('ags-more').style.display = (state.invoices && !state.invoicesError && state.months < MONTHS_MAX) ? '' : 'none';
var sel = state.pickedBought ? normCode(state.pickedBought.code) : '';
var hits = searchList(state.bought, elBoughtFilter.value, function (b) { return b.w || (b.w = wordsOf(b.name + ' ' + b.code)); });
var opts = [], n = hits.length;
for (var h = 0; h < hits.length && h < 400; h++) {
var i = hits[h].i, b = state.bought[i], inv = b.invoices[0];
opts.push('' + esc(b.name) + ' (' + esc(b.code) + ')' + (inv ? ' – ' + esc(inv.no) + (inv.date ? ' ' + fmtDate(inv.date) : '') : '') + ' ');
}
elBought.innerHTML = opts.join('');
$('ags-bought-count').textContent = state.bought.length ? countText(n) + (n > 400 ? ' (' + t.first400 + ')' : '') : '';
}
function onBoughtPick() {
var b = state.bought[+elBought.value];
if (!b) { return; }
state.pickedBought = b;
var it = feedByCode(b.code);
state.product = { brand: it ? it[0] : guessBrand(b.name), name: it ? it[1] : b.name, code: b.code, ean: it ? it[3] : '' };
if (it && it[1].length < b.name.length) { state.product.name = b.name; }
elBoughtFilter.value = b.name;
state.invoiceChoice = b.invoices[0] ? b.invoices[0].no : '';
showPicked(state.product, it);
renderInvoices();
}
/* --- zdroj B: katalóg --- */
function renderProducts() {
var brand = elBrand.value;
state.itemWords = state.itemWords || [];
var hits = searchList(state.items, elFilter.value, function (it, i) { return state.itemWords[i] || (state.itemWords[i] = wordsOf(it[0] + ' ' + it[1] + ' ' + it[2] + ' ' + it[3])); },
brand ? function (it) { return it[0] === brand; } : null);
var opts = [], n = hits.length;
for (var h = 0; h < hits.length && h < 400; h++) {
var it = state.items[hits[h].i];
opts.push('' + esc(it[1]) + ' (' + esc(it[2]) + ') ');
}
elProduct.innerHTML = opts.join('');
elCount.textContent = countText(n) + (n > 400 ? ' (' + t.first400 + ')' : '');
elProduct.disabled = !opts.length;
state.product = null; state.invoiceChoice = '';
showPicked(null); renderInvoices();
}
function onProductPick() {
var it = state.items[+elProduct.value];
if (!it) { state.product = null; showPicked(null); return; }
state.product = { brand: it[0], name: it[1], code: it[2], ean: it[3] };
elFilter.value = it[1]; /* celý názov do poľa (bez spustenia filtra) */
state.invoiceChoice = '';
showPicked(state.product, it);
renderInvoices();
}
/* predvýber z odkazu „Reklamovať" pri položke faktúry (?kod=…&faktura=…) */
function applyPreselect() {
if (!state.preKod || state.preDone) { return; }
for (var i = 0; i < state.bought.length; i++) {
if (normCode(state.bought[i].code) === normCode(state.preKod)) {
state.preDone = true; renderBought(); elBought.value = String(i); onBoughtPick();
if (state.preFak) { state.invoiceChoice = state.preFak; renderInvoices(); }
return;
}
}
}
/* --- faktúry k vybranému produktu --- */
function renderInvoices() {
var box = $('ags-inv'); var p = currentProduct();
if (!p || (!p.code && !p.ean)) { box.innerHTML = '' + esc(t.pickProductFirst) + '
'; return; }
if (state.invoicesError) { box.innerHTML = '' + esc(t.invoicesError) + '
'; return; }
var total = state.invoices ? state.invoices.length : 0;
var done = state.invoices && state.parsed >= total;
var hits = invoiceMatches(p.code, p.ean);
var h = '';
if (!done) { h += '' + esc(fmt(t.searching, { n: state.parsed, m: total, mo: state.months })) + '
'; }
if (hits.length) {
h += '' + esc(t.found) + '
';
for (var i = 0; i < hits.length; i++) {
var chk = state.invoiceChoice === hits[i].no ? ' checked' : '';
h += ' ' + esc(hits[i].no) + (hits[i].date ? ' (' + esc(t.invoiceDate) + ' ' + fmtDate(hits[i].date) + ') ' : '') + ' ';
}
} else if (state.moreLoading) {
h += '' + esc(t.moreLoading) + '
';
} else if (done) {
h += '' + esc(fmt(t.none, { mo: state.months })) + '
';
if (state.months < MONTHS_MAX) { h += '' + esc(t.more) + '
'; }
}
box.innerHTML = h;
var mb = $('ags-more2'); if (mb) { mb.addEventListener('click', loadMore); }
var rs = box.querySelectorAll('input[name=ags-inv-r]');
for (var r = 0; r < rs.length; r++) { rs[r].addEventListener('change', function (e) { state.invoiceChoice = e.target.value; }); }
if (hits.length && !state.invoiceChoice) { state.invoiceChoice = hits[0].no; rs[0].checked = true; }
}
function buildUrl() {
var p = currentProduct(); var a = state.account;
var inv = txt($('ags-inv-manual').value) || state.invoiceChoice || '';
var params = {
alignLeft: 1, hideTitle: 1, transparentBackground: 1, dynamicHeight: 1,
firma: a.firma, email: a.email, ico: a.ico, dic: a.dic, trh: cfg.trh, zdroj: state.zdroj, objednavka: state.objednavka,
ulica: a.ulica, psc: a.psc, mesto: a.mesto, krajina: a.krajina,
znacka: p.brand, produkt: p.name, kod: p.code, ean: p.ean, faktura: inv
};
var q = Object.keys(params).map(function (k) { return k + '=' + encodeURIComponent(params[k] == null ? '' : params[k]); }).join('&');
return { embed: 'https://tally.so/embed/' + cfg.formId + '?' + q, full: 'https://tally.so/r/' + cfg.formId + '?' + q };
}
function go() {
var p = currentProduct(); var err = $('ags-err');
if (!p || !p.brand || !p.name || !p.code) { err.textContent = t.validation; err.style.display = ''; return; }
err.style.display = 'none';
var u = buildUrl(); var host = $('ags-reklamacia-form');
host.innerHTML = '' +
'' + esc(t.openNew) + '
';
$('ags-go').style.display = 'none';
if (window.Tally && window.Tally.loadEmbeds) { window.Tally.loadEmbeds(); }
else { loadScript('https://tally.so/widgets/embed.js').then(function () { if (window.Tally && window.Tally.loadEmbeds) { window.Tally.loadEmbeds(); } }, function () { host.querySelector('iframe').src = u.embed; }); }
host.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
var tabs = app.querySelectorAll('.ags-tab');
for (var ti = 0; ti < tabs.length; ti++) { tabs[ti].addEventListener('click', function (e) { setSource(e.target.getAttribute('data-src')); }); }
var debB; elBoughtFilter.addEventListener('input', function () { state.pickedBought = null; state.product = null; state.invoiceChoice = ''; showPicked(null); clearTimeout(debB); debB = setTimeout(function () { renderBought(); renderInvoices(); }, 120); });
elBoughtFilter.addEventListener('focus', function () { if (state.pickedBought) { this.select(); } });
elBought.addEventListener('change', onBoughtPick);
elBrand.addEventListener('change', function () { elFilter.value = ''; renderProducts(); });
var debP; elFilter.addEventListener('input', function () { clearTimeout(debP); debP = setTimeout(renderProducts, 150); });
elFilter.addEventListener('focus', function () { if (state.product) { this.select(); } }); /* po výbere produktu: písanie nahradí názov */
elProduct.addEventListener('change', onProductPick);
var deb;
['ags-m-code', 'ags-m-ean'].forEach(function (id) { $(id).addEventListener('input', function () { clearTimeout(deb); deb = setTimeout(renderInvoices, 400); }); });
$('ags-go').addEventListener('click', go);
/* --- štart --- */
readHeader();
readIds();
renderBought();
loadFeed().then(function (items) {
state.items = items;
var bs = {}; items.forEach(function (it) { bs[it[0]] = 1; });
state.brands = Object.keys(bs).sort(function (a, b) { return a.localeCompare(b); });
elBrand.innerHTML = '' + esc(t.brandPh) + ' ' + state.brands.map(function (b) { return '' + esc(b) + ' '; }).join('');
elBrand.disabled = false; elFilter.disabled = false;
$('ags-feed-status').textContent = '';
renderProducts();
}).catch(function () {
state.feedError = true;
$('ags-feed-status').textContent = t.feedError;
});
renderInvoices();
loadInvoiceList().then(function (list) {
state.invoices = list; renderBought(); renderInvoices();
if (list.length) { return parseInvoices(); }
}).catch(function () { state.invoicesError = true; renderBought(); renderInvoices(); });
/* staršie faktúry (25 – 48 mesiacov) len na vyžiadanie – z kroku 1 aj z kroku 3 */
function loadMore() {
if (state.months >= MONTHS_MAX || !state.invoices || state.moreLoading) { return; }
state.months = MONTHS_MAX; state.moreLoading = true; $('ags-more').style.display = 'none'; $('ags-more-status').textContent = t.moreLoading; renderInvoices();
loadInvoiceList(false, MONTHS_MAX).then(function (list) {
var have = {}; state.invoices.forEach(function (x) { have[x.no] = 1; });
var add = list.filter(function (x) { return !have[x.no]; });
state.invoices = state.invoices.concat(add); state.moreLoading = false;
$('ags-more-status').textContent = '';
renderBought(); renderInvoices();
return parseInvoices(add);
}).then(function () { $('ags-more-status').textContent = t.moreDone; }, function () { state.moreLoading = false; $('ags-more-status').textContent = t.invoicesError; renderInvoices(); });
}
$('ags-more').addEventListener('click', loadMore);
})();