// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the // entries the chat assistant answers from, and try a question against them. Same file as InstantAdPay's // admin-kb.js; LinkSpin tickets are answered on the InstantAdPay desk, so fromTicket is unused here. (function () { const $ = IAP.$; const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); async function api(path, body, method) { const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} }; if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); } const r = await (await fetch(path, opts)).json(); if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error); return r; } const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : ''; const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' }; let entries = [], filter = { q: '', src: '' }, wired = false; function wire() { if (wired) return; wired = true; let t = null; $('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); }); $('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); }); $('kbNew').addEventListener('click', () => compose({})); $('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); }); const go = async () => { const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus(); const r = await api('/api/admin/kb/test', { question: q }); $('kbTryOut').innerHTML = (r.fast ? '

Instant answer: ' + esc(r.fast.title) + ' ' + esc(r.fast.id) + ' (no AI call)

' : '

No instant answer, so this goes to the AI with:

') + (r.ranked.length ? '
    ' + r.ranked.map(h => '' + esc(h.title) + ' ' + h.score + '' + (h.used ? ' used' : '') + '').join('') + '
' : '

No entry matches, so the assistant is told to say it is not sure and point to support.

'); }; $('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad'))); $('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); }); $('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } }); } async function load() { wire(); $('kbEdit').hidden = true; $('kbList').hidden = false; const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : '')); entries = r.entries || []; $('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : ''); draw(); } function draw() { const rows = entries.filter(e => !filter.src || e.source === filter.src); $('kbTable').innerHTML = 'EntryAsked asSourceUpdated' + (rows.length ? rows.map(e => '' + esc(e.title) + '' + (e.score != null ? ' ' + e.score + '' : '') + '
' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '
' + ((e.tags || []).length ? '
' + e.tags.map(t => '' + esc(t) + '').join('') + '
' : '') + '' + '' + (e.questions || []).slice(0, 3).map(esc).join('
') + ((e.questions || []).length > 3 ? '
+' + (e.questions.length - 3) + ' more' : '') + '' + '' + esc(SRC[e.source] || e.source) + (e.pattern ? '
instant
' : '') + (e.ticketRef ? '
' + esc(e.ticketRef) + '
' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '
edited
' : '') + '' + '' + esc(ctDay(e.updated)) + '').join('') : 'No entries here.'); } async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); } // e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef }) function compose(e) { wire(); e = e || {}; const isNew = !e.id; $('kbList').hidden = true; $('kbEdit').hidden = false; $('kbEdit').innerHTML = '

' + (isNew ? 'New entry' : 'Edit entry') + '

' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '
' + (e.source === 'ticket' && isNew ? '

Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.

' : '') + (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '

This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.

' : '') + '
' + '' + '' + '' + '' + '' + 'Instant answer (advanced)' + '

A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.

' + '
' + '
' + '

' + (isNew ? '' : '') + '

'; $('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); }); $('kbSave').addEventListener('click', async () => { const b = $('kbSave'); if (b.disabled) return; b.disabled = true; try { const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','), handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef }; if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT'); IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; } }); if ($('kbDel')) $('kbDel').addEventListener('click', async () => { if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return; try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); } }); $('kbTitle').focus(); } // a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question function fromTicket(t, question, reply) { const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300); const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '') .replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim(); const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120); const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other'); return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref }; } window.IAPKB = { load: () => load(), compose, fromTicket }; })();