Files
martbost 7e113f055d Smarter chatbot + support matching by meaning (Marty 2026-11-16): the hub's semantic match (free core2 embeddings)
Chatbot (chatbot.js + netkb.js route): a hand-off pattern still answers first; then the hub's POST /v1/kb/match answers with
this site's entry when it is sure, keeps or overrules the CANNED regex hit, and picks the AI prompt context, this site's own
entries first. 1.5 s timeout, then the hub is skipped for 30 s and the old pattern + BM25 path answers (NETKB_MATCH=0 = off).
Support desk: while a signed-in member types a new ticket, POST /api/my/support/suggest shows the closest help answers (KB
entries only, incl. ones written from past tickets, never another member's ticket; BM25 when the hub is down); Send is never
blocked. support.js?v=20261116sg.
Tests: qa/netkb-semantic.test.mjs (route/suggest decisions, fail soft, shared-file parity; run.sh kb) and
qa/support-suggest.mjs (run.sh member). netkb.js is the same file in all eight network sites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:46:31 -06:00

227 lines
21 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Help desk front end (2026-10-16): the public /support form, the private ticket link page (/support/t/<token>)
// and the member Help pane (/my#help). Server side: tickets.js + the /api/support, /api/my/support routes.
// Times show in US Central, like the rest of the site's support copy.
window.IAPSupport = (function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const CATS = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
const STATUS = { open: 'Open', waiting_on_member: 'Waiting on you', closed: 'Closed' };
const when = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
const linkify = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '<a href="$1" target="_blank" rel="noopener nofollow">$1</a>');
async function call(path, body, method) {
const o = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); }
const r = await (await fetch(path, o)).json();
if (r.error && !r.challenge) { const e = new Error(r.error); e.data = r; throw e; }
return r;
}
(function css() {
if (document.getElementById('supCss')) return;
const st = document.createElement('style'); st.id = 'supCss';
st.textContent = '.sup-form label{display:block;font-size:13px;color:var(--muted);margin:12px 0 4px}.sup-form input,.sup-form select,.sup-form textarea{width:100%;box-sizing:border-box}'
+ '.sup-row{display:flex;gap:10px;align-items:center;justify-content:space-between;padding:12px 4px;border-bottom:1px solid var(--line);cursor:pointer}.sup-row:last-child{border-bottom:0}.sup-row:hover{background:var(--mint-faint)}'
+ '.sup-row .sr-main{min-width:0;flex:1}.sup-row .sr-sub{font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sup-row .sr-meta{font-size:12px;color:var(--muted)}'
+ '.sup-st{font-size:11.5px;font-weight:700;border-radius:999px;padding:2px 10px;border:1px solid var(--line-strong);white-space:nowrap}.sup-st.open{color:var(--mint);border-color:var(--mint-line-2)}.sup-st.waiting_on_member{color:var(--gold-2);border-color:var(--gold-line)}.sup-st.closed{color:var(--muted)}'
+ '.sup-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--amber,#ffb238);margin-right:6px;vertical-align:1px}'
+ '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:var(--ground-soft)}.sup-msg.admin{border-color:var(--mint-line);background:var(--mint-faint)}.sup-msg.system{opacity:.8}'
+ '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}'
+ '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}'
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}'
+ '.sup-suggest{border:1px solid var(--mint-line);border-radius:12px;padding:10px 14px;margin:10px 0 0;background:var(--mint-faint)}.sup-sg{margin:4px 0}.sup-sg summary{cursor:pointer;font-weight:700;font-size:14px}.sup-sg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:14px;line-height:1.5;margin:6px 0 8px}';
document.head.appendChild(st);
})();
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
const AUTHOR = { member: 'You', admin: 'Marty, InstantAdPay support', system: 'InstantAdPay' };
function threadHtml(v) {
const t = v.ticket;
return '<div class="card-head" style="flex-wrap:wrap;gap:8px"><h3 style="margin:0">' + esc(t.subject) + '</h3><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>'
+ '<p class="small muted" style="margin:4px 0 6px">' + esc(t.ref) + ' · ' + esc(t.category) + ' · opened ' + esc(when(t.created)) + '</p>'
+ v.messages.map(m => '<div class="sup-msg ' + esc(m.author) + '"><div class="sm-head"><b>' + esc(AUTHOR[m.author] || m.author) + '</b><span>' + esc(when(m.created)) + '</span></div>'
+ '<div class="sm-body">' + linkify(m.body) + '</div>'
+ ((m.attachments || []).length ? '<div class="sup-att">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment"></a>').join('') + '</div>' : '') + '</div>').join('')
+ (t.status === 'closed' ? '<p class="small muted" style="margin:14px 0 0">This ticket is closed. Write below and it opens again.</p>' : '');
}
function replyBox(id, withAttach) {
return '<div class="sup-form"><label for="' + id + 'Body">Your reply</label><textarea id="' + id + 'Body" rows="4" maxlength="5000" placeholder="Add more detail or answer Marty here"></textarea>'
+ (withAttach ? attachRow(id) : '')
+ '<div class="sup-actions"><button class="btn small" type="button" id="' + id + 'Send">Send reply</button><span class="small muted" id="' + id + 'Msg"></span></div></div>';
}
// up to 2 screenshots per message, through the member upload path (signed-in only)
const attachRow = id => '<label for="' + id + 'File">Screenshots (optional, up to 2 images)</label><input type="file" id="' + id + 'File" accept="image/png,image/jpeg,image/webp,image/gif" multiple><div class="sup-att" id="' + id + 'Att"></div>';
function wireAttach(id) {
const list = []; const inp = document.getElementById(id + 'File'); if (!inp) return () => [];
const draw = () => { document.getElementById(id + 'Att').innerHTML = list.map(u => '<img src="' + esc(u) + '" alt="screenshot">').join(''); };
inp.addEventListener('change', async () => {
for (const f of [...inp.files]) {
if (list.length >= 2) { IAP.status('Two images per message at most.', 'bad'); break; }
try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); if (r.type !== 'image') throw new Error('Images only, please.'); list.push(r.url); draw(); }
catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); }
}
inp.value = '';
});
return () => list.slice(); // read at send time
}
// ── member Help pane ──
let helpState = { open: null };
async function badge() {
try { const r = await call('/api/my/support'); const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; } return r; } catch (e) { return null; }
}
async function help(paneQ) {
const host = document.getElementById('helpBody'); if (!host) return;
const want = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(paneQ || '') || [])[1];
if (want) return openMine(want);
helpState.open = null;
host.innerHTML = '<div class="card"><p class="muted small">Loading your tickets…</p></div>';
let r; try { r = await call('/api/my/support'); } catch (e) { host.innerHTML = '<div class="card"><p class="small">Could not load your tickets. ' + esc(e.message) + '</p></div>'; return; }
const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; }
host.innerHTML = '<div class="card"><div class="card-head"><h3>Help and support</h3><button class="btn small" type="button" id="helpNewBtn">New ticket</button></div>'
+ '<p class="muted small" style="margin:6px 0 0">Stuck on something? Send Marty a ticket. He reads every one and replies here, and you get an email when he does. The quickest answers to common questions are in Training and the chat bubble.</p></div>'
+ '<div class="card" id="helpNew" hidden></div>'
+ '<div class="card"><div class="card-head"><h3>Your tickets</h3><span class="sub">' + r.tickets.length + '</span></div>'
+ (r.tickets.length ? r.tickets.map(t => '<div class="sup-row" data-ref="' + esc(t.ref) + '"><div class="sr-main"><div class="sr-sub">' + (t.unread ? '<span class="sup-dot" title="New reply"></span>' : '') + esc(t.subject) + '</div>'
+ '<div class="sr-meta">' + esc(t.ref) + ' · ' + esc(t.category) + ' · updated ' + esc(when(t.updated)) + '</div></div><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>').join('')
: '<p class="muted small" id="helpEmpty">No tickets yet. When you send one, it shows up here with Marty\'s replies.</p>') + '</div>';
host.querySelectorAll('.sup-row').forEach(el => el.addEventListener('click', () => { history.replaceState(null, '', '#help?t=' + el.dataset.ref); openMine(el.dataset.ref); }));
document.getElementById('helpNewBtn').addEventListener('click', () => newForm());
if (/(?:^|&)new=1/.test(paneQ || '')) newForm();
}
function newForm() {
const box = document.getElementById('helpNew'); if (!box) return;
box.hidden = false;
box.innerHTML = '<h3 style="margin:0 0 4px">New ticket</h3><div class="sup-form">'
+ '<label for="hnCat">What is it about?</label><select id="hnCat">' + catOptions('') + '</select>'
+ '<label for="hnSubject">Subject</label><input id="hnSubject" maxlength="140" placeholder="A few words, like: my payout did not arrive">'
+ '<label for="hnBody">Message</label><textarea id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
+ '<div id="hnSuggest" class="sup-suggest" hidden aria-live="polite"></div>'
+ attachRow('hn')
+ '<div class="sup-actions"><button class="btn small" type="button" id="hnSend">Send to support</button><button class="btn small sec" type="button" id="hnCancel">Cancel</button><span class="small muted" id="hnMsg"></span></div></div>';
const atts = wireAttach('hn');
wireSuggest();
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
const send = document.getElementById('hnSend');
send.addEventListener('click', async () => {
if (send.disabled) return; send.disabled = true;
try {
const r = await call('/api/my/support', { category: document.getElementById('hnCat').value, subject: document.getElementById('hnSubject').value, body: document.getElementById('hnBody').value, attachments: atts() });
IAP.status('Sent. Your ticket is ' + r.ref + '. Marty will reply here and by email.', 'ok');
history.replaceState(null, '', '#help?t=' + r.ref); openMine(r.ref);
} catch (e) { document.getElementById('hnMsg').textContent = e.message; }
finally { send.disabled = false; }
});
document.getElementById('hnSubject').focus();
}
// help answers while typing (2026-11-16): debounced, from the KB only (the hub's semantic match); a suggestion never blocks Send
function wireSuggest() {
const box = document.getElementById('hnSuggest'), subj = document.getElementById('hnSubject'), body = document.getElementById('hnBody');
if (!box || !subj || !body) return;
let timer = null, seq = 0, last = '';
const run = async () => {
const text = (subj.value + ' ' + body.value).replace(/\s+/g, ' ').trim();
if (text.replace(/[^A-Za-z0-9]/g, '').length < 10) { box.hidden = true; box.innerHTML = ''; last = ''; return; }
if (text === last) return; last = text; const mine = ++seq;
let r; try { r = await call('/api/my/support/suggest', { subject: subj.value, body: body.value }); } catch (e) { return; }
if (mine !== seq || !document.body.contains(box)) return;
const items = (r && r.items) || [];
if (!items.length) { box.hidden = true; box.innerHTML = ''; return; }
box.innerHTML = '<p class="small" style="margin:0 0 6px"><b>These answers may help</b> <span class="muted">You can still send your ticket.</span></p>'
+ items.map(i => '<details class="sup-sg"><summary>' + esc(i.title) + (i.site ? ' <span class="muted small">(' + esc(i.site) + ')</span>' : '') + (i.fromTicket ? ' <span class="muted small">from a past ticket</span>' : '') + '</summary>'
+ '<div class="sm-body">' + linkify(i.answer) + (i.link && i.site ? '<br><a href="' + esc(i.link) + '" target="_blank" rel="noopener">Open ' + esc(i.site) + '</a>' : '') + '</div></details>').join('');
box.hidden = false;
};
const kick = () => { clearTimeout(timer); timer = setTimeout(run, 700); };
subj.addEventListener('input', kick); body.addEventListener('input', kick);
}
async function openMine(ref) {
const host = document.getElementById('helpBody'); if (!host) return;
helpState.open = ref;
host.innerHTML = '<div class="card"><p class="muted small">Loading…</p></div>';
let v; try { v = await call('/api/my/support/' + encodeURIComponent(ref)); } catch (e) { host.innerHTML = '<div class="card"><p class="small">' + esc(e.message) + '</p><p><a href="#help" id="helpBack">Back to your tickets</a></p></div>'; wireBack(); return; }
drawMine(v);
badge();
}
const wireBack = () => { const a = document.getElementById('helpBack'); if (a) a.addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#help'); help(''); }); };
function drawMine(v) {
const host = document.getElementById('helpBody');
host.innerHTML = '<p style="margin:0 0 10px"><a href="#help" id="helpBack">‹ All your tickets</a></p><div class="card">' + threadHtml(v) + '</div><div class="card">' + replyBox('hr', true) + '</div>';
wireBack();
const atts = wireAttach('hr');
const btn = document.getElementById('hrSend');
btn.addEventListener('click', async () => {
if (btn.disabled) return; btn.disabled = true;
try { const nv = await call('/api/my/support/' + encodeURIComponent(v.ticket.ref) + '/reply', { body: document.getElementById('hrBody').value, attachments: atts() }); drawMine(nv); IAP.status('Reply sent.', 'ok'); }
catch (e) { document.getElementById('hrMsg').textContent = e.message; }
finally { btn.disabled = false; }
});
}
// ── public /support page and the private ticket link ──
async function page() {
const host = document.getElementById('supMain'); if (!host) return;
const m = /^\/support\/t\/([A-Za-z0-9_.-]{20,80})$/.exec(location.pathname);
if (m) return tokenPage(host, m[1]);
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (e) {}
const signedIn = !!(me && me.signedIn && me.email);
host.innerHTML = (signedIn ? '<div class="card" style="border-color:var(--mint-line)"><p class="small" style="margin:0">You are signed in as <b>' + esc(me.username ? '@' + me.username : me.email) + '</b>. Your tickets and Marty\'s replies live in <a href="/my#help">Help in your dashboard</a>, which is the easiest place to follow up. This form works too and files the ticket under your account.</p></div>' : '')
+ '<div class="card"><form class="sup-form" id="supForm" novalidate autocomplete="on">'
+ '<input class="hp-field" type="text" name="website_url" id="supHp" tabindex="-1" aria-hidden="true" autocomplete="off">'
+ (signedIn ? '' : '<label for="supName">Your name</label><input id="supName" maxlength="80" autocomplete="name">'
+ '<label for="supEmail">Your email (replies go here)</label><input id="supEmail" type="email" maxlength="190" autocomplete="email" required>')
+ '<label for="supCat">What is it about?</label><select id="supCat">' + catOptions('') + '</select>'
+ '<label for="supSubject">Subject</label><input id="supSubject" maxlength="140" placeholder="A few words, like: my sign-in code does not arrive">'
+ '<label for="supBody">Message</label><textarea id="supBody" rows="7" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
+ '</form></div>';
// hand-off from a network site's chat assistant (2026-11-15): ?from=<site id>&subject=<question> prefills the subject and names
// the site in the message, so the ticket says where it came from. Plain text only (value / textContent), never HTML.
try {
const qs = new URLSearchParams(location.search); const SITES = { viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', vbb: 'Viral Banner Blitz', bannerline: 'Downline Banners', stackpol: 'Stack POL' };
const from = SITES[String(qs.get('from') || '').toLowerCase()]; const subj = String(qs.get('subject') || '').replace(/[\u0000-\u001f<>]/g, ' ').trim().slice(0, 140);
if (subj) document.getElementById('supSubject').value = subj;
if (from) document.getElementById('supBody').value = 'About ' + from + ': ';
} catch (e) {}
const f = document.getElementById('supForm');
f.addEventListener('submit', async e => {
e.preventDefault();
const btn = document.getElementById('supSend'); if (btn.disabled) return; btn.disabled = true;
const msg = document.getElementById('supMsg'); msg.textContent = 'Sending…';
const val = id => { const el = document.getElementById(id); return el ? el.value : ''; };
try {
const g = IAP.guard; await g.formSettled();
let pick = null, r = null;
for (let i = 0; i < 4; i++) {
r = await call('/api/support', { name: val('supName'), email: val('supEmail'), category: val('supCat'), subject: val('supSubject'), body: val('supBody'),
fts: g.FORM_TS, fage: Date.now() - g.FORM_TS, hp_field_x9: g.hpValue(document.getElementById('supHp')), pick });
if (r.challenge) { msg.textContent = ''; pick = await g.iconCheck(document.getElementById('supCheck'), r.challenge, r.error); continue; }
break;
}
if (!r || !r.ok) throw new Error('Could not verify. Refresh the page and try again.');
host.innerHTML = '<div class="card"><h3 style="margin:0 0 6px">Got it. Your ticket is ' + esc(r.ref) + '.</h3>'
+ '<p class="muted small">Marty reads every ticket and replies as soon as he can. ' + (r.member ? 'His reply shows up in Help in your dashboard and in your email.' : 'We just emailed you a private link to this ticket, so you can check on it or add more detail without signing in. If it does not arrive, look in spam or promotions.') + '</p>'
+ '<p class="sup-actions">' + (r.member ? '<a class="btn small" href="/my#help?t=' + esc(r.ref) + '">Open it in Help</a>' : '<a class="btn small" href="/support/t/' + esc(r.token) + '">View your ticket</a>') + '<a class="btn small sec" href="/">Back to InstantAdPay</a></p></div>';
window.scrollTo(0, 0);
} catch (err) { msg.textContent = err.message; }
finally { btn.disabled = false; }
});
}
async function tokenPage(host, tok) {
const h = document.querySelector('.sectionhead h2'); if (h) h.innerHTML = 'Your support <em>ticket</em>';
host.innerHTML = '<div class="card"><p class="muted small">Loading your ticket…</p></div>';
let v; try { v = await call('/api/support/t/' + encodeURIComponent(tok)); } catch (e) { host.innerHTML = '<div class="card"><p>' + esc(e.message) + '</p><p><a class="btn small" href="/support">Send a new ticket</a></p></div>'; return; }
const draw = v2 => {
host.innerHTML = '<div class="card">' + threadHtml(v2) + '</div><div class="card">' + replyBox('tk', false)
+ '<p class="small muted" style="margin:10px 0 0">Keep this link private: anyone with it can read and answer this ticket. Members can also follow up from <a href="/my#help">Help in the dashboard</a>, where screenshots can be attached.</p></div>';
const btn = document.getElementById('tkSend');
btn.addEventListener('click', async () => {
if (btn.disabled) return; btn.disabled = true;
try { const nv = await call('/api/support/t/' + encodeURIComponent(tok) + '/reply', { body: document.getElementById('tkBody').value }); draw(nv); IAP.status('Reply sent. Marty will see it.', 'ok'); }
catch (e) { document.getElementById('tkMsg').textContent = e.message; }
finally { btn.disabled = false; }
});
};
draw(v);
}
return { help, badge, page, CATS, STATUS, when, esc, linkify };
})();
if (document.getElementById('supMain')) IAPSupport.page();