// Admin portal: email-code sign-in (allowlisted to ADMIN_EMAIL on the server),
// house ads that cost nothing, every campaign, members, reports, settings.
(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;
}
function busy(btn, fn) {
return async (...a) => {
if (btn.disabled) return;
btn.disabled = true;
try { await fn(...a); } catch (e) { IAP.status(e.message || 'Something went wrong.', 'bad'); }
finally { btn.disabled = false; }
};
}
const when = ts => ts ? new Date(Number(ts)).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
let rates = {}, sizes = [], houseOwner = 'house@instantadpay.com';
// ── sign-in ──
$('adSend').addEventListener('click', busy($('adSend'), async () => {
$('adErr').hidden = true;
const r = await api('/api/admin/auth/start', { email: $('adEmail').value });
$('adCodeRow').hidden = false; $('adVerify').hidden = false;
if (r.devCode) $('adCode').value = r.devCode;
IAP.status(r.sent ? 'Code sent. Check your inbox.' : 'Dev mode: code filled in.', 'ok');
$('adCode').focus();
}));
$('adVerify').addEventListener('click', busy($('adVerify'), async () => {
$('adErr').hidden = true;
await api('/api/admin/auth/verify', { email: $('adEmail').value, code: $('adCode').value });
await render();
}));
$('adCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('adVerify').click(); });
$('adEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('adVerify').hidden ? $('adSend') : $('adVerify')).click(); });
$('adLogout').addEventListener('click', async e => {
e.preventDefault();
try { await api('/api/admin/auth/logout', {}); } catch (err) {}
location.reload();
});
// ── panes ──
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
function setPane(name) {
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email)
if (!TITLES[name]) name = 'overview';
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name));
$('boTitle').textContent = TITLES[name];
const keepQ = name === 'support' && paneQ ? '?' + paneQ : '';
if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ);
$('adminArea').classList.remove('side-open');
return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad'));
}
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane)));
document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); });
window.addEventListener('hashchange', () => setPane(location.hash.slice(1)));
$('boBurger').addEventListener('click', () => $('adminArea').classList.toggle('side-open'));
async function render() {
let me = { admin: false };
try { me = await api('/api/admin/me'); } catch (e) {}
$('authArea').hidden = !!me.admin;
$('adminArea').hidden = !me.admin;
if (!me.admin) return;
$('adWho').textContent = me.email || 'admin';
try {
const c = await IAP.getConfig();
$('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : '');
} catch (e) {}
setPane(location.hash.slice(1) || 'overview');
supportBadge();
}
// ── overview ──
async function loadOverview() {
const o = await api('/api/admin/overview');
rates = o.rates || rates;
$('ovAccounts').textContent = (o.accounts || 0).toLocaleString();
$('ovMembers').textContent = o.memberCount == null ? '?' : Number(o.memberCount).toLocaleString();
$('ovActive').textContent = (o.byStatus && o.byStatus.active) || 0;
$('ovCampSub').textContent = o.campaigns + ' total · ' + o.house + ' house';
$('ovReports').textContent = o.openReports || 0;
$('ovBurnSub').textContent = (o.pendingBurns || 0) + ' pending burns';
$('repBadge').hidden = !o.openReports; $('repBadge').textContent = o.openReports || '';
const f = o.followups || {};
$('ovDrips').textContent = f.active || 0;
$('ovDripSub').textContent = (f.done || 0) + ' finished · ' + (f.unsubscribed || 0) + ' unsubscribed';
if ($('ovBix')) { $('ovBix').textContent = Number(o.bixLinks || 0).toLocaleString(); $('ovBixSub').textContent = o.bixpayLive ? 'members with their own link · live' : 'members with their own link · bixpayLive is off'; } // BixPay (2026-10-29)
const bt = Object.entries(o.byType || {}).sort((a, b) => b[1] - a[1]);
$('ovByType').innerHTML = bt.length ? bt.map(([t, n]) => '
' + esc(t) + ' ' + n + '
').join('') : 'No campaigns yet.';
const ch = o.chain || {};
$('ovChain').innerHTML = '' + esc(ch.chainName) + ' (chain ' + esc(ch.chainId) + ')
'
+ '' + esc(ch.contract) + '
'
+ (ch.explorer ? 'Open in explorer → ' : '');
}
// ── house ads ──
const HROWS = { banner: ['hBannerRow'], text: ['hTextRow'], login: [], solo: ['hSoloRow'], video: ['hVideoRow'], featured: ['hFeatRow'], visits: ['hVisitsRow'] };
function showHouseRows() {
const t = $('hType').value;
['hBannerRow', 'hTextRow', 'hSoloRow', 'hVideoRow', 'hFeatRow', 'hVisitsRow'].forEach(id => { $(id).hidden = !(HROWS[t] || []).includes(id); });
$('hBudget').hidden = t === 'featured' || t === 'visits';
houseHints();
}
function houseHints() {
const r = rates || {};
const soloCost = r.soloCostPerRecipient || 5, soloMin = r.soloMinRecipients || 10;
const cap = Number($('hBudget').value) || 100000;
$('hSoloHint').textContent = 'Delivers to one inbox per ' + soloCost + ' credits of cap (minimum ' + soloMin + ' recipients). A cap of ' + cap.toLocaleString() + ' reaches up to ' + Math.floor(cap / soloCost).toLocaleString() + ' members.';
const days = Number($('hFeatDays').value) || 0;
$('hFeatHint').textContent = days ? days + '-day run in the featured strip (' + (r.featuredPerDay || 40) + ' credits/day, free here). Book up to ' + (r.featuredWindowDays || 7) + ' days ahead.' : '';
const n = Number($('hVisitCount').value) || 0;
$('hVisitHint').textContent = 'Packs start at ' + (r.visitMinPack || 20) + ' visits.' + (n ? ' ' + n + ' verified visits, delivered one per member.' : '');
}
$('hType').addEventListener('change', showHouseRows);
['hBudget', 'hFeatDays', 'hVisitCount'].forEach(id => $(id).addEventListener('input', houseHints));
$('hFeatDays').addEventListener('change', houseHints);
$('hImageUploadBtn').addEventListener('click', () => $('hImageFile').click());
$('hVideoUploadBtn').addEventListener('click', () => $('hVideoFile').click());
async function upload(fileInput, info, target, kind) {
const f = fileInput.files[0]; if (!f) return;
info.textContent = 'Uploading ' + f.name + '…';
try {
const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
if (r.error) { info.textContent = r.error; }
else { target.value = r.url; info.textContent = f.name + ' uploaded'; }
} catch (e) { info.textContent = 'Upload failed. Try again.'; }
fileInput.value = '';
}
$('hImageFile').addEventListener('change', () => upload($('hImageFile'), $('hImageInfo'), $('hImage')));
$('hVideoFile').addEventListener('change', () => upload($('hVideoFile'), $('hVideoInfo'), $('hVideoUrl')));
let hVidDims = null;
function probeVideoDims(url) {
return new Promise(resolve => {
const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true;
const done = d => { v.src = ''; resolve(d); };
v.onloadedmetadata = () => done(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null);
v.onerror = () => done(null);
setTimeout(() => done(null), 12000);
v.src = url;
});
}
$('hCreate').addEventListener('click', busy($('hCreate'), async () => {
$('hErr').hidden = true;
const t = $('hType').value;
if (t === 'video' && $('hVideoUrl').value) hVidDims = await probeVideoDims($('hVideoUrl').value);
const days = Number($('hFeatDays').value), count = Number($('hVisitCount').value);
const body = { type: t, name: $('hName').value, targetUrl: $('hTarget').value,
imageUrl: $('hImage').value, size: $('hSize').value,
title: t === 'video' ? $('hVideoTitle').value : t === 'featured' ? $('hFeatTitle').value : t === 'visits' ? $('hVisitTitle').value : t === 'solo' ? $('hSoloTitle').value : $('hTitle').value,
body: t === 'solo' ? $('hSoloBody').value : $('hBody').value,
ctaLabel: t === 'video' ? $('hVideoCta').value : $('hSoloCta').value,
videoUrl: $('hVideoUrl').value, watchSecs: Number($('hWatchSecs').value),
videoW: hVidDims ? hVidDims.w : null, videoH: hVidDims ? hVidDims.h : null,
days, startDay: Number($('hFeatStart').value) || 0, count, placement: t === 'visits' && $('hVisitPlace') ? $('hVisitPlace').value : undefined,
budget: t === 'featured' ? days * (rates.featuredPerDay || 40)
: t === 'visits' ? count * (($('hVisitPlace') && $('hVisitPlace').value === 'golden') ? (rates.goldenDoorCost || 6) : ($('hVisitPlace') && $('hVisitPlace').value === 'doors') ? (rates.doorPackCost || 4) : (rates.visitCostPerVisit || 3))
: (Number($('hBudget').value) || 0) };
try {
await api('/api/admin/campaigns', body);
} catch (e) { $('hErr').textContent = e.message; $('hErr').hidden = false; throw e; }
IAP.status('House ad is live. It serves right away at no cost.', 'ok');
['hName', 'hBudget', 'hTarget', 'hImage', 'hTitle', 'hBody', 'hSoloTitle', 'hSoloBody', 'hSoloCta',
'hVideoUrl', 'hVideoTitle', 'hVideoCta', 'hFeatTitle', 'hVisitTitle', 'hVisitCount'].forEach(id => { $(id).value = ''; });
$('hImageInfo').textContent = ''; $('hVideoInfo').textContent = ''; hVidDims = null;
await loadHouse();
}));
function campRow(c, showOwner) {
const left = Math.max(0, (c.budget || 0) - (c.spent || 0));
const creative = c.type === 'banner' && c.imageUrl ? ' ' : esc(c.title || c.name);
const act = c.status === 'active' ? 'Pause '
: c.status === 'paused' ? 'Resume ' : '';
return '#' + c.id + (c.house ? 'HOUSE ' : '') + ' '
+ (showOwner ? '' + esc(c.house ? 'house' : c.owner) + ' ' : '')
+ '' + esc(c.type) + ' '
+ '' + esc(c.name) + '' + creative + '
' + esc(c.targetUrl) + ' '
+ '' + esc(c.status) + ' '
+ '' + (c.spent || 0).toLocaleString() + ' / ' + (c.budget || 0).toLocaleString() + '' + left.toLocaleString() + ' left
'
+ '' + (c.imps || 0).toLocaleString() + (c.impsNas ? ' +' + c.impsNas + ' nas' : '') + '' + (c.clicks || 0) + ' clicks
'
+ '' + when(c.created) + ' '
+ '' + act + ' ';
}
function campHead(showOwner) {
return 'ID ' + (showOwner ? 'Owner ' : '') + 'Type Campaign Status Spent / cap Delivery Created ';
}
async function loadHouse() {
const r = await api('/api/admin/campaigns');
rates = r.rates || rates; sizes = r.bannerSizes || sizes; houseOwner = r.houseOwner || houseOwner;
if (!$('hSize').options.length) $('hSize').innerHTML = sizes.map(s => '' + esc(s.label || s.id) + ' (' + s.w + '×' + s.h + ') ').join('');
if (!$('hWatchSecs').options.length) $('hWatchSecs').innerHTML = (rates.videoTiers || []).map(t => 'Watch ' + t.secs + 's (viewer earns ' + t.reward + ') ').join('');
if (!$('hFeatDays').options.length) $('hFeatDays').innerHTML = (rates.featuredDurations || [1, 2, 7]).map(d => '' + d + ' day' + (d > 1 ? 's' : '') + ' ').join('');
showHouseRows();
loadWallAds();
const house = (r.campaigns || []).filter(c => c.house);
$('houseSub').textContent = house.filter(c => c.status === 'active').length + ' active · ' + house.length + ' total';
$('houseTable').innerHTML = house.length ? campHead(false) + house.map(c => campRow(c, false)).join('') : 'No house ads yet. Place one above. ';
}
// wall fallback ads editor
let wallAds = [];
function drawWallAds() {
const w = $('wallAdsList');
w.innerHTML = wallAds.map((a, i) => 'WALL AD ' + (i + 1) + ' '
+ '↑ ↓ Remove
'
+ '
'
+ (a.bannerUrl ? '
' : '')
+ '
').join('') || 'No wall ads set. Walls fall back to a plain InstantAdPay card.
';
}
function readWallAds() {
return [...document.querySelectorAll('#wallAdsList .drip-step')].map(c => ({ name: c.querySelector('.wa-name').value.trim(), targetUrl: c.querySelector('.wa-target').value.trim(), bannerUrl: c.querySelector('.wa-banner').value.trim() }));
}
async function loadWallAds() {
try { const r = await api('/api/admin/wall-ads'); wallAds = r.ads || []; $('wallAdsSub').textContent = r.usingDefaults ? 'none set: walls show the default InstantAdPay card' : wallAds.length + ' in rotation'; drawWallAds(); } catch (e) {}
}
$('wallAdsList').addEventListener('click', async e => {
const up = e.target.closest('.wa-upload');
if (up) { up.parentElement.querySelector('.wa-file').click(); return; }
const b = e.target.closest('[data-wact]'); if (!b) return;
const i = Number(b.closest('.drip-step').dataset.i); wallAds = readWallAds();
if (b.dataset.wact === 'remove') wallAds.splice(i, 1);
if (b.dataset.wact === 'up' && i > 0) [wallAds[i - 1], wallAds[i]] = [wallAds[i], wallAds[i - 1]];
if (b.dataset.wact === 'down' && i < wallAds.length - 1) [wallAds[i + 1], wallAds[i]] = [wallAds[i], wallAds[i + 1]];
drawWallAds();
});
$('wallAdsList').addEventListener('change', async e => {
const f = e.target.closest('.wa-file'); if (!f || !f.files[0]) return;
const file = f.files[0]; const card = f.closest('.drip-step');
try {
const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': file.type }, body: file })).json();
if (r.error) IAP.status(r.error, 'bad'); else { card.querySelector('.wa-banner').value = r.url; IAP.status('Uploaded.', 'ok'); }
} catch (err) { IAP.status('Upload failed.', 'bad'); }
f.value = '';
});
$('wallAdsAdd').addEventListener('click', () => { wallAds = readWallAds(); wallAds.push({ name: '', targetUrl: '', bannerUrl: '' }); drawWallAds(); });
$('wallAdsSave').addEventListener('click', busy($('wallAdsSave'), async () => {
$('wallAdsErr').hidden = true;
try { const r = await api('/api/admin/wall-ads', { ads: readWallAds() }, 'PATCH'); wallAds = r.ads || []; drawWallAds(); IAP.status('Wall ads saved.', 'ok'); await loadWallAds(); }
catch (e) { $('wallAdsErr').textContent = e.message; $('wallAdsErr').hidden = false; }
}));
document.addEventListener('click', async e => {
const b = e.target.closest('[data-act][data-id]'); if (!b) return;
b.disabled = true;
try {
await api('/api/admin/campaigns/' + b.dataset.id + '/' + b.dataset.act, {});
IAP.status('Campaign #' + b.dataset.id + ' ' + (b.dataset.act === 'pause' ? 'paused' : 'resumed') + '.', 'ok');
await Promise.all([loadHouse(), loadCampaigns()]);
} catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
// ── all campaigns ──
let allCamps = [];
async function loadCampaigns() {
loadLoginLine().catch(e => IAP.status(e.message, 'bad'));
const r = await api('/api/admin/campaigns');
allCamps = r.campaigns || [];
drawCamps();
}
// prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time.
const lqWhen = ts => ts ? esc(ctWhen(ts)) : 'unknown '; // ctWhen (below) prints Central time
async function loadLoginLine() {
const d = await api('/api/admin/login-queue');
$('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open';
$('lqTable').innerHTML = 'Place ID Owner Campaign Paid Queued at Estimated start '
+ (d.queue.length ? d.queue.map(c => '#' + c.place + ' #' + c.id + ' ' + esc(c.owner) + ' '
+ '' + esc(c.name) + ' '
+ '' + Number(c.paid || 0).toLocaleString() + ' ' + lqWhen(c.queuedAt) + ' ' + lqWhen(c.estStart) + ' '
+ 'Cancel + refund ').join('')
: 'Nobody is waiting. When every slot is taken, members can pay now to reserve the next one. ');
}
document.addEventListener('click', async e => {
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' });
if (!ok) return;
b.disabled = true;
try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); }
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
function drawCamps() {
const q = ($('campFilter').value || '').trim().toLowerCase();
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
$('campSub').textContent = list.length + ' of ' + allCamps.length;
$('campTable').innerHTML = list.length ? campHead(true) + list.map(c => campRow(c, true)).join('') : 'Nothing matches. ';
}
$('campFilter').addEventListener('input', drawCamps);
// ── members ──
let allMembers = [];
async function loadTank() {
try {
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
const nReady = r.waiting.filter(w => w.ready).length;
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members held ' + (r.holdHours || 24) + ' h, then auto-assigned in rotation';
// ready = wallet linked: activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; };
const rb = w => (w.opensAt > Date.now() ? ' Opens ' + when(w.opensAt) + ' ' : '') + (w.ready ? ' Ready to activate · ' + left(w) + ' ' : '');
$('tankWait').innerHTML = 'Waiting Email Joined Last sign-in ' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + rb(w) + ' ' + esc(w.email) + ' ' + when(w.joined) + ' ' + (w.lastSeen ? when(w.lastSeen) : 'never ') + ' ').join('') : 'empty ')
+ ((r.aligned || []).length ? 'Aligned to their network sponsor (LinkSpin) instead of the tank ' + r.aligned.slice(0, 15).map(x => '' + esc(x.email) + ' ' + esc(x.toName || x.to) + ' ' + when(x.at) + ' ' + esc(x.via || '') + ' ').join('') : '');
$('tankAdopt').innerHTML = 'Member Adopted by When Window ends Status ' + (r.adoptions.length ? r.adoptions.map(a => '' + esc(a.adopteeName) + ' ' + esc(a.adopterName) + ' ' + when(a.ts) + ' ' + (a.status === 'released' || a.status === 'invited' ? '' : when(a.expires)) + ' ' + esc(a.status) + ' ').join('') : 'none yet ');
} catch (e) {}
}
async function loadMembers() {
loadSpamScan().catch(() => {});
loadTank(); loadFraud();
const r = await api('/api/admin/members');
allMembers = r.members || [];
drawMembers();
}
function drawMembers() {
const q = ($('memFilter').value || '').trim().toLowerCase();
const list = allMembers.filter(a => !q || [a.email, a.username, a.memberId, a.sponsorRef, a.address, a.code].join(' ').toLowerCase().includes(q));
$('memSub').textContent = list.length + ' of ' + allMembers.length;
$('memTable').innerHTML = 'Email Username Member # Wallet Sponsor Positions Via Code Joined '
+ list.map(a => '' + esc(a.email) + ' ' + (a.username ? '@' + esc(a.username) : 'none ') + ' '
+ '' + (a.memberId ? '#' + a.memberId : 'free ') + ' '
+ '' + (a.address ? esc(a.address.slice(0, 8) + '…' + a.address.slice(-6)) : 'none ') + ' '
+ '' + (a.sponsorName ? esc(a.sponsorName) + (a.sponsorVia === 'code' ? ' via code ' + esc(a.sponsorRef) + ' ' : a.sponsorVia === 'member #' ? ' via #' + esc(a.sponsorRef) + ' ' : '') : a.sponsorRef ? 'dead link: ' + esc(a.sponsorRef) + ' ' : 'none ') + ' ' + (a.positions ? a.positions : '0 ') + ' ' + esc(a.joinedVia || '') + ' ' + esc(a.code || '') + ' '
+ '' + when(a.created) + (a.suspended ? ' suspended ' : '') + ((a.flags || []).length ? ' ' + esc((a.flags || []).join(' ')) + ' ' : '') + ' '
+ 'Open ' + (a.suspended ? 'Unsuspend' : 'Suspend') + ' Sponsor ').join('');
}
$('memFilter').addEventListener('input', drawMembers);
// Link-farm list (2026-10-30): the daily scan's candidates; Delete selected = one DELETE /api/admin/member per email (on-chain refused); Allow = spamScanAllow
async function loadSpamScan() {
let v; try { v = await api('/api/admin/spamscan'); } catch (e) { return; }
const last = v.last || {}; const rows = last.candidates || [];
$('spamSub').textContent = last.at ? (rows.length + ' candidate' + (rows.length === 1 ? '' : 's') + ' \u00B7 scanned ' + when(last.at) + (last.manual ? ' (manual)' : '') + ' \u00B7 ' + (last.scanned || 0) + ' accounts, ' + (last.skipped || 0) + ' allowlisted') : 'no scan yet (daily at 06:30 Central)';
$('spamAllow').textContent = 'Allowlist: ' + ((v.allow || []).join(', ') || 'empty');
$('spamTable').innerHTML = 'Account Joined Sponsor First link Why Also on ' + esc(v.otherSite || 'the other site') + ' '
+ (rows.length ? rows.map(c => '' + (c.username ? '@' + esc(c.username) + ' ' : '') + '' + esc(c.email) + ' ' + (c.quarantined ? ' quarantined ' : '') + ' '
+ '' + when(c.created) + ' ' + esc(c.sponsorName || 'none') + ' ' + esc(c.firstLink || '') + ' '
+ '' + esc((c.reasons || []).join(', ')) + ' ' + (c.alsoOn === true ? 'yes' : c.alsoOn === false ? 'no' : 'unknown') + ' '
+ 'Open Allow ').join('') : 'Nothing to review. ');
}
$('spamRun').addEventListener('click', busy($('spamRun'), async () => { await api('/api/admin/spamscan/run', {}); await loadSpamScan(); IAP.status('Scan done.', 'ok'); }));
$('spamDelete').addEventListener('click', busy($('spamDelete'), async () => {
const sel = [...document.querySelectorAll('[data-spamsel]:checked')].map(x => x.dataset.spamsel);
if (!sel.length) { IAP.status('Tick the accounts to delete first.', 'bad'); return; }
if (!await IAP.confirmBox('Delete ' + sel.length + ' account' + (sel.length === 1 ? '' : 's') + ' with their profile text? On-chain members are refused. LinkSpin is not touched.', { title: 'Delete selected', ok: 'Delete', cancel: 'Cancel' })) return;
let ok = 0, bad = 0; for (const e of sel) { try { await api('/api/admin/member?email=' + encodeURIComponent(e), undefined, 'DELETE'); ok++; } catch (err) { bad++; } }
IAP.status(ok + ' deleted' + (bad ? ', ' + bad + ' refused' : '') + '.', bad ? 'bad' : 'ok');
await api('/api/admin/spamscan/run', {}).catch(() => {}); await loadSpamScan(); loadMembers().catch(() => {});
}));
document.addEventListener('click', async e => {
const b = e.target.closest('[data-spamallow]'); if (!b) return;
try { await api('/api/admin/spamscan/allow', { email: b.dataset.spamallow }); IAP.status('Allowed ' + b.dataset.spamallow + '.', 'ok'); await api('/api/admin/spamscan/run', {}).catch(() => {}); loadSpamScan(); } catch (err) { IAP.status(err.message, 'bad'); }
});
document.addEventListener('click', async e => {
const b = e.target.closest('[data-susp]'); if (!b) return;
const on = b.dataset.on === '1';
if (on) { if (!await IAP.confirmBox('Unsuspend ' + b.dataset.susp + '? They can sign in again.', { title: 'Unsuspend', ok: 'Unsuspend', cancel: 'Cancel' })) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: false }, 'PATCH'); }
else { const why = await IAP.ask({ title: 'Suspend ' + b.dataset.susp, text: 'They will be signed out everywhere and cannot sign in. Reason (shown to admins only):', value: 'duplicate account', ok: 'Suspend' }); if (why === null || why === undefined) return; await api('/api/admin/members', { email: b.dataset.susp, suspend: true, reason: why, flags: ['multi-account'] }, 'PATCH'); }
loadMembers();
});
async function loadFraud() {
const box = $('fraudBox'); if (!box) return;
try {
const r = await api('/api/admin/fraud');
const grp = (title, list) => list.length ? '' + title + '
' + list.map(g => '' + esc(g.key) + ': ' + g.emails.map(x => esc(x)).join(', ') + '
').join('') : '';
box.innerHTML = 'Duplicate signals ' + r.total + ' accounts with sign-in signals recorded (since 2026-09-16). Shared browser = same device cookie; shared IP within 30 days. Households are legal; two buying accounts on one browser are not.
'
+ grp('Shared browser', r.sharedDevice) + grp('Shared IP', r.sharedIp)
+ (r.flagged.length ? 'Flagged
' + r.flagged.map(f => '' + esc(f.email) + ' [' + esc(f.flags.join(', ')) + ']' + (f.suspended ? ' suspended' : '') + '
').join('') : '')
+ (r.suspended.length ? 'Suspended
' + r.suspended.map(x => '' + esc(x.email) + ' (' + esc(x.reason || '') + ', ' + when(x.at) + ')
').join('') : '')
+ (!r.sharedDevice.length && !r.sharedIp.length && !r.flagged.length && !r.suspended.length ? 'Nothing shared or flagged yet.
' : '')
// Approved exceptions (Marty, 2026-09-17): people okayed to hold more than one
// account. Lives right under the signals so the two are read together.
+ ''
+ '
Approved exceptions '
+ '
People you have okayed to hold more than one account. They are never blocked at sign-up, never hard-flagged, and keep their leaderboard and adoption rights. Add the address of the account they ALREADY have, or the new one, either works. Suspension still overrides this.
'
+ '
'
+ ' '
+ ' '
+ 'Add exception
'
+ '
'
+ ((r.allow || []).length
? (r.allow || []).map(a => '
'
+ '
' + esc(a.email) + ' '
+ (a.note ? '
' + esc(a.note) + ' ' : '')
+ '
' + when(a.at) + ' '
+ '
remove ').join('')
: '
No exceptions yet. Everyone is held to one account per person.
')
+ '
';
const say = (t, bad) => { const m = $('allowMsg'); if (m) { m.textContent = t; m.style.color = bad ? 'var(--bad)' : 'var(--mint)'; } };
const addBtn = $('allowAdd');
if (addBtn) addBtn.addEventListener('click', async () => {
const em = ($('allowEmail').value || '').trim(); const note = ($('allowNote').value || '').trim();
if (!em) return say('Enter an email address.', true);
addBtn.disabled = true; say('Saving…');
try { await api('/api/admin/fraud/allow', { email: em, note }); say('Added.'); loadFraud(); }
catch (err) { say(err.message, true); addBtn.disabled = false; }
});
box.querySelectorAll('[data-allow-rm]').forEach(a => a.addEventListener('click', async ev => {
ev.preventDefault();
const em = a.getAttribute('data-allow-rm');
if (!(await IAP.confirmBox(em + ' goes back to the normal one-account-per-person checks. Existing accounts are not touched.', { title: 'Remove exception', ok: 'Remove', cancel: 'Cancel' }))) return;
try { await api('/api/admin/fraud/allow', { email: em, remove: true }); loadFraud(); }
catch (err) { say(err.message, true); }
}));
} catch (e) { box.innerHTML = '' + esc(e.message) + '
'; }
}
document.addEventListener('click', async e => {
const b = e.target.closest('[data-spon]'); if (!b) return;
const v = await IAP.ask({ title: 'Sponsor for ' + b.dataset.spon, text: 'Username, share code, or member #. Leave blank to clear.', value: b.dataset.cur, ok: 'Save' });
if (v === null || v === undefined) return;
try {
await api('/api/admin/members', { email: b.dataset.spon, sponsorRef: v.trim() }, 'PATCH');
IAP.status('Sponsor updated.', 'ok');
await loadMembers();
} catch (err) { IAP.status(err.message, 'bad'); }
});
// ── member card: search, drill down, act (Marty, 2026-09-13) ──
let mcCur = null;
const polOf = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } };
const ago = ts => { if (!ts) return 'never'; const d = Date.now() - Number(ts); const h = Math.floor(d / 3600000); return h < 1 ? Math.max(1, Math.floor(d / 60000)) + ' min ago' : h < 48 ? h + ' h ago' : Math.floor(h / 24) + ' days ago'; };
const memLink = (email, label) => '' + esc(label) + ' ';
async function openMember(q) {
const msg = $('memSearchMsg'); msg.hidden = true;
let d;
try { d = await api('/api/admin/member?q=' + encodeURIComponent(q)); } catch (e) { msg.textContent = e.message; msg.hidden = false; msg.className = 'small bad'; return; }
renderMember(d);
}
function kv(rows) { return '' + rows.map(r => '' + r[0] + ' ' + r[1] + ' ').join('') + '
'; }
function renderMember(d) {
mcCur = d; const a = d.account; $('memHits').hidden = true;
$('memCard').hidden = false; document.querySelectorAll('#pane-members > .card').forEach(c => { if (c.id !== 'memCard' && c.id !== 'memSearchCard') c.hidden = true; });
$('mcName').textContent = (a.username ? '@' + a.username : a.email) + (a.memberId ? ' · member #' + a.memberId : ' · free member');
$('mcSub').textContent = 'joined ' + when(a.created) + ' · last seen ' + ago(a.lastSeen) + (a.profileQuarantined ? ' · PROFILE QUARANTINED (link planted on a brand-new free account; not shown publicly)' : '');
$('mcWall').hidden = !a.username; if (a.username) $('mcWall').href = '/wall/' + a.username;
const ch = d.chain, cr = d.credits, t = d.totals;
const level = ch && !ch.readError ? (ch.buyerCount >= 5 ? 'level 3 (5+ buyers)' : ch.buyerCount >= 2 ? 'level 2 (2 buyers)' : 'level 1') : '';
let h = '';
h += '
Identity ' + kv([
['Email', esc(a.email)], ['Username', a.username ? '@' + esc(a.username) : '
not set '], ['Share code', esc(a.code || '')],
// A linked wallet is NOT an active position: linking is a free signature, switching on
// payouts is a separate transaction that creates the position. The address used to sit here
// on its own, which reads as "he is set up" when he is not (Marty, 2026-09-17, @mcbit1).
['Main wallet', a.address
? '
' + esc(a.address) + ' '
+ (ch && !ch.readError
? '
payouts ON '
: '
payouts OFF ')
: '
none linked '],
['PolyWarriors mint passes', d.pwPasses ? '
' + (d.pwPasses.n || 0) + ' unused
(earned ' + (d.pwPasses.earned || 0) + ', used ' + (d.pwPasses.used || 0) + ') ' : '
none '],
['Extra positions', d.positions.length ? d.positions.map(p => '
' + esc(p.address.slice(0, 8) + '…' + p.address.slice(-6)) + ' ' + (p.memberId ? ' = #' + p.memberId : ' (unregistered)')).join('
') : '
none '],
['Sponsor (site)', d.upline.length ? memLink(d.upline[0].email, d.upline[0].name) + '
token ' + esc(a.sponsorRef || '') + ' ' : (a.sponsorRef ? '
unresolved: ' + esc(a.sponsorRef) + ' ' : '
none (company) ')],
['Upline chain', d.upline.length > 1 ? d.upline.map(u => memLink(u.email, u.name)).join(' → ') : '
- '],
['Joined via', esc(a.joinedVia || 'join page') + (a.joinedRef ? ' from ' + esc(a.joinedRef) : '')],
['Line banner', a.lineTargetUrl ? '
' + esc(a.lineTargetUrl.slice(0, 50)) + ' ' : '
not set '],
['BixPay partner link', a.bixPartnerLink ? '
' + esc(a.bixPartnerLink) + ' ' : '
not set (pages use a sponsor’s link or the network link) '],
['Chat', a.chatAvailable ? 'available' : 'switched off']]) + '
';
h += '
On-chain and money ' + kv([
// Say WHICH of the two "not registered" states this is, and what it costs them, so the row
// above never gets read as "he is fine".
['Registered', ch
? (ch.readError ? 'read error' : 'yes, #' + ch.memberId + ' under ' + (ch.sponsorId ? '#' + ch.sponsorId + (d.names[ch.sponsorId] ? ' @' + esc(d.names[ch.sponsorId]) : '') : 'nobody'))
: (a.address
? 'no wallet linked, but payouts were never switched on, so no position exists. Sales in their line walk up to their sponsor and lock there. '
: 'no no wallet linked yet. ')],
['Qualifying buyers', ch && !ch.readError ? ch.buyerCount + ' · ' + level : '-'],
['Packages bought', t.purchases + (t.purchases ? ' · $' + (t.spentCents / 100).toFixed(0) + ' · ' + polOf(t.spentWei) + ' POL' : '')],
['Payouts received', t.payoutsIn + (t.payoutsIn ? ' · ' + polOf(t.receivedWei) + ' POL' : '')],
['Credits', cr ? cr.available.toLocaleString() + ' available · ' + cr.inCampaigns.toLocaleString() + ' in campaigns · ' + cr.total.toLocaleString() + ' total' : '- '],
['Earned pool', d.earnedSplit ? d.earnedSplit.total.toLocaleString() + ' (' + (d.earnedSplit.grade || 0).toLocaleString() + ' purchased-grade)' : '-'],
['Old-site account', d.legacy ? 'had a ' + (d.legacy.brand === 'both' ? 'Faucet Wave and Tier One Ads' : d.legacy.brand === 'tier1ads' ? 'Tier One Ads' : 'Faucet Wave') + ' account (' + d.legacy.seg + ') · welcome-back credits ' + (d.legacy.grant ? d.legacy.grant.credits + ' issued ' + when(d.legacy.grant.at) : 'not issued (joined outside the legacy bridge)') : 'none on record '],
['Promo codes', d.promos.length ? d.promos.map(p => esc(p.code) + ' (' + p.credits + ', ' + when(p.ts) + ')').join(' ') : 'none '],
['Drip', d.drip ? (d.drip.stopped ? 'stopped' : 'step ' + d.drip.step + ', next ' + when(d.drip.next_at)) + (d.drip.angle ? ' · ' + esc(d.drip.angle) : '') : '- '],
['Holding tank', d.tank ? (d.tank.waiting ? 'waiting for a sponsor ' : 'not in tank') + (d.tank.adoptedBy.length ? ' · adopted by ' + d.tank.adoptedBy.map(x => memLink(x.email, x.name)).join(', ') : '') + (d.tank.adopted.length ? ' · adopted ' + d.tank.adopted.map(x => memLink(x.email, x.name)).join(', ') : '') : '-'],
['Earning', d.earning ? 'today ' + d.earning.today + '/5' + (d.earning.claimed ? ' claimed' : '') + ' · streak day ' + d.earning.streakDay + (d.activeDays14 !== undefined ? ' · active ' + d.activeDays14 + ' of last 14 days, ' + d.claims14 + ' claims' : '') : '-'],
['Visits / videos / chat', (d.visits || 0) + ' verified visits · ' + (d.videos || 0) + ' video watches · ' + (d.messageCount || 0) + ' messages']]) + ' ';
// line
h += 'Line (' + d.lineCounts.join(' / ') + ') ';
if (!d.line.length) h += 'Nobody in their line yet.
';
for (const L of d.line) {
h += 'Level ' + L.level + ' · ' + L.members.length + '
Member Member # Wallet Bought Qualified Joined Last seen '
+ L.members.map(m => '' + memLink(m.email, m.name) + (L.level === 1 ? '' + esc(m.email) + ' ' : '') + ' ' + (m.memberId ? '#' + m.memberId : 'free ') + ' ' + (m.wallet ? 'yes' : 'no ') + ' ' + (m.bought ? 'yes' : 'no ') + ' ' + (m.qualified ? 'yes ' : '') + ' ' + when(m.joined) + ' ' + ago(m.lastSeen) + ' ').join('') + '
';
}
// purchases + payouts + campaigns
h += 'Purchases When Position Package Paid Tx '
+ (d.purchases.length ? d.purchases.map(p => '' + when(p.ts) + ' #' + p.buyerId + ' $' + (p.priceCents / 100).toFixed(0) + ' · ' + Number(p.credits || 0).toLocaleString() + ' cr ' + polOf(p.paidWei) + ' POL ' + esc(p.tx.slice(0, 10)) + '… ').join('') : 'No purchases. ') + '
';
h += '
Payouts received When From Tier Amount '
+ (d.received.length ? d.received.map(r => '' + when(r.ts) + ' #' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + ' ' + r.tier + ' ' + polOf(r.amountWei) + ' POL ').join('') : 'Nothing received yet. ') + '
';
h += 'Campaigns (' + d.campaigns.length + ') # Type Status Budget Spent Views Clicks Created '
+ (d.campaigns.length ? d.campaigns.map(c => '' + c.id + ' ' + esc(c.type) + ' ' + esc(c.status) + ' ' + Number(c.budget || 0).toLocaleString() + ' ' + Number(c.spent || 0).toLocaleString() + ' ' + (c.pack ? Number(c.views || 0).toLocaleString() + ' of ' + Number(c.pack).toLocaleString() + ' visits ' : Number(c.views || 0).toLocaleString()) + ' ' + Number(c.clicks || 0).toLocaleString() + ' ' + when(c.created) + ' ').join('') : 'No campaigns. ') + '
';
$('mcBody').innerHTML = h;
if (location.hash !== '#members') history.replaceState(null, '', '#members');
loadTrace(d);
}
// payment trace under the member card (2026-09-16): per purchase, who was paid / skipped and why
async function loadTrace(d) {
const ch = d.chain || {}; const mid = ch.memberId || (d.account && d.account.memberId) || 0;
const box = document.createElement('div'); box.id = 'mcTrace'; box.innerHTML = 'Payment trace Reading the chain…
';
$('mcBody').appendChild(box);
if (!mid) { box.innerHTML = 'Payment trace Not activated on the chain, nothing to trace.
'; return; }
try {
const r = await api('/api/admin/trace?who=' + mid);
const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody';
let h = 'Payment trace ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' · every purchase this member was part of, newest first.
';
if (!r.purchases.length) h += 'No purchases involving them yet.
';
for (const p of r.purchases) {
h += '' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought $' + (p.priceCents / 100).toFixed(0) + ' (' + polOf(p.paidWei) + ' POL)' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + ' · ' + esc(p.tx.slice(0, 12)) + '…
';
for (const t of p.tiers) {
let line = '
L' + t.tier + ' ' + t.pct + '% : ';
for (const x of t.skipped) line += '
' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' buyers then' : esc(x.reason)) + ') → ';
line += t.paidTo ? '
' + nm(t.paidTo) + ' ' + polOf(t.amountWei) + ' POL ' : '
no catcher → company ';
h += '
' + line + '
';
}
h += '
platform ' + polOf(p.adminWei) + ' POL
';
}
box.innerHTML = h;
} catch (e) { box.innerHTML = 'Payment trace ' + esc(e.message) + '
'; }
}
function closeMember() { $('memCard').hidden = true; document.querySelectorAll('#pane-members > .card').forEach(c => { c.hidden = false; }); }
// live matches while typing: any part of the username, email, member #, share code or wallet
let memHitList = [];
function memMatches(q) {
q = q.toLowerCase();
return allMembers.filter(a => [a.username, a.email, a.memberId ? '#' + a.memberId : '', a.memberId, a.code, a.address, a.sponsorName].filter(Boolean).join(' ').toLowerCase().includes(q)).slice(0, 12);
}
async function memTypeahead() {
const q = $('memSearch').value.trim();
if (!allMembers.length) { try { const r = await api('/api/admin/members'); allMembers = r.members || []; } catch (e) {} }
if (q.length < 2) { $('memHits').hidden = true; memHitList = []; return; }
memHitList = memMatches(q);
$('memHits').innerHTML = memHitList.length ? memHitList.map(a => '' + (a.username ? '@' + esc(a.username) : 'no username ') + ' ' + esc(a.email) + ' ' + (a.memberId ? '#' + a.memberId : 'free') + (a.sponsorName ? ' · under ' + esc(a.sponsorName) : '') + ' ').join('')
: 'No member matches that.
';
$('memHits').hidden = false;
}
$('memSearch').addEventListener('input', memTypeahead);
$('memSearch').addEventListener('focus', memTypeahead);
$('memOpen').addEventListener('click', () => { const q = $('memSearch').value.trim(); if (!q) return; if (memHitList.length) openMember(memHitList[0].email); else openMember(q); });
$('memSearch').addEventListener('keydown', e => { if (e.key === 'Enter') $('memOpen').click(); if (e.key === 'Escape') $('memHits').hidden = true; });
document.addEventListener('click', e => { if (!e.target.closest('#memSearchCard')) $('memHits').hidden = true; });
$('mcBack').addEventListener('click', closeMember);
document.addEventListener('click', e => { const l = e.target.closest('[data-mcopen]'); if (l) { e.preventDefault(); openMember(l.dataset.mcopen); } });
document.querySelectorAll('[data-mcact]').forEach(b => b.addEventListener('click', busy(b, async () => {
if (!mcCur) return; const a = mcCur.account, act = b.dataset.mcact; let body = null;
if (act === 'username') { const v = await IAP.ask({ title: 'Username for ' + a.email, text: '3-20 letters, numbers or underscore. Changing it breaks any invite links they already handed out.', value: a.username || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { username: v }; }
if (act === 'sponsor') { const v = await IAP.ask({ title: 'Sponsor for ' + (a.username ? '@' + a.username : a.email), text: 'Username, share code or member #. Blank = no sponsor (company). Re-points free referrals and future purchases; on-chain sponsorship never changes.', value: a.sponsorRef || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { sponsorRef: v }; }
if (act === 'wallet') { const v = await IAP.ask({ title: 'Main wallet for ' + a.email, text: 'Paste the 0x address that should be their main wallet (the one that paid, if a purchase came from an unlinked account). The member number is re-read from the chain. Blank = unlink.', value: a.address || '', ok: 'Swap' }); if (v === null || v === undefined) return; if (!await IAP.confirmBox('Swap the main wallet for ' + a.email + ' to ' + (v.trim() || 'nothing') + '?', { title: 'Sure?', ok: 'Swap it', cancel: 'Cancel' })) return; body = { address: v }; }
if (act === 'credits') { const v = await IAP.ask({ title: 'Grant credits to ' + (a.username ? '@' + a.username : a.email), text: 'Whole number of earned-pool credits (1 credit = 1 cent of delivery). They can spend them on campaigns right away.', type: 'number', value: '', placeholder: '250', ok: 'Grant' }); if (!v) return; const note = await IAP.ask({ title: 'Reason (kept in the server log)', value: '', placeholder: 'e.g. refund for broken banner', ok: 'Grant' }); body = { grantCredits: v, note: note || '' }; }
// message the member (Marty 2026-11-12): lands in their member inbox AND emails them (opt-outs honoured by the mailer)
if (act === 'message') {
const who = a.username ? '@' + a.username : a.email;
const subject = await IAP.ask({ title: 'Message ' + who, text: 'Subject line. The message goes to their member inbox and is emailed to them (unless they unsubscribed from email).', value: '', placeholder: 'A quick note from Marty', ok: 'Next' }); if (!subject) return;
const text = await IAP.ask({ title: subject, text: 'Your message. Plain text; blank lines start new paragraphs.', type: 'textarea', value: '', ok: 'Send' }); if (!text || !text.trim()) return;
const r = await api('/api/admin/member/message', { email: a.email, subject, text }, 'POST');
IAP.status('Sent to ' + who + "'s inbox" + (r.emailed ? ' and emailed.' : r.emailSkipped ? '. Email skipped: ' + r.emailSkipped + '.' : '.'), r.emailed ? 'ok' : 'warn'); return;
}
if (act === 'delete') {
if (a.memberId) { IAP.status('Registered members cannot be deleted; their position is on-chain.', 'bad'); return; }
if (!await IAP.confirmBox('Delete the free account ' + a.email + '? Their sign-in, referrals link and credits go away. There is no undo.', { title: 'Delete account', ok: 'Delete', cancel: 'Keep it' })) return;
await api('/api/admin/member?email=' + encodeURIComponent(a.email), undefined, 'DELETE'); IAP.status('Account deleted.', 'ok'); closeMember(); loadMembers().catch(() => {}); return;
}
if (!body) return;
const d = await api('/api/admin/member', Object.assign({ email: a.email }, body), 'PATCH');
renderMember(d); IAP.status('Saved.', 'ok'); loadMembers().catch(() => {});
})));
// ── every admin table: click a header to sort (numbers sort as numbers), inputs with
// class "tfilter" filter the table named in data-for ──
document.addEventListener('click', e => {
const th = e.target.closest('.adm-table th'); if (!th || th.closest('table').classList.contains('kv')) return;
const table = th.closest('table'), hdr = th.parentElement, idx = [...hdr.children].indexOf(th);
const rows = [...table.querySelectorAll('tr')].filter(r => r !== hdr && r.children.length > 1);
const num = s => { const t = String(s).replace(/[$,%\s]/g, '').replace(/…$/, ''); return t !== '' && !isNaN(t) ? Number(t) : null; };
const dir = th.dataset.dir === 'asc' ? 'desc' : 'asc';
hdr.querySelectorAll('th').forEach(x => { delete x.dataset.dir; x.classList.remove('sort-asc', 'sort-desc'); });
th.dataset.dir = dir; th.classList.add('sort-' + dir);
rows.sort((r1, r2) => { const a = (r1.children[idx] || {}).textContent || '', b = (r2.children[idx] || {}).textContent || ''; const na = num(a), nb = num(b); const c = na !== null && nb !== null ? na - nb : a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); return dir === 'asc' ? c : -c; });
rows.forEach(r => (hdr.parentElement).appendChild(r));
});
document.addEventListener('input', e => {
const inp = e.target.closest('.tfilter'); if (!inp) return;
const table = $(inp.dataset.for); if (!table) return;
const q = inp.value.trim().toLowerCase(); let shown = 0;
[...table.querySelectorAll('tr')].forEach((r, i) => { if (i === 0 || r.querySelector('th')) return; const hit = !q || r.textContent.toLowerCase().includes(q); r.hidden = !hit; if (hit) shown++; });
const c = inp.parentElement.querySelector('.tfilter-count'); if (c) c.textContent = q ? shown + ' shown' : '';
});
// ── release notes + roadmap (Marty, 2026-09-14) ──
async function loadReleases() {
loadUpdates();
const d = await api('/api/admin/releases');
$('rnSub').textContent = d.notes.length + ' notes'; $('rmSub').textContent = d.roadmap.length + ' items';
$('rnTable').innerHTML = 'Date Title Tags ' + (d.notes.length ? d.notes.map(n => '' + esc(n.date) + ' ' + esc(n.title) + ' ' + esc(n.tags.join(', ')) + ' Edit Delete ').join('') : 'No notes yet. ');
$('rmTable').innerHTML = 'Status Title ETA # ' + (d.roadmap.length ? d.roadmap.map(r => '' + esc(r.status) + ' ' + esc(r.title) + ' ' + (r.note ? '' + esc(r.note) + ' ' : '') + '' + esc(r.eta || '') + ' ' + (r.order || '') + ' Edit Delete ').join('') : 'Nothing on the roadmap yet. ');
$('rnTable').querySelectorAll('[data-rnedit]').forEach(b => b.addEventListener('click', () => { const n = d.notes.find(x => x.id === b.dataset.rnedit); if (!n) return; $('rnId').value = n.id; $('rnTitle').value = n.title; $('rnDate').value = n.date; $('rnTags').value = n.tags.join(', '); $('rnBody').value = n.body; $('rnTitle').focus(); }));
$('rmTable').querySelectorAll('[data-rmedit]').forEach(b => b.addEventListener('click', () => { const r = d.roadmap.find(x => x.id === b.dataset.rmedit); if (!r) return; $('rmId').value = r.id; $('rmTitle').value = r.title; $('rmStatus').value = r.status; $('rmEta').value = r.eta || ''; $('rmOrder').value = r.order || ''; $('rmNote').value = r.note || ''; $('rmTitle').focus(); }));
$('rnTable').querySelectorAll('[data-rndel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this release note?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=notes&id=' + encodeURIComponent(b.dataset.rndel), undefined, 'DELETE'); loadReleases(); }));
$('rmTable').querySelectorAll('[data-rmdel]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Delete this roadmap item?', { ok: 'Delete', cancel: 'Keep' })) return; await api('/api/admin/releases?kind=roadmap&id=' + encodeURIComponent(b.dataset.rmdel), undefined, 'DELETE'); loadReleases(); }));
}
// ── member update emails (Marty, 2026-09-14) ──
async function loadUpdates() {
if (!$('updCard')) return;
try {
const d = await api('/api/admin/updates');
$('updSub').textContent = (d.mailer ? '' : 'mailer not configured · ') + (d.lastSentAt ? 'last send ' + new Date(d.lastSentAt).toLocaleString() : 'nothing sent yet') + (d.running ? ' · sending now' : '');
const keep = $('updAudience').value;
$('updAudience').innerHTML = Object.entries(d.audiences).map(([k, v]) => '' + esc(v) + (d.counts ? ' (' + (d.counts[k] || 0) + ')' : ' (counting…)') + ' ').join('');
if (keep) $('updAudience').value = keep;
if (!d.counts) setTimeout(() => loadUpdates().catch(() => {}), 15000); // the counts are being worked out in the background
// a re-render (the background count refresh) must keep whatever is ticked; only the first render pre-ticks fresh notes,
// and a saved draft decides for itself (Marty, 2026-09-28: a test send carried every note because a refresh re-ticked them)
const wasTicked = new Set([...$('updNotes').querySelectorAll('input:checked')].map(i => i.value)), rendered = $('updNotes').querySelector('input') !== null;
$('updNotes').innerHTML = d.notes.length ? d.notes.map(n => '' + esc(n.title) + ' ' + esc(n.date) + ' ').join('') : 'No release notes yet. ';
$('updLog').innerHTML = 'When Subject Audience Sent ' + (d.sends.length ? d.sends.map(x => '' + new Date(x.ts).toLocaleString() + ' ' + esc(x.subject) + ' ' + esc(d.audiences[x.audience] || x.audience) + ' ' + x.sent + ' of ' + x.total + (x.skipped ? ' · ' + x.skipped + ' opted out' : '') + (x.failed ? ' · ' + x.failed + ' failed' : '') + (x.unknown ? ' · ' + x.unknown + ' unchecked (Sendy gave no answer)' : '') + (x.status === 'running' ? ' · running' : '') + ' ').join('') : 'None yet. ');
if (d.draft && !updDraftLoaded) { updDraftLoaded = true; $('updSubject').value = d.draft.subject || ''; $('updIntro').value = d.draft.intro || ''; $('updClosing').value = d.draft.closing || ''; if (d.draft.audience) $('updAudience').value = d.draft.audience; $('updNotes').querySelectorAll('input').forEach(i => { i.checked = (d.draft.noteIds || []).includes(i.value); }); $('updSub').textContent += ' · draft loaded (saved ' + new Date(d.draft.savedAt).toLocaleString() + ')'; }
if (d.running) setTimeout(loadUpdates, 4000);
} catch (e) { $('updSub').textContent = e.message; }
}
let updDraftLoaded = false;
const updInput = () => ({ subject: $('updSubject').value, intro: $('updIntro').value, closing: $('updClosing').value, noteIds: [...$('updNotes').querySelectorAll('input:checked')].map(i => i.value), audience: $('updAudience').value });
if ($('updCard')) {
$('updSaveDraft').addEventListener('click', busy($('updSaveDraft'), async () => { await api('/api/admin/updates/draft', updInput()); IAP.status('Draft saved.', 'ok'); }));
$('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; }));
$('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); }));
$('updSend').addEventListener('click', busy($('updSend'), async () => {
const inp = updInput(); if (!inp.noteIds.length && !String(inp.intro || '').trim()) { IAP.status('Write an intro or pick at least one note.', 'bad'); return; }
const opt = $('updAudience').selectedOptions[0].textContent;
if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return;
const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates();
}));
}
$('rnClear').addEventListener('click', () => { ['rnId', 'rnTitle', 'rnDate', 'rnTags', 'rnBody'].forEach(id => { $(id).value = ''; }); });
$('rmClear').addEventListener('click', () => { ['rmId', 'rmTitle', 'rmEta', 'rmOrder', 'rmNote'].forEach(id => { $(id).value = ''; }); $('rmStatus').value = 'planned'; });
$('rnSave').addEventListener('click', busy($('rnSave'), async () => { await api('/api/admin/releases', { kind: 'note', id: $('rnId').value || null, title: $('rnTitle').value, date: $('rnDate').value, tags: $('rnTags').value, body: $('rnBody').value }); IAP.status('Note saved.', 'ok'); $('rnClear').click(); loadReleases(); }));
$('rmSave').addEventListener('click', busy($('rmSave'), async () => { await api('/api/admin/releases', { kind: 'roadmap', id: $('rmId').value || null, title: $('rmTitle').value, status: $('rmStatus').value, eta: $('rmEta').value, order: $('rmOrder').value, note: $('rmNote').value }); IAP.status('Roadmap item saved.', 'ok'); $('rmClear').click(); loadReleases(); }));
// ── reports + burns ──
// ── profit and loss ──
let pnlDays = 30;
const pol = w => { try { return (Number(BigInt(w || '0') / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }); } catch (e) { return '0'; } };
const usdOf = (w, px) => { try { return '$' + ((Number(BigInt(w || '0') / 10n ** 14n) / 10000) * px).toLocaleString(undefined, { maximumFractionDigits: 0 }); } catch (e) { return '$0'; } };
// ── traffic: referring domains / sources, landing pages, angles, by day ──
let trfDays = 30;
document.querySelectorAll('#trfRange [data-days]').forEach(b => b.addEventListener('click', () => { trfDays = Number(b.dataset.days); document.querySelectorAll('#trfRange [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadTraffic().catch(e => IAP.status(e.message, 'bad')); }));
async function loadPromos() {
const d = await (await fetch('/api/admin/promos')).json();
if (d.error) throw new Error(d.error);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const when = t => t ? new Date(t).toLocaleDateString() : '';
$('pcTable').innerHTML = 'Code Credits Partner Uses Max Expires Status '
+ (d.codes.length ? d.codes.map(c => '' + esc(c.code) + ' ' + c.credits.toLocaleString() + ' ' + esc(c.partner) + ' ' + c.uses + ' ' + (c.maxUses || '∞') + ' ' + (c.expires ? when(c.expires) : '') + ' ' + (c.active ? 'active' : 'off') + ' ' + (c.active ? 'Switch off' : 'Switch on') + ' ').join('') : 'No codes yet. ');
$('pcRecent').innerHTML = 'When Code Email Credits Via '
+ (d.recent.length ? d.recent.map(r => '' + new Date(r.ts).toLocaleString() + ' ' + esc(r.code) + ' ' + esc(r.email) + ' ' + r.credits + ' ' + esc(r.via) + ' ').join('') : 'No redemptions yet. ');
document.querySelectorAll('[data-pctoggle]').forEach(b => b.addEventListener('click', async () => {
try { await api('/api/admin/promos', { code: b.dataset.pctoggle, active: b.dataset.on === '1' }, 'PATCH'); loadPromos(); } catch (e) { IAP.status(e.message, 'bad'); }
}));
}
if ($('pcSave')) $('pcSave').addEventListener('click', async () => {
const msg = $('pcMsg'); msg.hidden = false;
try {
const r = await api('/api/admin/promos', { code: $('pcCode').value, credits: $('pcCredits').value, partner: $('pcPartner').value, maxUses: $('pcMax').value, expires: $('pcExpires').value || null, active: true });
msg.textContent = 'Saved ' + r.code.code + ': ' + r.code.credits + ' credits.'; msg.style.color = 'var(--mint)';
$('pcCode').value = ''; $('pcCredits').value = ''; $('pcPartner').value = ''; loadPromos();
} catch (e) { msg.textContent = e.message; msg.style.color = 'var(--bad)'; }
});
async function loadTraffic() {
loadPromos().catch(e => IAP.status(e.message, 'bad'));
loadLoginShows().catch(e => IAP.status(e.message, 'bad'));
const d = await (await fetch('/api/admin/traffic?days=' + trfDays)).json();
if (d.error) throw new Error(d.error);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const n = v => Number(v || 0).toLocaleString();
$('trfSub').textContent = 'last ' + d.days + ' days · ' + n(d.totals.hits) + ' page views · ' + n(d.totals.joinViews) + ' join-page views · ' + n(d.totals.signups) + ' signups · ' + n(d.totals.buyers) + ' buyers';
// conversion columns (Marty, 2026-09-13): visits = page views + join-page views; signup rate is per visit,
// registered and buyer rates are per signup (what happened to the people who did sign up)
const pct = (num, den) => den ? (100 * num / den).toFixed(num && 100 * num / den < 10 ? 1 : 0) + '%' : '- ';
$('trfSources').innerHTML = 'Source Page views Join-page views Signups Visit → signup Registered Signup → registered $20+ buyers Signup → buyer '
+ (d.sources.length ? d.sources.map(s => '' + esc(s.source) + ' ' + n(s.hits) + ' ' + n(s.joinViews) + ' ' + n(s.signups) + ' ' + pct(s.signups, s.hits + s.joinViews) + ' ' + n(s.registered) + ' ' + pct(s.registered, s.signups) + ' ' + n(s.buyers) + ' ' + pct(s.buyers, s.signups) + ' ').join('') : 'Nothing recorded in this range yet. ');
// games to members (2026-10-05): card taps that reached InstantAdPay, first packages bought, dollars, per game (all time)
if (d.starter) { const st = d.starter, rows = Object.values(st.games);
$('stSub').textContent = (st.settings.on ? 'on' : 'off') + ' · welcome bonus ' + st.settings.bonus + ' credits · ' + st.granted + ' granted';
$('trfStarter').innerHTML = 'Game Offer taps First packages Package $ Tap → buy ' + rows.map(g => '' + esc(g.name) + ' ' + n(g.visits) + ' ' + n(g.buyers) + ' $' + g.usd.toFixed(2) + ' ' + pct(g.buyers, g.visits) + ' ').join(''); }
$('trfPaths').innerHTML = 'Page Views ' + (d.paths.length ? d.paths.map(p => '' + esc(p.path) + ' ' + n(p.hits) + ' ').join('') : 'No page views yet. ');
// BixPay clicks by surface + per member (2026-10-29)
if (d.bixpay && $('trfBix')) { const bx = d.bixpay, LBL = { wallet: 'Wallet tab card', overview: 'Overview card', email: 'Payout emails', nudge: 'Game wallet nudges', promo: 'Promo tools (members’ posts and banners)', guide: '/bixpay guide', chat: 'Chatbot', other: 'Other' };
$('bixSub').textContent = 'last ' + bx.days + ' days: ' + n(bx.total) + ' clicks · all time ' + n(bx.allTime) + (bx.live ? '' : ' · bixpayLive is OFF');
const rows = Object.entries(bx.bySurface).sort((a, b) => b[1] - a[1]);
$('trfBix').innerHTML = 'Surface Clicks ' + (rows.length ? rows.map(([s, c]) => '' + esc(LBL[s] || s) + ' ' + n(c) + ' ').join('') : 'No BixPay clicks in this range yet. ');
$('trfBixMembers').innerHTML = 'Member All clicks Via promo kit Last ' + (bx.members.length ? bx.members.map(m => '' + esc(m.name || m.email) + ' ' + n(m.total) + ' ' + n(m.promo) + ' ' + (m.last ? ago(m.last) : '') + ' ').join('') : 'No member clicks yet. '); }
$('trfAngles').innerHTML = 'Angle Join-page views Signups View → signup ' + (d.angles.length ? d.angles.map(a => '' + esc(a.angle) + ' ' + n(a.views) + ' ' + n(a.signups) + ' ' + pct(a.signups, a.views) + ' ').join('') : 'No angle data yet. ');
$('trfDaily').innerHTML = 'Day Page views Signups ' + (d.daily.length ? d.daily.slice().reverse().map(x => '' + esc(x.day) + ' ' + n(x.hits) + ' ' + n(x.signups) + ' ').join('') : 'Nothing yet. ');
}
// login-ad showings per Central day (2026-10-18): the dashboard gate vs the games' sign-in kit, member slot vs house ad,
// and sign-ins that had no login ad to show. A week of these decides whether the 3-slot cap goes up.
async function loadLoginShows() {
const d = await (await fetch('/api/admin/login-shows?days=14')).json();
if (d.error) throw new Error(d.error);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const n = v => Number(v || 0).toLocaleString(), shown = x => x.member + x.house;
const week = d.days.slice(0, 7).reduce((a, x) => { a.dash += shown(x.dashboard); a.games += shown(x.games); return a; }, { dash: 0, games: 0 });
$('lsSub').textContent = 'last 7 days: ' + n(week.dash + week.games) + ' shown (' + n(week.dash) + ' dashboard, ' + n(week.games) + ' games) · slots ' + d.slots.used + ' of ' + d.slots.max + ' taken';
$('trfLogin').innerHTML = 'Day (CT) Dashboard shown Games shown Total shown Of which house ad Sign-ins with no login ad By game '
+ d.days.map(x => '' + esc(x.day) + ' ' + n(shown(x.dashboard)) + ' ' + n(shown(x.games)) + ' ' + n(shown(x.dashboard) + shown(x.games)) + ' ' + n(x.dashboard.house + x.games.house) + ' ' + n(x.dashboard.none + x.games.none) + ' '
+ (Object.keys(x.byGame).length ? Object.entries(x.byGame).map(([g, v]) => esc(g) + ' ' + n(v)).join(', ') : '- ') + ' ').join('');
}
// ── blog: coaching articles, public at /blog (Marty, 2026-09-12) ──
let blCur = null; // slug being edited, or null for a new one
function blCount() {
const t = $('blTitle').value.length, e = $('blExcerpt').value.length;
$('blTitleCount').textContent = t + '/60' + (t > 60 ? ' (long)' : '');
$('blExcCount').textContent = e + ' chars' + (e && (e < 120 || e > 160) ? ' (aim 120-160)' : '');
const w = $('blBody').textContent.trim().split(/\s+/).filter(Boolean).length;
$('blWords').textContent = w + ' words';
}
['blTitle', 'blExcerpt'].forEach(id => $(id).addEventListener('input', blCount));
$('blBody').addEventListener('input', blCount);
$('blTitle').addEventListener('input', () => { if (!blCur && !$('blSlug').dataset.touched) $('blSlug').value = $('blTitle').value.toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80); });
$('blSlug').addEventListener('input', () => { $('blSlug').dataset.touched = '1'; });
document.querySelectorAll('.ed-bar [data-bl]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand(b.dataset.bl, false, null); }));
document.querySelectorAll('.ed-bar [data-blblock]').forEach(b => b.addEventListener('click', () => { $('blBody').focus(); document.execCommand('formatBlock', false, b.dataset.blblock); }));
$('blLinkBtn').addEventListener('click', async () => {
const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
const u = await IAP.ask({ title: 'Link address', label: 'https://', placeholder: 'https://instantadpay.com/join/martbost', ok: 'Insert' });
if (u) { $('blBody').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); }
});
$('blImgBtn').addEventListener('click', () => $('blImgFile').click());
$('blImgFile').addEventListener('change', async () => {
const f = $('blImgFile').files[0]; if (!f) return;
try {
const r = await (await fetch('/api/admin/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
if (r.error) throw new Error(r.error);
$('blBody').focus();
const html = ' ';
if (!document.execCommand('insertHTML', false, html)) $('blBody').insertAdjacentHTML('beforeend', html);
blCount();
} catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); }
$('blImgFile').value = '';
});
$('blCoverBtn').addEventListener('click', () => $('blCoverFile').click());
$('blCoverFile').addEventListener('change', () => upload($('blCoverFile'), $('blCoverInfo'), $('blCover')));
$('blHtmlBtn').addEventListener('click', () => {
const raw = !$('blHtml').hidden;
if (raw) { $('blBody').innerHTML = $('blHtml').value; $('blHtml').hidden = true; $('blBody').hidden = false; }
else { $('blHtml').value = $('blBody').innerHTML; $('blBody').hidden = true; $('blHtml').hidden = false; }
blCount();
});
function blBodyHtml() { return $('blHtml').hidden ? $('blBody').innerHTML : $('blHtml').value; }
function blMsg(t, bad) { $('blMsg').textContent = t; $('blMsg').hidden = !t; $('blMsg').className = 'small ' + (bad ? 'bad' : 'ok'); }
function blOpen(post) {
blCur = post ? post.slug : null;
$('blogList').hidden = true; $('blogEditor').hidden = false;
$('blEdTitle').textContent = post ? 'Edit article' : 'New article';
$('blEdSub').textContent = post ? (post.status === 'published' ? 'published ' + when(post.publishedAt) + ' · ' + (post.views || 0) + ' views' : 'draft') : '';
$('blTitle').value = post ? post.title : ''; $('blSlug').value = post ? post.slug : ''; delete $('blSlug').dataset.touched;
$('blTags').value = post ? post.tags.join(', ') : ''; $('blExcerpt').value = post ? post.excerpt : ''; $('blCover').value = post ? post.cover : ''; $('blCoverInfo').textContent = '';
$('blHtml').hidden = true; $('blBody').hidden = false; $('blBody').innerHTML = post ? post.body : '';
$('blUnpublish').hidden = !(post && post.status === 'published'); $('blDelete').hidden = !post;
$('blPreview').hidden = !post; if (post) $('blPreview').href = '/blog/' + post.slug;
$('blPublish').textContent = post && post.status === 'published' ? 'Save and publish' : 'Publish';
blMsg(''); blCount(); $('blTitle').focus();
}
async function blSave(status) {
const body = { existingSlug: blCur, title: $('blTitle').value, slug: $('blSlug').value, tags: $('blTags').value, excerpt: $('blExcerpt').value, cover: $('blCover').value, body: blBodyHtml(), status };
const r = await api('/api/admin/blog', body);
blCur = r.post.slug;
$('blSlug').value = r.post.slug; $('blPreview').hidden = false; $('blPreview').href = '/blog/' + r.post.slug; $('blDelete').hidden = false;
$('blUnpublish').hidden = r.post.status !== 'published'; $('blPublish').textContent = r.post.status === 'published' ? 'Save and publish' : 'Publish';
$('blEdTitle').textContent = 'Edit article';
blMsg(r.post.status === 'published' ? 'Published. Live at instantadpay.com/blog/' + r.post.slug + (r.syndicating ? ' · posting to X and Instagram now (see the Social column in the list).' : '') : 'Draft saved.');
IAP.status(r.post.status === 'published' ? 'Published.' : 'Draft saved.', 'ok');
}
$('blSaveDraft').addEventListener('click', busy($('blSaveDraft'), () => blSave('draft')));
$('blPublish').addEventListener('click', busy($('blPublish'), () => blSave('published')));
$('blUnpublish').addEventListener('click', busy($('blUnpublish'), () => blSave('draft')));
$('blClose').addEventListener('click', () => { $('blogEditor').hidden = true; $('blogList').hidden = false; loadBlog().catch(e => IAP.status(e.message, 'bad')); });
$('blDelete').addEventListener('click', busy($('blDelete'), async () => {
if (!blCur) return;
if (!await IAP.confirmBox('The page at /blog/' + blCur + ' stops existing. There is no undo.', { title: 'Delete this article?', ok: 'Delete', cancel: 'Keep it' })) return;
await api('/api/admin/blog?slug=' + encodeURIComponent(blCur), undefined, 'DELETE');
$('blClose').click();
}));
$('blNew').addEventListener('click', () => blOpen(null));
async function loadBlog() {
const d = await api('/api/admin/blog');
const pub = d.posts.filter(p => p.status === 'published').length;
$('blSub').textContent = pub + ' published · ' + (d.posts.length - pub) + ' drafts';
const synd = p => { const s = p.syndicated; if (!s) return p.status === 'published' ? 'not posted ' : ''; const r = s.results || {}; const part = ['x', 'instagram'].map(k => r[k] ? (r[k].ok ? k + ' ✓' : k + ' ✗') : k + ' –').join(' · '); return '' + part + ' '; };
$('blSyndNote').hidden = false; $('blSyndNote').textContent = d.syndication ? 'Publishing an article posts it to X (@cryptoteambuild) and Instagram (marketingwithmarty) through Blotato, once per article, with the cover image.' : 'Social syndication is off: no Blotato key on the server.';
$('blTable').innerHTML = 'Title Status Social Tags Views Updated '
+ (d.posts.length ? d.posts.map(p => '' + esc(p.title) + ' /blog/' + esc(p.slug) + ' ' + (p.status === 'published' ? 'published ' : 'draft ') + ' ' + synd(p) + ' ' + esc(p.tags.join(', ')) + ' ' + (p.views || 0) + ' ' + when(p.updated) + ' Edit View ' + (p.status === 'published' && d.syndication && !(p.syndicated && p.syndicated.done) ? ' Post to X + IG ' : '') + ' ').join('')
: 'No articles yet. Start with "New article". ');
$('blTable').querySelectorAll('[data-blsynd]').forEach(b => b.addEventListener('click', busy(b, async () => {
const r = await api('/api/admin/blog/syndicate', { slug: b.dataset.blsynd });
const res = r.syndicated && r.syndicated.results || {}; const bad = Object.entries(res).filter(([, v]) => !v.ok).map(([k, v]) => k + ': ' + v.error);
IAP.status(bad.length ? 'Posted with problems: ' + bad.join(' | ') : 'Posted to X and Instagram.', bad.length ? 'bad' : 'ok'); loadBlog().catch(() => {});
})));
$('blTable').querySelectorAll('[data-bledit]').forEach(b => b.addEventListener('click', async () => {
try { const r = await api('/api/admin/blog?slug=' + encodeURIComponent(b.dataset.bledit)); blOpen(r.post); } catch (e) { IAP.status(e.message, 'bad'); }
}));
}
async function loadPnl() {
loadOverride().catch(() => {}); // its own request: does not wait for the chain reads below
const r = await api('/api/admin/pnl?days=' + pnlDays);
const px = r.polUsd || 0;
const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px;
const months = pnlDays ? pnlDays / 30 : Math.max(1, (r.latest - r.fromBlock) / 43200 / 30);
const fixed = (r.fixedMonthlyUsd || 0) * months;
$('pnlTiles').innerHTML = [
['Packages sold', r.purchases.count, Object.entries(r.purchases.byPackage || {}).map(([k, v]) => v + '×' + k).join(' · ') || '—'],
['Gross volume', pol(r.purchases.volumeWei) + ' POL', usdOf(r.purchases.volumeWei, px) + ' at today\'s rate · $' + (r.purchases.usdCents / 100).toLocaleString() + ' at sale'],
['Platform (fees + dust + unclaimed)', pol(r.platformWei) + ' POL', usdOf(r.platformWei, px)],
['Paid to members', pol(r.memberPayoutsWei) + ' POL', usdOf(r.memberPayoutsWei, px)],
['Net after fixed costs', '$' + Math.round(platUsd - fixed).toLocaleString(), 'fixed ' + Math.round(fixed).toLocaleString() + ' over ' + months.toFixed(1) + ' month(s)'],
['Pass-ups', r.passedUp.count, r.passedUp.unqualified + ' unqualified · ' + r.passedUp.sendFailed + ' send-failed']
].map(t => '' + esc(String(t[1])) + '
' + esc(t[0]) + '
' + esc(t[2]) + ' ').join('');
// PolHunter: a marketing cost paid from its own faucet, so it is read across rather than
// derived from our chain events (Marty, 2026-09-23)
const ph = r.polhunter, phEl = $('pnlHunt');
if (phEl) {
if (!ph || ph.error || !ph.totals) phEl.innerHTML = 'PolHunter figures unavailable' + (ph && ph.error ? ' (' + esc(ph.error) + ')' : '') + '. ';
else {
const t = ph.totals, rf = ph.referrals || {}, usd = n => '$' + (Number(n) * px).toFixed(2);
const findPol = Math.max(0, Number(t.pol || 0) - Number(rf.paidPol || 0));
phEl.innerHTML = 'Line POL USD now '
+ [['Mission finds (' + Number(t.paid || 0).toLocaleString() + ' paid)', findPol],
['Referral bounties (' + Number(rf.bounties || 0) + ')', null],
['Referral matches (' + Number(rf.matches || 0) + ')', null],
['Referral payouts total', Number(rf.pol || 0)],
['All PolHunter payouts', Number(t.pol || 0)]]
.filter(x => x[1] !== null)
.map(x => '' + x[0] + ' ' + Number(x[1]).toFixed(4) + ' ' + usd(x[1]) + ' ').join('')
+ 'Hunters paid ' + Number(t.hunters || 0) + ' today ' + Number(t.today || 0).toFixed(3) + ' POL ';
}
}
// every game's payouts, all time, running total (Marty, 2026-10-18). PassiveDrip is a drip
// program rather than a game, so it sits under the total instead of inside it.
const ga = r.gamesAll, gaEl = $('pnlGames');
if (gaEl) {
if (!ga || ga.error || !Array.isArray(ga.games) || !ga.games.length) gaEl.innerHTML = '' + (ga && ga.scanning ? 'Reading the game wallets from Polygon for the first time. Refresh in a minute.' : 'Game payout figures unavailable' + (ga && ga.error ? ' (' + esc(ga.error) + ')' : '') + '.') + ' ';
else {
const wp = w => Number(BigInt(w) / 10n ** 12n) / 1e6, games = ga.games.filter(g => g.slug !== 'passivedrip'), pd = ga.games.find(g => g.slug === 'passivedrip');
const row = (name, w, n, pl, cls) => '' + name + ' ' + wp(w).toFixed(4) + ' $' + (wp(w) * px).toFixed(2) + ' ' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + ' ';
const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0);
gaEl.innerHTML = 'Game POL USD now Payouts to players '
+ games.map(g => row(esc(g.name) + (g.error ? ' stale ' : ''), g.wei, g.count, g.players)).join('')
+ 'All game payouts ' + wp(tw).toFixed(4) + ' $' + (wp(tw) * px).toFixed(2) + ' ' + tn.toLocaleString() + ' payouts '
+ (pd ? row('PassiveDrip (not a game) ', pd.wei, pd.count, pd.players) : '')
+ 'Read ' + (ga.at ? new Date(ga.at).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' }) + ' CT' : 'just now') + (ga.scanning ? ', refreshing' : '') + '. Updates every 10 minutes. ';
}
}
$('pnlSplit').innerHTML ='Line POL USD now '
+ [['Level 1 (50%)', r.byTier[1]], ['Level 2 (20%)', r.byTier[2]], ['Level 3 (10%)', r.byTier[3]], ['Platform (20% + pass-ups)', r.platformWei]].map(x => '' + x[0] + ' ' + pol(x[1]) + ' ' + usdOf(x[1], px) + ' ').join('');
const W = r.wallets || {}, B = r.balances || {};
$('pnlWallets').innerHTML = 'Wallet Address Balance '
+ [['Owner / fee A (Tangem)', W.feeA, B.feeA], ['Fee B', W.feeB, B.feeB], ['Engine (gas)', W.engine, B.engine]].filter(x => x[1]).map(x => '' + x[0] + ' ' + esc(x[1]) + ' ' + (x[2] == null ? '?' : pol(x[2]) + ' POL') + ' ').join('');
renderLedger(r);
$('pnlFixed').value = r.fixedMonthlyUsd || 0;
const b = r.burner || {};
$('burnerLine').textContent = !b.hasEthers ? 'ethers is not installed in this build.' : !b.keyPresent ? 'No engine key configured (ENGINE_KEY). Burns stay pending until it is set.' : b.mismatch ? 'ENGINE_KEY does not match the contract engine signer. Disabled.' : 'Engine wallet ' + b.address + ' holds ' + pol(b.balanceWei) + ' POL. That is its gas fund, not a cost: one burn uses about 0.003 POL (roughly 48,000 gas), paid by this wallet, never by the member. ' + b.burned + ' burn' + (b.burned === 1 ? '' : 's') + ' since boot' + (b.lastRun ? ' · last check ' + when(b.lastRun) : '') + (b.lastError ? ' · last error: ' + b.lastError : '') + (b.skipped && Object.keys(b.skipped).length ? ' · skipped (needs review): ' + Object.entries(b.skipped).map(([k, v]) => k + ' (' + v + ')').join(', ') : '');
}
// The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that
// makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody
// wrote down (Marty, 2026-09-23).
const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' };
const LD_CAT = { advertising: 'Advertising', games: 'Game marketing', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' };
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' };
const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 });
function renderLedger(r) {
const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {};
if ($('pnlLedger')) {
$('pnlLedger').innerHTML = 'Date Wallet Kind POL What for '
+ (rows.length ? rows.map(e => '' + e.date + ' ' + (LD_WALLET[e.wallet] || e.wallet) + ' '
+ '' + (LD_KIND[e.kind] || e.kind) + (e.kind === 'cost' ? ' (' + (LD_CAT[e.category] || e.category || 'other') + ') ' : '') + ' '
+ '' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount)
+ (e.usd ? ' ($' + Number(e.usd).toFixed(2) + ') ' : '') + ' '
+ '' + esc(e.note || '') + ' '
+ 'Remove ').join('')
: 'Nothing recorded yet. ');
$('pnlLedger').querySelectorAll('[data-ldkill]').forEach(b => b.addEventListener('click', async () => {
if (!await IAP.confirmBox('Remove this ledger line?')) return;
try { await api('/api/admin/ledger/delete', { id: b.dataset.ldkill }); loadPnl(); }
catch (e) { IAP.status('Could not remove it: ' + e.message, 'bad'); }
}));
}
if ($('pnlRecon')) {
const drift = Number(rec.drift || 0);
const ok = Math.abs(drift) < 0.01;
$('pnlRecon').innerHTML = 'Receiver A earned ' + pol4(rec.earnedPol) + ' POL on chain'
+ (t.revenuePol ? ' plus ' + pol4(t.revenuePol) + ' outside revenue' : '')
+ (t.drawPol ? ', less ' + pol4(t.drawPol) + ' drawn' : '')
+ (t.transferPol ? ', ' + (t.transferPol > 0 ? 'plus ' : 'less ') + '' + pol4(Math.abs(t.transferPol)) + ' transferred in for storage' : '')
+ '. Expected ' + pol4(rec.expected) + ' , actually holding ' + pol4(rec.actual) + ' . '
+ (ok ? 'Reconciled. '
: 'Unexplained: ' + pol4(drift) + ' POL '
+ '(' + (drift > 0 ? 'more on hand than accounted for, so income or a transfer in is missing a line'
: 'less on hand than accounted for, so a draw is missing a line') + ') ');
}
}
if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => {
const body = { dir: $('ldDir').value, kind: $('ldKind').value, category: $('ldCat') ? $('ldCat').value : '', wallet: $('ldWallet').value,
amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0,
date: $('ldDate').value, note: $('ldNote').value };
try {
await api('/api/admin/ledger', body);
$('ldAmount').value = ''; $('ldUsd').value = ''; $('ldNote').value = '';
IAP.status('Line added.', 'good'); loadPnl();
} catch (e) { IAP.status(e.message, 'bad'); }
});
// a draw is almost never revenue and an outside deposit almost never a draw: move the kind with
// the direction, but leave it editable
if ($('ldDir')) $('ldDir').addEventListener('change', () => {
$('ldKind').value = $('ldDir').value === 'in' ? 'revenue' : 'draw';
});
document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); }));
if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
// Level 4 override (2026-10-23): week status from /api/admin/override; the pay button exists only while the live payer is ready
const OV_STATE = { 'not planned': 'not planned', planning: 'planning', planned: 'pending', paying: 'paying', held: 'held', paid: 'paid' };
async function loadOverride(week) {
if (!$('ovPayer')) return;
let r; try { r = await (await fetch('/api/admin/override' + (week ? '?week=' + encodeURIComponent(week) : ''), { cache: 'no-store' })).json(); } catch (e) { $('ovPayer').textContent = 'Could not read the override: ' + e.message; return; }
const pz = r.payer || {};
$('ovPayer').textContent = 'Mode: ' + (pz.mode || '?') + (pz.ready ? ' · PAYING automatically each Monday after 9 AM CT' : ' · not paying (' + (pz.why || []).join('; ') + ')')
+ (pz.address ? ' · payer wallet ' + pz.address + ' holds ' + (pz.balancePol || '?') + ' POL' : '') + ' · weekly cap ' + (pz.capPol || '?') + ' POL · minimum ' + (pz.dustPol || '?') + ' POL'
+ (pz.goLive ? ' · purchases from ' + new Date(pz.goLive).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : '') + (pz.lastError ? ' · last error: ' + pz.lastError.msg : '');
$('ovPay').hidden = !pz.ready;
const sel = $('ovWeek'); if (!sel.options.length) { const now = new Date(); for (let i = 0; i < 10; i++) { const d = new Date(now.getTime() - i * 7 * 86400000); const v = d.toISOString().slice(0, 10); sel.innerHTML += 'week containing ' + v + ' '; } sel.selectedIndex = 1; }
$('ovWeeks').innerHTML = (r.dueWeeks || []).length ? 'Week of Status Total ' + r.dueWeeks.map(w => '' + esc(w.week) + ' ' + esc(OV_STATE[w.state] || w.state) + (w.heldWhy ? ' (' + esc(w.heldWhy) + ') ' : '') + ' ' + esc(w.totalPol || '0') + ' POL ').join('') + '
' : '';
const st = r.status || {}; const t = r.totals || {};
$('ovOut').innerHTML = 'Week of ' + esc(r.week || '') + ': ' + (r.purchases || 0) + ' purchases, $' + Number(t.salesUsd || 0).toFixed(2) + ' sales. Override due: $' + Number(t.wouldPayUsd || 0).toFixed(2) + ' (' + Number(t.wouldPayPol || 0).toFixed(4) + ' POL) to ' + (r.recipients || []).length + ' members; company keeps $' + Number(t.companyKeepsUsd || 0).toFixed(2) + '. Payout status: ' + esc(OV_STATE[st.state] || st.state || '?') + ' ' + (st.heldWhy ? ' (' + esc(st.heldWhy) + ')' : '') + '.
'
+ ((st.rows || []).length ? 'Member POL USD Status ' + st.rows.map(x => '#' + x.memberId + ' ' + esc(x.pol) + ' $' + Number(x.usd || 0).toFixed(2) + ' ' + esc(x.state) + (x.note ? ' ' + esc(x.note) + ' ' : '') + ' ' + (x.tx ? 'tx ' : '') + ' ').join('') + '
'
: (r.recipients || []).length ? 'Member POL USD Buys ' + r.recipients.map(x => '#' + x.recipientId + ' ' + Number(x.pol).toFixed(4) + ' $' + Number(x.usd).toFixed(2) + ' ' + x.purchases + ' ').join('') + '
' : '');
}
if ($('ovShow')) $('ovShow').addEventListener('click', () => loadOverride($('ovWeek').value));
if ($('ovPay')) $('ovPay').addEventListener('click', async () => {
const wk = $('ovWeek').value;
if (!await IAP.confirmBox('This sends real POL from the payer wallet for every closed week up to the week containing ' + wk + ' that is not paid yet. Each member is paid once; anything already paid is skipped.', { title: 'Pay the override now?', ok: 'Pay now' })) return;
try { const r = await api('/api/admin/override/pay', { week: wk }); IAP.status('Override: ' + (r.results || []).map(x => x.week + ' ' + (x.state || x.held || (x.why || []).join(', '))).join(' · '), 'ok'); loadOverride(wk); } catch (e) { IAP.status(e.message, 'bad'); }
});
if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
async function loadAudit() {
if (!$('audTable')) return;
try {
$('audSub').textContent = 'checking…';
const a = await api('/api/admin/audit');
const bad = a.checks.filter(c => !c.ok).length;
$('audSub').textContent = (bad ? bad + ' issue' + (bad === 1 ? '' : 's') : 'all counters reconcile') + ' · checked ' + new Date(a.checkedAt).toLocaleTimeString();
$('audTable').innerHTML = 'Check Status Detail ' + a.checks.map(c => '' + esc(c.name) + ' ' + (c.ok ? 'ok ' : '' + c.issues.length + ' issue' + (c.issues.length === 1 ? '' : 's') + ' ') + ' ' + esc(c.detail) + (c.issues.length ? ' ' + c.issues.map(esc).join(' ') : '') + ' ').join('');
} catch (e) { $('audSub').textContent = e.message; }
}
if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit));
// ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ──
const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' };
const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' };
const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '$1 ');
let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = [];
async function supportBadge() {
try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; }
}
async function loadSupport(q) {
const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1];
if (ref) return openTicket(ref);
$('spView').hidden = true; $('spList').hidden = false;
const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString();
const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]);
spTemplates = tp.templates || []; spCats = r.categories || spCats;
const c = r.counts || {};
$('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || '');
$('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread';
const chip = (v, label, n) => '' + label + (n != null ? ' (' + n + ')' : '') + ' ';
$('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All');
if (!$('spCategory').options.length) $('spCategory').innerHTML = 'All categories ' + spCats.map(x => '' + esc(x) + ' ').join('');
$('spTable').innerHTML = 'Ticket Subject From Category Status Last activity '
+ (r.tickets.length ? r.tickets.map(t => '' + (t.adminUnread ? '● ' : '') + esc(t.ref)
+ (t.platform !== 'iap' ? ' ' + esc(t.platform) + ' ' : '') + (t.priority === 'high' ? ' high ' : '') + ' '
+ '' + (t.adminUnread ? '' + esc(t.subject) + ' ' : esc(t.subject)) + '' + esc(t.source) + '
'
+ '' + esc(t.name || '') + '' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '
'
+ '' + esc(t.category) + ' ' + esc(SP_STATUS[t.status] || t.status) + ' ' + esc(ctWhen(t.updated)) + ' ').join('')
: 'No tickets here. ');
drawTemplates();
}
$('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
$('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
$('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); });
$('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } });
async function openTicket(ref) {
const v = await api('/api/admin/support/' + encodeURIComponent(ref));
if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} }
if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
drawTicket(v); supportBadge();
}
function drawTicket(v) {
const t = v.ticket, rq = v.requester || {};
$('spList').hidden = true; $('spView').hidden = false;
const sel = (id, opts, cur) => '' + opts.map(o => '' + esc(o[1]) + ' ').join('') + ' ';
const stOpts = Object.entries(SP_STATUS);
$('spView').innerHTML = '‹ All tickets
'
+ '
' + esc(t.subject) + ' ' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + ' '
+ '
Status ' + sel('spSt', stOpts, t.status) + ' '
+ 'Priority ' + sel('spPr', [['normal', 'Normal'], ['high', 'High']], t.priority) + ' '
+ 'Category ' + sel('spCat', spCats.map(c => [c, c]), t.category) + '
'
+ '
Requester ' + (rq.member ? 'member account' : 'no account with this email') + ' '
+ kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [
['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' ·
open member card '],
['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '
' + esc(v.link) + ' ']]))
+ '
'
+ '
Thread ' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + ' '
+ v.messages.map(m => '
'
+ '
' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + ' ' + esc(ctWhen(m.created)) + '
'
+ '
' + spLink(m.body) + '
'
+ (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '
Save as KB entry
' : '')
+ (m.bodyEn ? '
🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath) \n' + spLink(m.bodyEn) + '
' : '')
+ ((m.attachments || []).length ? '
' + m.attachments.map(a => '
').join('') + '
' : '') + '
').join('')
+ '
'
+ '
Reply emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + ' '
+ '
Insert a saved reply… ' + spTemplates.map((x, i) => '' + esc(x.name) + ' ').join('') + '
'
+ '
'
+ '
Internal note (only you see it, nothing is sent) '
+ 'Then set status ' + sel('spAfter', stOpts, 'waiting_on_member') + ' '
+ 'Send reply
';
$('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20)
const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return;
const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal);
const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body);
await setPane('kb'); window.IAPKB.compose(draft);
}));
$('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } };
$('spSt').addEventListener('change', () => patch({ status: $('spSt').value }));
$('spPr').addEventListener('change', () => patch({ priority: $('spPr').value }));
$('spCat').addEventListener('change', () => patch({ category: $('spCat').value }));
if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); });
$('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; });
$('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; });
$('spSend').addEventListener('click', busy($('spSend'), async () => {
const internal = $('spInternal').checked;
if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return;
drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value }));
supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok');
}));
}
function drawTemplates() {
$('spTpls').innerHTML = spTemplates.map((x, i) => '').join('') || 'No saved replies. Add one below.
';
}
const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value }));
$('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); });
$('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); });
$('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); }));
async function loadReports() {
loadAudit();
const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]);
const reps = r.reports || [];
$('repTable').innerHTML = reps.length ? 'When Campaign Reason Note By '
+ reps.map(x => '' + when(x.ts) + ' #' + x.campaignId + ' ' + esc(x.reason) + ' ' + esc(x.note || '') + ' ' + esc(x.reporter || 'anon') + ' '
+ '' + (x.resolved ? 'resolved' : 'Pause ad Resolve ') + ' ').join('')
: 'No reports. ';
const burns = b.pending || [];
$('burnTable').innerHTML = burns.length ? 'When Member Credits Ref Burn id '
+ burns.map(x => '' + when(x.ts) + ' #' + x.memberId + ' ' + x.amount + ' ' + esc(x.ref) + ' ' + esc(x.id) + ' ').join('')
: 'Nothing pending. ';
}
document.addEventListener('click', async e => {
const b = e.target.closest('[data-resolve]'); if (!b) return;
b.disabled = true;
try { await api('/api/admin/reports/' + b.dataset.resolve + '/resolve', {}); IAP.status('Report resolved.', 'ok'); await Promise.all([loadReports(), loadOverview()]); }
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
// ── settings: graphical editors (follow-up emails, rates, site settings) ──
let dripSeq = [], ratesObj = {}, siteObj = {};
let lastFocusedField = null;
document.addEventListener('focusin', e => { if (e.target && (e.target.matches('textarea.ds-body') || e.target.matches('input.ds-subject'))) lastFocusedField = e.target; });
document.addEventListener('click', e => {
const c = e.target.closest('[data-ph]'); if (!c) return;
const el = lastFocusedField; if (!el) { IAP.status('Click into a subject or body first, then the chip.', 'bad'); return; }
const ph = c.dataset.ph, st = el.selectionStart || 0, en = el.selectionEnd || st;
el.value = el.value.slice(0, st) + ph + el.value.slice(en);
el.focus(); el.selectionStart = el.selectionEnd = st + ph.length;
el.dispatchEvent(new Event('input'));
});
const whenLabel = h => { h = Number(h) || 0; if (h < 24) return h + ' hour' + (h === 1 ? '' : 's') + ' after sign-up'; const d = h / 24; return (Number.isInteger(d) ? d : d.toFixed(1)) + ' day' + (d === 1 ? '' : 's') + ' after sign-up'; };
function drawDrip() {
const wrap = $('dripSteps');
wrap.innerHTML = dripSeq.map((st, i) => '').join('') || 'No emails yet. Add one below.
';
}
function readDrip() {
return [...document.querySelectorAll('#dripSteps .drip-step')].map(card => ({
hours: Number(card.querySelector('.ds-hours').value) || 0,
subject: card.querySelector('.ds-subject').value.trim(),
body: card.querySelector('.ds-body').value.trim()
}));
}
$('dripSteps').addEventListener('input', e => {
if (e.target.classList.contains('ds-hours')) { const l = e.target.closest('.ds-when').querySelector('.ds-whenlbl'); if (l) l.textContent = '(' + whenLabel(e.target.value) + ')'; }
});
$('dripSteps').addEventListener('click', async e => {
const b = e.target.closest('[data-act]'); if (!b) return;
const card = b.closest('.drip-step'), i = Number(card.dataset.i);
dripSeq = readDrip();
if (b.dataset.act === 'remove') { if (!await IAP.confirmBox('Remove email ' + (i + 1) + ' from the sequence?', { title: 'Remove step', ok: 'Remove', cancel: 'Keep' })) return; dripSeq.splice(i, 1); drawDrip(); return; }
if (b.dataset.act === 'up' && i > 0) { [dripSeq[i - 1], dripSeq[i]] = [dripSeq[i], dripSeq[i - 1]]; drawDrip(); return; }
if (b.dataset.act === 'down' && i < dripSeq.length - 1) { [dripSeq[i + 1], dripSeq[i]] = [dripSeq[i], dripSeq[i + 1]]; drawDrip(); return; }
if (b.dataset.act === 'test') {
b.disabled = true;
try { await saveDrip(); await api('/api/admin/drip/test', { step: i }); IAP.status('Email ' + (i + 1) + ' sent to your inbox.', 'ok'); }
catch (err) { IAP.status(err.message, 'bad'); }
b.disabled = false;
}
});
async function saveDrip() {
$('dripErr').hidden = true;
const seq = readDrip();
const r = await api('/api/admin/drip', { sequence: seq }, 'PATCH').catch(err => { $('dripErr').textContent = err.message; $('dripErr').hidden = false; throw err; });
dripSeq = r.sequence; drawDrip();
return r;
}
$('dripSave').addEventListener('click', busy($('dripSave'), async () => { await saveDrip(); IAP.status('Sequence saved.', 'ok'); await loadSettings(); }));
$('dripAdd').addEventListener('click', () => {
dripSeq = readDrip();
const last = dripSeq[dripSeq.length - 1];
dripSeq.push({ hours: last ? Number(last.hours) + 48 : 24, subject: '', body: '\n\nMarty\n\n{{footer}}' });
drawDrip();
const cards = document.querySelectorAll('#dripSteps .drip-step'); const c = cards[cards.length - 1]; if (c) { c.scrollIntoView({ behavior: 'smooth', block: 'center' }); c.querySelector('.ds-subject').focus(); }
});
$('dripReset').addEventListener('click', busy($('dripReset'), async () => {
if (!await IAP.confirmBox('Replace the saved sequence with the built-in defaults?', { title: 'Reset sequence', ok: 'Replace', cancel: 'Cancel' })) return;
const r = await api('/api/admin/drip', { reset: true }, 'PATCH');
dripSeq = r.sequence; drawDrip(); IAP.status('Defaults restored.', 'ok'); await loadSettings();
}));
// rates: labels + hints for the known keys; anything unknown still gets a plain field
const RATE_META = {
bannerBatch: ['Banner: views per batch', 'impressions counted before a banner campaign is charged'],
bannerCreditsPerBatch: ['Banner: credits per batch', 'charged to the advertiser per batch'],
textBatch: ['Text ad: views per batch', ''], textCreditsPerBatch: ['Text ad: credits per batch', ''],
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space banner views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
synRateDivisorText: ['Network rate divisor for TEXT ads (N)', 'Network Ad Space text-ad views cost 1/N of the on-site text rate (10 = 1 credit per 100 network views); whole numbers'],
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
viewDwellSeconds: ['Ad view: seconds per ad', 'the countdown; server-enforced'],
soloCostPerRecipient: ['Solo ad: credits per recipient', ''], soloMinRecipients: ['Solo ad: minimum recipients', ''],
soloReadCredits: ['Solo ad: reader reward (credits)', ''], soloReadCapPerDay: ['Solo ad: rewarded reads per day', ''], soloReadDwellSeconds: ['Solo ad: seconds to read', ''],
videoWatchCapPerDay: ['Video: rewarded watches per day', ''],
featuredPerDay: ['Featured link: credits per day', ''], featuredSlotsPerDay: ['Featured link: slots per day', ''], featuredWindowDays: ['Featured link: booking window (days)', ''],
featuredDurations: ['Featured link: durations offered (days)', 'comma-separated'],
doorPackCost: ['Spooky Doors: door pack, credits per door', 'placement "Behind Spooky Doors"'], goldenDoorCost: ['Spooky Doors: Golden Door, credits per door', 'placement "Golden Spooky Door"'],
goldenBonusCandy: ['Spooky Doors: Golden Door bonus candy', 'sent to the game as bonus'], sdSeasonEnd: ['Spooky Doors: season end (Central day, exclusive)', 'from this day door packs run as normal visits (YYYY-MM-DD)'],
visitCostPerVisit: ['Verified visit: credits per visit', ''], visitMinPack: ['Verified visit: smallest pack', ''], visitReward: ['Verified visit: viewer reward (credits)', ''], visitDwellSeconds: ['Verified visit: seconds on site', ''], visitCapPerDay: ['Verified visit: rewarded visits per day', ''],
videoTiers: ['Video ad tiers', 'watch length → advertiser cost → viewer reward'],
milestoneBonus: ['Milestone bonuses (credits)', 'one-time, when a member reaches each step']
};
const humanize = k => k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase());
function drawRates() {
const wrap = $('ratesForm'); const html = [];
for (const [k, v] of Object.entries(ratesObj)) {
const [label, hint] = RATE_META[k] || [humanize(k), ''];
if (typeof v === 'number') html.push('' + esc(label) + ' ' + (hint ? '' + esc(hint) + ' ' : '') + '
');
else if (typeof v === 'boolean') html.push('' + esc(label) + ' on
');
else if (Array.isArray(v) && v.every(x => typeof x === 'number')) html.push('' + esc(label) + ' ' + (hint ? '' + esc(hint) + ' ' : '') + '
');
else if (Array.isArray(v) && v.every(x => x && typeof x === 'object')) {
const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; const txt = new Set(cols.filter(c => v.some(x => typeof x[c] === 'string'))); // text columns (doorHouseAds) stay text
html.push('' + esc(label) + ' ' + (hint ? '
' + esc(hint) + ' ' : '')
+ '
');
} else if (v && typeof v === 'object') {
html.push('' + esc(label) + ' ' + (hint ? '
' + esc(hint) + ' ' : '') + '
'
+ Object.entries(v).map(([sk, sv]) => '' + esc(humanize(sk)) + ' ').join('') + '
');
} else html.push('' + esc(label) + '
');
}
wrap.innerHTML = html.join('');
}
function readRates() {
const out = {};
document.querySelectorAll('#ratesForm [data-rk]').forEach(el => {
const k = el.dataset.rk, kind = el.dataset.kind;
if (kind === 'numlist') out[k] = el.value.split(/[\s,]+/).filter(Boolean).map(Number).filter(n => !isNaN(n));
else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = i.dataset.str ? i.value.trim() : Number(i.value); }); return o; });
else if (kind === 'object') { const o = {}; el.querySelectorAll('input[data-sub]').forEach(i => { o[i.dataset.sub] = Number(i.value); }); out[k] = o; }
else if (el.type === 'checkbox') out[k] = !!el.checked;
else if (el.type === 'number') out[k] = Number(el.value);
else out[k] = el.value;
});
return out;
}
$('ratesSave').addEventListener('click', busy($('ratesSave'), async () => {
$('ratesErr').hidden = true;
try { const r = await api('/api/admin/rates', readRates(), 'PATCH'); ratesObj = r.rates || readRates(); drawRates(); IAP.status('Rates saved.', 'ok'); }
catch (e) { $('ratesErr').textContent = e.message; $('ratesErr').hidden = false; }
}));
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
const SITE_META = { loginAdEveryHours: 'Login ad: show again on the next member page once the last finished view is this many hours old (default 3)', noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Targets for milestones + daily snapshot: feed = main group, support = IAP support topic, echo = shared payments topic (comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramSupportChatId: 'Telegram support topic: chat id (milestones + daily snapshot)', telegramSupportTopicId: 'Telegram support topic: topic id', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
function drawSite() {
const wrap = $('siteForm');
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '' + esc(SITE_META[k] || humanize(k)) + ' '
+ (typeof v === 'boolean' ? ' '
: typeof v === 'number' ? ' '
: ' ')
+ 'Clear
').join('') || 'No settings saved yet.
';
}
function readSite() {
const out = {};
document.querySelectorAll('#siteForm [data-sk]').forEach(el => {
const k = el.dataset.sk;
if (el.type === 'checkbox') out[k] = !!el.checked;
else if (el.type === 'number') out[k] = Number(el.value);
else { const v = el.value; if (/^[\[{]/.test(v)) { try { out[k] = JSON.parse(v); return; } catch (e) {} } out[k] = v; }
});
return out;
}
$('siteForm').addEventListener('click', e => {
const b = e.target.closest('[data-sdel]'); if (!b) return;
siteObj = readSite(); siteObj[b.dataset.sdel] = ''; drawSite();
});
$('siteAddKey').addEventListener('click', () => {
const k = $('siteNewKey').value.trim(); if (!/^[A-Za-z][A-Za-z0-9_]{0,40}$/.test(k)) { IAP.status('Setting names are letters and numbers, no spaces.', 'bad'); return; }
siteObj = readSite(); if (!(k in siteObj)) siteObj[k] = ''; $('siteNewKey').value = ''; drawSite();
const el = document.querySelector('#siteForm [data-sk="' + k + '"]'); if (el) el.focus();
});
$('siteSave').addEventListener('click', busy($('siteSave'), async () => {
$('siteErr').hidden = true;
try { const r = await api('/api/admin/site', readSite(), 'PATCH'); siteObj = r.site || readSite(); drawSite(); IAP.status('Site settings saved.', 'ok'); }
catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; }
}));
// ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ----
async function loadGamePass() {
const r = await api('/api/admin/gamepass/stats');
const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2);
const tile = (v, lb, cls, sub) => '' + v + '
' + lb + '
' + (sub ? '
' + sub + ' ' : '') + '
';
const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {};
$('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only')
+ tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time')
+ tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package')
+ tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet'))
+ tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants')
+ tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total')
+ tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total')
+ tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members');
$('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : '';
const would = (r.capHits && r.capHits.would) || {};
$('gpWeek').innerHTML = ''
+ 'Carried forward (deferred progress paid on a later day) ' + pol(W.carried) + ' POL '
+ 'Dropped (daily play over the daily cap) ' + pol(W.dropped) + ' POL '
+ 'Deferred out (progress over the total cap, pays later) ' + pol(W.deferredOut) + ' POL '
+ (S.enforced ? '' : 'Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits. ')
+ 'Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day) ' + S.price + ' credits · ' + S.days + ' days '
+ '
'
+ (Q.byGame && Object.keys(Q.byGame).length ? 'By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '
' : '');
// per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month
const TS = r.tiers || {}, TC = S.tiers || {};
$('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales';
$('gpTiers').innerHTML = 'Tier Price Active Sold week Sold month All time Renewals 30d Ending in 7 days Comped Waiting '
+ (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return '' + esc(x.name || k) + (c.sale ? '' : 'not on sale ') + ' ' + (c.price || 0) + ' cr ' + (c.days || 0) + ' d ' + (x.active || 0) + ' ' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + ' ' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + ' ' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + ' ' + (x.renewals30d || 0) + ' ' + (x.expiring7d || 0) + ' ' + (x.comped || 0) + ' ' + (x.waitingOrders || 0) + ' '; }).join('')
+ '
Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).
';
// pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled)
const PM = P.pay || {}, SL = r.sales || [];
$('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')'
+ ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')';
const txLink = h => h ? '' + esc(String(h).slice(0, 10)) + '… ' : '';
$('gpSales').innerHTML = !SL.length ? 'No pass sold yet.
' : 'When Member Pass Paid by Pass Package Package tx '
+ SL.map(x => '' + when(x.ts) + ' ' + esc(x.email) + ' ' + esc(x.name || x.tier) + ' ' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + ' ' + usd(x.usd) + ' ' + (x.packageUsd ? usd(x.packageUsd) : '') + ' ' + txLink(x.tx) + ' ').join('')
+ '
';
await loadGpTest();
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
const L = T.last;
$('gpTour').innerHTML = !L ? 'No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).
'
: '' + esc(L.label) + ' : ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '
'
+ (L.winners && L.winners.length ? '' + L.winners.map(w => '#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + ' ' + w.score + ' plays ' + pol(w.pol) + ' POL ' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + ' ').join('') + '
' : 'No pass holder reported any plays that week.
')
+ ((T.history || []).length > 1 ? 'Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '
' : '');
}
// Tier test and preview (2026-10-25, Marty): the member Games card shows the admin exactly what a member sees, so every tier test lives
// here. Every action touches ONLY the signed-in admin's own account; a test buy opens the same waiting order a member gets (a fresh
// package on /my fulfils it, sponsors paid as usual), a test comp starts the tier at once with no sale recorded.
// Shards of Valor bonus heroes (2026-11-05, Marty approved): sold ONE TIME. The same test path as the tiers, on the admin's own account:
// a test buy opens the real waiting order (a fresh $20 / $50 package on /my fulfils it), Give grants it at once as comped, Remove takes it back.
function heroTestHtml(H) {
if (!H || !H.items) return '';
const row = (key, name, sub, usd, pkg, owned, waiting, free) => '' + esc(name) + ' ' + esc(sub) + '
'
+ '
' + (free ? 'Free for everyone' : '$' + usd + ' one time, the $' + pkg + ' package ') + '
'
+ '
' + (owned ? 'Your account: owned ' : waiting ? 'Your account: test order waiting for a $' + pkg + ' package ' : 'Your account: not owned') + '
'
+ (free || owned ? '' : waiting ? '
Buy the $' + pkg + ' package on /my Cancel test order ' : '
Test buy (real order, $' + pkg + ' package) ')
+ (owned || free ? '' : '
Give my account ' + esc(name.split(' ')[0]) + ' now (test) ')
+ (owned && !free && key !== 'bundle' ? '
Remove from my account ' : '') + '
';
const B = H.bundle;
return 'Shards of Valor bonus heroes ' + (H.sale ? 'on sale: members see them' : 'hidden from members (heroSales off)') + ' '
+ 'Sold one time, owned for good, paid by a fresh package like a pass (no credits). Prices, the free list and the bundle are settings: heroPrice<Name>Cents (0 = free for everyone), heroBundleHeroes, heroBundlePriceCents. heroBundleCap stays empty (the bundle is heroes only). Members see heroes only once heroSales is on.
'
+ '' + H.items.map(i => row(i.key, i.name, i.blurb, i.usd, i.package, i.owned, i.waiting, i.free)).join('')
+ (B ? row('bundle', 'Hero bundle', B.names.join(', '), B.usd, B.package, B.owned, B.waiting, false) : '') + '
';
}
function wireHeroTest(box, g) {
const nm = k => k === 'bundle' ? 'the hero bundle' : ((g.heroes.items.find(i => i.key === k) || {}).name || k);
box.querySelectorAll('[data-ht-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.htBuy; if (!(await IAP.confirmBox('Open a TEST order for ' + nm(k) + ' on your own account (' + g.email + ')? It is fulfilled when a fresh package of at least its price from one of your positions settles on chain. Members still cannot buy heroes while heroSales is off.', { title: 'Test buy: ' + nm(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
const x = await api('/api/admin/heroes/test-buy', { hero: k }); IAP.status('Test order for ' + nm(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-ht-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => { const k = b.dataset.htCancel; await api('/api/admin/heroes/test-cancel', { hero: k }); IAP.status('Test order for ' + nm(k) + ' cancelled.', 'ok'); await loadGpTest(); })));
box.querySelectorAll('[data-ht-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.htComp; if (!(await IAP.confirmBox('Give your own account ' + nm(k) + ' now, for testing? Recorded as comped (no sale); the game shows it the next time you sign in to it from /my Games.', { title: 'Test ' + nm(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
await api('/api/admin/heroes/test-comp', { hero: k }); IAP.status(nm(k) + ' is on your account (test).', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-ht-revoke]').forEach(b => b.addEventListener('click', busy(b, async () => { const k = b.dataset.htRevoke; await api('/api/admin/heroes/test-revoke', { hero: k }); IAP.status(nm(k) + ' removed from your account.', 'ok'); await loadGpTest(); })));
}
async function loadGpTest() {
const box = $('gpTest'); if (!box) return;
let g; try { g = await api('/api/admin/gamepass/preview'); } catch (e) { box.innerHTML = '' + esc(e.message) + '
'; return; }
const ct = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
const len = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
const rows = g.passes || [];
$('gpTestSub').textContent = 'TEST / PREVIEW · admin only · acts on your own account: ' + g.email;
const card = r => {
const sale = r.tier === 'weekly' ? !!g.enabled : !!r.sale;
const st = r.active ? 'Your account: active until ' + esc(ct(r.until)) + ' ' : r.waiting ? 'Your account: test order waiting for a $' + r.package + ' package ' : 'Your account: not active';
const acts = (r.waiting ? 'Buy the $' + r.package + ' package on /my Cancel test order '
: 'Test buy (real order, $' + r.package + ' package) ')
+ 'Give my account ' + esc(r.name) + ' now (test) '
+ (r.active ? 'End my ' + esc(r.name) + ' now ' : '');
return '' + esc(r.name) + ' ' + (sale ? 'on sale: members see it' : 'hidden from members') + ' '
+ '
$' + r.usd + ' for ' + len(r.days) + '
'
+ '
' + (r.perks || []).map(x => '' + esc(x) + ' ').join('') + ' '
+ '
' + st + '
' + acts + '
';
};
box.innerHTML = 'Test / preview, admin only. ' + (g.tierPreview ? 'The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings (it stays off until the paid tiers launch). ' : '')
+ 'These are the tier cards as members will see them. Every button here acts on your own account (' + esc(g.email) + ') and nobody else’s. The member Games card on /my shows you exactly what a member sees: while you hold a test tier it shows that tier the way it would for any member who holds one.
'
+ '' + rows.map(card).join('') + '
'
+ 'Test buy opens the same waiting order a member gets: a fresh package of at least the price, bought on /my by one of your positions, starts it (sponsors paid as usual). Cancel a test order you will not pay, or a later real package of that size fulfils it. Give my account starts one pass period at once, recorded as comped (no sale); End stops it. '
+ 'To test it in game, open Shards of Valor > Passes (key P) after signing in to the game again from /my Games: the game reads your highest tier from InstantAdPay at sign-in.
'
+ heroTestHtml(g.heroes);
const tierName = k => (rows.find(r => r.tier === k) || {}).name || k;
wireHeroTest(box, g);
box.querySelectorAll('[data-gpt-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptBuy; const r = rows.find(x => x.tier === k);
if (!(await IAP.confirmBox('Open a TEST order for ' + tierName(k) + ' on your own account (' + g.email + ')? It starts when a fresh $' + r.package + ' or bigger package from one of your positions settles on chain. Members still cannot see or buy this tier.', { title: 'Test buy: ' + tierName(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
const x = await api('/api/admin/gamepass/test-buy', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-gpt-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptCancel; await api('/api/admin/gamepass/test-cancel', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' cancelled.', 'ok'); await loadGpTest();
})));
box.querySelectorAll('[data-gpt-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptComp;
if (!(await IAP.confirmBox('Give your own account (' + g.email + ') one ' + tierName(k) + ' period now, for testing? It is recorded as comped (no sale) and shows in the game the next time you sign in to it.', { title: 'Test ' + tierName(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
const x = await api('/api/admin/gamepass/test-comp', { tier: k }); IAP.status(tierName(k) + ' on your account until ' + when(x.until) + ' (test).', 'ok'); await loadGamePass();
})));
box.querySelectorAll('[data-gpt-end]').forEach(b => b.addEventListener('click', busy(b, async () => {
const k = b.dataset.gptEnd;
if (!(await IAP.confirmBox('End ' + tierName(k) + ' on your own account now?', { title: 'End test tier', ok: 'End it now', cancel: 'Keep it' }))) return;
await api('/api/admin/gamepass/revoke', { email: g.email, tier: k, why: 'admin tier test' }); IAP.status(tierName(k) + ' on your account ended.', 'ok'); await loadGamePass();
})));
}
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
$('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => {
const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; }
if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return;
const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass();
}));
async function loadSettings() {
const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]);
ratesObj = r.rates || {}; drawRates();
siteObj = s.site || {}; drawSite();
dripSeq = d.sequence || []; drawDrip();
const st = d.stats || {};
$('dripSub').textContent = (st.active || 0) + ' in flight · ' + (st.done || 0) + ' finished · ' + (st.unsubscribed || 0) + ' unsubscribed' + (d.mailReady ? '' : ' · NO MAIL KEY: nothing sends');
}
render();
})();
// ---- tax summary (2026-10-04) + the cost category picker
(function () {
const $ = id => document.getElementById(id);
if ($('ldKind') && $('ldCat')) { const sync = () => { $('ldCat').hidden = $('ldKind').value !== 'cost'; }; $('ldKind').addEventListener('change', sync); sync(); }
if (!$('taxYear')) return;
const y = new Date().getFullYear(); for (let v = y; v >= 2025; v--) { const o = document.createElement('option'); o.value = v; o.textContent = v; $('taxYear').appendChild(o); }
const money = n => '$' + Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
$('taxRun').addEventListener('click', async () => {
$('taxOut').textContent = 'Working it out...';
try {
const r = await (await fetch('/api/admin/tax?year=' + $('taxYear').value, { credentials: 'same-origin' })).json();
if (r.error) throw new Error(r.error);
const cats = Object.entries(r.expenses.byCategory || {}).map(([k, v]) => '' + (r.expenses.labels[k] || k) + ' ' + money(v) + ' ').join('');
$('taxOut').innerHTML = '' + r.year + ' '
+ 'Income : platform share of ' + r.income.sales + ' package sales' + money(r.income.platformUsd) + ' '
+ (r.income.outsideUsd ? 'Outside revenue ' + money(r.income.outsideUsd) + ' ' : '')
+ 'Total income ' + money(r.income.totalUsd) + ' '
+ (cats || 'No costs recorded yet ')
+ 'Advertising and promotion (advertising + game marketing + player rewards)' + money(r.expenses.advertisingAndPromotionUsd) + ' '
+ 'Total costs ' + money(r.expenses.totalUsd) + ' '
+ 'Net ' + money(r.netUsd) + '
'
+ 'Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).
';
$('taxCsvText').value = r.csv; $('taxCsv').hidden = false;
} catch (e) { $('taxOut').textContent = 'Could not build the summary: ' + e.message; }
});
$('taxCsv').addEventListener('click', async () => {
try { await navigator.clipboard.writeText($('taxCsvText').value); IAP.status('CSV copied. Paste it into a spreadsheet.', 'good'); }
catch (e) { $('taxCsvText').hidden = false; $('taxCsvText').select(); IAP.status('Selected. Copy it with your keyboard.', 'good'); }
});
})();