Files
instantadpay/public/assets/support.js
T
martbost 9be58bd5ef Help desk: support tickets for members (Help pane), the public /support page with private ticket links, chatbot hand-off, and an admin Support pane
- tickets.js: one shared desk (platform iap now, linkspin later), dual-mode store (MySQL tables tickets + ticket_messages, else support.json); refs IAP-<1000+id> / LS-; private no-login link /support/t/<ref>.<HMAC> signed with DATA_DIR/support.key (or SUPPORT_SECRET); ingestEmail() ready for the support@ intake step (threads by Message-ID, then [ref] in the subject from the same sender)
- Member Help pane (/my#help): list with status + unread badge, new ticket (category, subject, message, up to 2 screenshots via /api/my/upload), thread + reply (a reply reopens a closed ticket)
- Public /support: name, email, category, subject, message behind the sign-up walls (honeypot, form age, per-IP limits with the icon check, global cap) plus a per-email cap; confirmation email with the ref and the private link
- Chatbot: CANNED + systemPrompt know the help desk; answers that cannot help (or "talk to a human") offer "Send this to support", which files the last turns as a ticket (members: Help pane; signed out: email + the same guard)
- Admin Support pane: open / waiting / closed / all, platform, category, search; open-count badge; ticket view with requester account info, internal notes, status/priority/category, saved replies (site setting supportTemplates); deep link /admin#support?t=<ref>
- Notifications: new ticket / member reply -> Telegram to Marty's private chat only (supportTelegramChat, default 1289244227, site bot then Hermes fallback, never a group or the Discord relay) + email to ADMIN_EMAIL, max one per ticket per 10 min; Marty's reply -> email "[IAP-1042] subject" + a 'notice' inbox message for members, bursts batched
- support* settings are kept out of /api/config; Support link in the site footer, home footer, member page foot, terms and privacy; "Contact support" errors point at /support
- QA walk: member Help ticket flow, admin Support pane + deep link, internal-note leak check, public /support + private link + tampered token + form-age refusal
- Cache tags: common.js 20261016a, chat.js 20261016a, my.js 20261016r, admin.js 20261016sp, support.js 20261016a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:51:30 -05:00

195 lines
18 KiB
JavaScript
Raw 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:rgba(67,232,195,.04)}'
+ '.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:rgba(67,232,195,.5)}.sup-st.waiting_on_member{color:#f2c94c;border-color:rgba(242,201,76,.5)}.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:rgba(4,8,7,.35)}.sup-msg.admin{border-color:rgba(67,232,195,.45);background:rgba(67,232,195,.06)}.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}';
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>'
+ 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');
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();
}
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:rgba(67,232,195,.45)"><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>';
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();