Files
linkspin/public/assets/cr-shell.js
T
martbost 211eb5a0e8 Traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension
A Source is a first-class record of a network a member buys traffic on (PropellerAds,
Zeropark, Adsterra, ExoClick and 25 more from the shipped catalog, or defined by hand).
It remembers the network's macro tokens and conversion postback, attaches to spin links,
builds the exact campaign URL to paste into the network, fires that network's own
postback only for clicks that came through it, and shows up in Reports by source and
by the zone / placement / site the macro carried.

- data/traffic-sources.json: catalog of 29 networks (BeMob template harvest), un-ignored
  via data/* + !data/traffic-sources.json; loader tolerates missing fields, null costModel,
  {{slot}} labels with spaces and parentheses, optional slots, unknown single-brace macros
- sources.js: DATA_DIR/sources.json model, 30 per account, 20 params, key allow-list,
  postbacks.validateUrl on the filled postback; list/create/update/get/urlFor/test
- rotator.js: update() takes sourceId (owner-checked), pub() exposes it, hits and conversions
  are stamped with the source at click time (sr), wider query allow-list (cost, creative,
  site, banner, keyword, geo, os, browser, device, carrier, format, external_id, visitor_id),
  summary() adds sources[] and placements[], sourceCounts(), detachSource()
- postbacks.js: fire() delivers the matching source's postback after the manual ones through
  the same deliver() (guards, retry, rate cap, auto-disable); log rows carry source; convertFor,
  inbound and the page lead path pass sourceId; fill/deliver/logForSource exported
- routes (GET and POST): /api/sources/catalog, /api/my/sources, /api/my/sources/<id>,
  /api/my/sources/<id>/url; /sources screen
- /sources Control Room screen (list + Campaign URL / Postback / Settings tabs, two-step
  New source dialog); Links share kit gets a source select and a "Campaign URL for <network>"
  first row; Reports gets Traffic sources and Placements; rail entry; chatbot canned answer,
  FACTS line and KNOWLEDGE_DATE 2026-10-12
- cr.css: phone rail icons only at 34px so ten entries fit; cache tags bumped to 20261012a

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 11:16:24 -05:00

159 lines
18 KiB
JavaScript

// LinkSpin Control Room shell (2026-09-29): the frame every workspace screen shares.
// Rail + topbar, session check, in-shell sign-in (email code, same endpoints as the dashboard),
// fetch helper, toast, in-page dialogs (never native prompt/confirm). Pages: put content in
// <div id="page">, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
window.CR = (function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const fmt = n => Number(n || 0).toLocaleString();
const NAV = [
['links', 'Links', '/links', '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>'],
['sources', 'Sources', '/sources', '<path d="M3 5h18l-7 8v6l-4-2v-4z"/>'],
['pages', 'Pages', '/pages', '<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M8 9h8M8 13h6"/>'],
['zones', 'Zones', '/zones', '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/>'],
['ads', 'Ads', '/ads', '<path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8"/>'],
['credits', 'Credits', '/credits', '<circle cx="12" cy="12" r="8"/><path d="M12 8v8M9.5 10.5h3.5a1.5 1.5 0 0 1 0 3H10a1.5 1.5 0 0 0 0 3h4.5"/>'],
['reports', 'Reports', '/reports', '<path d="M4 19V9M10 19V5M16 19v-8M22 19H2"/>'],
['team', 'Team', '/team', '<circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.5"/><path d="M3 19c0-3 3-5 6-5s6 2 6 5M15 15c3 0 6 1.5 6 4"/>'],
['wallet', 'Wallet', '/wallet', '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M16 12h3"/>'],
['promo', 'Promo tools', '/tools#promo', '<path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/>'],
['training', 'Training', '/tools#training', '<rect x="3" y="5" width="18" height="13" rx="2"/><path d="M10 9l5 2.5-5 2.5z"/>', 1],
['pipeline', 'Pipeline', '/tools#pipeline', '<rect x="3" y="5" width="5" height="14" rx="1"/><rect x="9.5" y="5" width="5" height="10" rx="1"/><rect x="16" y="5" width="5" height="7" rx="1"/>', 1],
['profile', 'Profile', '/tools#profile', '<circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-4 3-6 7-6s7 2 7 6"/>', 1],
['tools', 'More', '/tools', '<circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/>'],
];
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
const FALLBACK = {}; // the classic /my dashboard is retired (2026-10-08); its leftover panes live at /tools
const BUILT = new Set(['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'reports', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11)
let ME = null, toastT;
function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.classList.toggle('bad', !!bad); t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); }
async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; }
async function get(path) { const r = await (await fetch(path, { headers: { Accept: 'application/json' } })).json(); if (r.error) throw new Error(r.error); return r; }
function copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } }
function dialog(opts) {
return new Promise(resolve => {
let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); }
host.innerHTML = '';
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '<div class="modal" role="dialog" aria-modal="true"><h2>' + esc(opts.title) + '</h2>' + (opts.text ? '<div class="ink2">' + esc(opts.text) + '</div>' : '') + (opts.html || '')
+ (opts.fields || []).map(f => '<label class="lbl">' + esc(f.label) + (f.type === 'textarea' ? '<textarea class="field' + (f.mono ? ' mono' : '') + '" id="dlg-' + f.k + '" rows="' + (f.rows || 3) + '" placeholder="' + esc(f.placeholder || '') + '">' + esc(f.value || '') + '</textarea>' : '<input class="field' + (f.mono ? ' mono' : '') + '" id="dlg-' + f.k + '" type="' + (f.type || 'text') + '" value="' + esc(f.value || '') + '" placeholder="' + esc(f.placeholder || '') + '"' + (f.max ? ' maxlength="' + f.max + '"' : '') + '>') + '</label>').join('')
+ '<div class="acts"><button class="btn" type="button" id="dlgNo">' + esc(opts.no || 'Cancel') + '</button><button class="btn pri' + (opts.danger ? ' danger' : '') + '" type="button" id="dlgOk">' + esc(opts.ok || 'OK') + '</button></div></div>';
host.appendChild(back);
const done = v => { host.innerHTML = ''; resolve(v); };
back.querySelector('#dlgNo').addEventListener('click', () => done(null));
back.addEventListener('click', e => { if (e.target === back) done(null); });
back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); });
const first = back.querySelector('input,textarea'); if (first) { first.focus(); if (first.select) first.select(); }
back.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); });
});
}
function mount(o) {
const page = $('page'); if (!page) return;
const app = document.createElement('div'); app.className = 'app'; let railWide = true; try { railWide = localStorage.getItem('cr.rail') !== 'narrow'; } catch (e) {} if (railWide) app.classList.add('wide'); // expanded by default (Marty 2026-10-08), the choice remembered per browser
app.innerHTML = '<nav class="rail" aria-label="LinkSpin"><a class="mark" href="/" aria-label="LinkSpin home" title="LinkSpin"></a>'
+ NAV.map(([k, label, href, svg, sec]) => '<a href="' + (BUILT.has(k) ? href : FALLBACK[k]) + '"' + (k === o.active ? ' class="on' + (sec ? ' rsec' : '') + '" aria-current="page"' : (sec ? ' class="rsec"' : '')) + ' title="' + label + '" aria-label="' + label + '"><svg viewBox="0 0 24 24">' + svg + '</svg><span class="lbl">' + label + '</span></a>').join('')
+ '<span class="sp"></span><button class="railtog" type="button" id="crRailTog" title="Collapse or expand the menu" aria-label="Collapse or expand the menu"><svg viewBox="0 0 24 24"><path d="M15 6l-6 6 6 6"/></svg><span class="lbl">Collapse</span></button></nav>'
+ '<div class="main"><div class="topbar"><div><div class="crumb">' + esc(o.crumb || 'Control room') + '</div><h1>' + esc(o.title || '') + '</h1></div><span class="readout" id="crSub">' + esc(o.sub || '') + '</span><span class="grow"></span><span id="crActions">' + (o.actions || '') + '</span><button class="who" type="button" id="crUserBtn" title="Account"><i id="crAv"></i><span id="crWho">Sign in</span></button></div><div id="crBody"></div>'
+ '<div class="strip" id="crStrip"><span><span class="dot off" id="stDot"></span>rotator <b id="stHealth">checking</b></span><span>served today <b id="stServed">·</b></span><span>zones live <b id="stZones">·</b></span><span>network <b id="stNet">·</b></span><span class="grow"></span><span id="stClock"></span></div></div>';
page.parentNode.insertBefore(app, page); app.querySelector('#crBody').appendChild(page);
$('crRailTog').addEventListener('click', () => { const wide = !app.classList.contains('wide'); app.classList.toggle('wide', wide); try { localStorage.setItem('cr.rail', wide ? 'wide' : 'narrow'); } catch (e) {} });
$('crUserBtn').addEventListener('click', async e => { e.preventDefault(); if (!ME || !ME.signedIn) return signInFlow(() => location.reload()); const v = await dialog({ title: ME.username ? '@' + ME.username : (ME.email || 'Account'), text: 'Signed in on LinkSpin. Your classic dashboard is still at /my.', ok: 'Sign out', no: 'Close', danger: true }); if (v) { try { await api('/api/auth/logout'); } catch (er) {} location.reload(); } });
clock(); setInterval(clock, 30000);
}
// status strip: the clock ticks locally (Central); the readouts come from /api/my/strip once the member is known
function clock() { const c = $('stClock'); if (!c) return; try { c.textContent = new Date().toLocaleTimeString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit' }) + ' CT'; } catch (e) { c.textContent = ''; } }
async function strip() {
try { const s = await get('/api/my/strip'); $('stDot').className = 'dot' + (s.ok ? '' : ' off'); $('stHealth').textContent = s.ok ? 'healthy' : 'degraded'; $('stServed').textContent = fmt(s.served); $('stZones').textContent = fmt(s.zones); $('stNet').textContent = s.network ? 'on' : 'off'; }
catch (e) { $('stHealth').textContent = 'offline'; }
}
function whoPaint(m) { const w = $('crWho'), a = $('crAv'); if (!w) return; if (m && m.signedIn) { const name = m.username ? '@' + m.username : (m.email || '').split('@')[0]; w.textContent = name; a.textContent = (m.username || m.email || '?').replace(/^@/, '').slice(0, 2).toUpperCase(); } else { w.textContent = 'Sign in'; a.textContent = ''; } }
const sub = t => { const s = $('crSub'); if (s) s.textContent = t; };
async function me(force) { if (ME && !force) return ME; try { ME = await (await fetch('/api/me', { headers: { Accept: 'application/json' } })).json(); } catch (e) { ME = { signedIn: false }; } return ME; }
// sign-in inside the shell: email -> six-digit code, on the same endpoints and guards as the dashboard.
const FTS = Date.now();
async function signInFlow(onReady) {
let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); }
host.innerHTML = '<div class="modal-back"><div class="modal" role="dialog" aria-modal="true"><h2>Sign in</h2><div class="ink2">Email first. We send a six-digit code; no password to remember. New here? The same box creates your account.</div>'
+ '<label class="lbl">Email<input class="field" id="siEmail" type="email" autocomplete="email" placeholder="you@example.com"></label>'
+ '<div id="siCodeRow" hidden><label class="lbl">Code from the email<input class="field mono" id="siCode" inputmode="numeric" maxlength="6" placeholder="123456"></label></div>'
+ '<div class="muted" id="siMsg"></div><div class="acts"><a class="btn" href="/tools">More tools</a><button class="btn pri" type="button" id="siGo">Send code</button></div></div></div>';
const email = $('siEmail'), code = $('siCode'), go = $('siGo'), msg = $('siMsg'); let stage = 'email';
email.focus();
const say = (t, bad) => { msg.textContent = t; msg.className = bad ? 'bad' : 'muted'; };
async function step() {
try {
if (stage === 'email') {
const e = email.value.trim(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return say('That email address does not look right.', true);
go.disabled = true; say('Sending…');
// the sign-up guard refuses a form younger than a few seconds (bot defence); wait it out instead of bouncing the person
const wait = FTS + 4500 - Date.now(); if (wait > 0) await new Promise(r => setTimeout(r, wait));
const r = await api('/api/auth/email/start', { email: e, fts: FTS, hp_field_x9: '', pick: null });
go.disabled = false;
if (r.challenge) { say('One more check is needed for this address. Use the classic dashboard sign-in this once.', true); return; }
$('siCodeRow').hidden = false; code.focus(); stage = 'code'; go.textContent = 'Sign in';
if (r.devCode) code.value = r.devCode;
say(r.sent ? 'Code sent. Check your inbox, and spam the first time.' : 'Code filled in (local dev).');
} else {
go.disabled = true; say('Checking…');
await api('/api/auth/email/verify', { email: email.value.trim(), code: code.value.trim() });
host.innerHTML = ''; ME = null; await me(true); toast('You are in'); onReady && onReady(ME);
}
} catch (e) { go.disabled = false; say(e.message, true); }
}
go.addEventListener('click', step);
host.querySelector('.modal').addEventListener('keydown', e => { if (e.key === 'Enter') step(); });
}
async function loginAd() {
let seen = false; try { seen = !!sessionStorage.getItem('ls.la'); } catch (e) {}
if (seen) return; try { sessionStorage.setItem('ls.la', '1'); } catch (e) {}
let ad = null; try { ad = (await get('/api/ads/slot?type=login')).ad; } catch (e) { return; }
if (!ad || !ad.targetUrl) return;
await new Promise(done => {
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '<div class="modal" style="max-width:520px"><div class="muted" style="font:600 11px Manrope,system-ui;letter-spacing:.08em;text-transform:uppercase">Today\'s login sponsor</div>'
+ '<div style="margin:12px 0;text-align:center">' + (ad.imageUrl ? '<img src="' + esc(ad.imageUrl) + '" alt="" style="max-width:100%;height:auto;border:1px solid var(--line)">' : '<div class="panel" style="padding:22px"><b style="font-size:16px">' + esc(ad.title || 'Visit today\'s sponsor') + '</b></div>') + '</div>'
+ '<div class="muted" id="laStatus">Open the ad in a new tab. The timer runs here.</div>'
+ '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px;align-items:center"><button class="btn pri" type="button" id="laOpen">Open ad</button><span class="mono" id="laTimer" hidden></span><button class="btn" type="button" id="laGo" hidden>Continue</button></div></div>';
document.body.appendChild(back);
back.querySelector('#laOpen').addEventListener('click', () => {
window.open(ad.targetUrl, '_blank'); back.querySelector('#laOpen').disabled = true;
let left = ad.dwell || 10; const t = back.querySelector('#laTimer'); t.hidden = false; t.textContent = left + ' s';
const iv = setInterval(() => { left -= 1; if (left > 0) { t.textContent = left + ' s'; return; } clearInterval(iv); t.textContent = 'done'; back.querySelector('#laStatus').textContent = 'Thanks for the look.'; back.querySelector('#laGo').hidden = false; }, 1000);
});
back.querySelector('#laGo').addEventListener('click', () => { back.remove(); done(); });
});
}
// first run: a member needs a username before anything else (it becomes the invite link; permanent once set)
async function ensureUsername(m) {
if (!m || !m.signedIn || m.username) return m;
let suggest = ''; try { suggest = (await get('/api/my/username-suggest')).suggest || ''; } catch (e) {}
for (let i = 0; i < 3; i++) {
const v = await dialog({ title: 'Pick your username', text: 'This is how your team sees you and it becomes your invite link. It is permanent once saved. Letters, numbers and underscores, 3 to 20 characters.', fields: [{ k: 'username', label: 'Username', value: suggest, placeholder: 'yourname' }], ok: 'Save and continue', no: 'Later' });
if (!v) return m;
try { await api('/api/my/profile', { username: String(v.username || '').trim() }); const fresh = await me(true); whoPaint(fresh); toast('Saved. Your invite link is /join/' + fresh.username); return fresh; }
catch (e) { toast(e.message, true); suggest = String(v.username || ''); }
}
return m;
}
async function requireSession(onReady) { let m = await me(); whoPaint(m); if (m && m.signedIn) { strip(); m = await ensureUsername(m); await loginAd(); return onReady(m); } signInFlow(async r => { whoPaint(r); strip(); await loginAd(); onReady(r); }); }
// tiles with a sparkline and a delta chip (Instrument scheme, 2026-09-29): series = numbers oldest first
function sparkline(series) {
const s = (series || []).map(Number); if (s.length < 2 || !s.some(Boolean)) return '';
const W = 74, H = 26, max = Math.max(...s), min = Math.min(...s);
const pts = s.map((v, i) => [(i / (s.length - 1)) * W, H - 2 - ((v - min) / ((max - min) || 1)) * (H - 4)]);
const line = pts.map(p => p[0].toFixed(1) + ',' + p[1].toFixed(1)).join(' ');
return '<svg class="sparkline" viewBox="0 0 74 26" aria-hidden="true"><polygon class="fill" points="0,26 ' + line + ' 74,26"/><polyline points="' + line + '"/></svg>';
}
function delta(now, before, label) {
now = Number(now) || 0; before = Number(before) || 0; if (!before && !now) return null;
if (!before) return { text: 'new' + (label ? ' ' + label : ''), cls: 'flat' };
const pct = Math.round((now - before) / before * 100);
return { text: (pct > 0 ? '+' : '') + pct + '%' + (label ? ' ' + label : ''), cls: pct > 0 ? '' : pct < 0 ? 'down' : 'flat' };
}
function tile(o) {
return '<div class="tile' + (o.hi ? ' hi' : '') + '"><span class="k">' + esc(o.k) + '</span><div class="row"><span class="v">' + o.v + (o.unit ? '<small>' + esc(o.unit) + '</small>' : '') + '</span>' + sparkline(o.series) + '</div>'
+ (o.delta ? '<span class="delta' + (o.delta.cls ? ' ' + o.delta.cls : '') + '">' + esc(o.delta.text) + '</span>' : '') + (o.note ? '<span class="muted mono" style="font-size:11px">' + esc(o.note) + '</span>' : '') + '</div>';
}
return { esc, fmt, api, get, copy, dialog, toast, mount, sub, me, requireSession, signInFlow, tile, sparkline, delta };
})();