Files
linkspin/public/assets/sources-screen.js
T

147 lines
20 KiB
JavaScript

// LinkSpin Traffic sources screen (Control Room, 2026-10-12): the networks a member buys traffic on.
// Left: the member's sources with 30-day clicks and conversions. Right: Campaign URL (the exact URL to paste
// into the network, macros included), Postback (the network's own conversion URL, test, log), Settings.
// New source = pick a network from the catalog (or Custom), then a short form with one input per {{slot}}.
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let S = [], CAT = [], ROT = [], SEL = null, DET = null, FILTER = '', KEYS = [], EVENTS = ['join', 'lead', 'wallet', 'purchase', 'external'], LIMITS = {}, URL_ROT = null, PE = [];
CR.mount({ active: 'sources', title: 'Traffic sources', sub: 'loading', actions: '<a class="btn sm" href="/traffic-guide" title="Which traffic works for which kind of offer">Traffic guide</a> <button class="btn pri" type="button" id="newBtn">+ New source</button>' });
// traffic guide (2026-10-28): formats each network sells, adult-heavy / strict-policy flags, what it suits best
const TG = window.TRAFFIC_GUIDE || null;
const gTags = key => { const n = TG && TG.NETWORKS[key]; if (!n) return ''; return n.f.map(f => '<span class="tag plain">' + esc(TG.fmtName(f)) + '</span>').join('') + (n.adult === 'adult' ? '<span class="tag warn">adult sites</span>' : n.adult === 'mixed' ? '<span class="tag dim" title="Big adult inventory; target its mainstream sites">adult-heavy</span>' : '') + (n.strict ? '<span class="tag warn" title="Strict ad policy: crypto, income claims and MLM are restricted or need approval">strict policy</span>' : ''); };
const gText = key => { const n = TG && TG.NETWORKS[key]; return n ? n.f.map(f => (TG.FORMATS[f] || {}).name || f).join(' ') : ''; };
const ago = ts => { if (!ts) return 'never'; const s = Math.max(0, Math.round((Date.now() - ts) / 1000)); return s < 60 ? 'just now' : s < 3600 ? Math.round(s / 60) + ' min ago' : s < 86400 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' d ago'; };
const netOf = s => CAT.find(c => c.key === s.template) || null;
const netName = s => { const n = netOf(s); return n ? n.name : (s.template === 'custom' ? 'Custom' : s.template); };
const EV_LABEL = { join: 'Join', lead: 'Lead', wallet: 'Wallet', purchase: 'Purchase', external: 'Partner-reported', goal: 'Any goal (pixel)' };
async function load(keep) {
let r; try { r = await CR.get('/api/my/sources'); } catch (e) { CR.sub('could not load'); return; }
S = (r.sources || []).slice().sort((a, b) => (b.hits30 || 0) - (a.hits30 || 0)); KEYS = r.keys || KEYS; EVENTS = r.events || EVENTS; LIMITS = r.limits || {};
if (!CAT.length) { try { CAT = (await CR.get('/api/sources/catalog')).catalog || []; } catch (e) { CAT = []; } }
if (!ROT.length) { try { ROT = (await CR.get('/api/my/rotations')).rotations || []; } catch (e) { ROT = []; } }
const tot = S.reduce((n, x) => n + (x.hits30 || 0), 0), conv = S.reduce((n, x) => n + (x.conv30 || 0), 0);
CR.sub(S.length + ' source' + (S.length === 1 ? '' : 's') + ' · ' + fmt(tot) + ' clicks · ' + fmt(conv) + ' conversions in 30 days');
renderList();
const want = SEL != null ? SEL : (location.hash.slice(1) || null);
if (want && S.find(x => x.id === want)) return select(want, true);
if (!S.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; return; }
select(S[0].id, true);
}
function renderList() {
const q = FILTER.trim().toLowerCase();
const rows = S.filter(x => !q || x.name.toLowerCase().includes(q) || netName(x).toLowerCase().includes(q) || (x.site || '').toLowerCase().includes(q));
$('listCount').textContent = S.length + ' source' + (S.length === 1 ? '' : 's');
$('items').innerHTML = rows.length ? rows.map(x => '<div class="item' + (x.id === SEL ? ' on' : '') + '" data-id="' + x.id + '" role="button" tabindex="0">'
+ '<div><div class="nm">' + esc(x.name) + (x.enabled ? '' : ' <span class="tag warn">OFF</span>') + (x.conv30 ? ' <span class="tag ok">' + fmt(x.conv30) + ' conv</span>' : '') + '</div><div class="cd">' + esc(netName(x)) + (x.site ? ' · ' + esc(x.site) : '') + (x.links ? ' · ' + x.links + ' link' + (x.links === 1 ? '' : 's') : '') + '</div></div>'
+ '<div class="rt"><span class="n">' + fmt(x.hits30 || 0) + '</span><span class="muted" style="font-size:10px">clicks 30 d</span></div></div>').join('')
: '<div class="empty"><div class="muted">' + (S.length ? 'No source matches that filter.' : 'No sources yet.') + '</div></div>';
$('items').querySelectorAll('.item').forEach(el => { const go = () => select(el.dataset.id); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
}
async function select(id, quiet) {
SEL = id; const s = S.find(x => x.id === id); if (!s) return;
if (location.hash.slice(1) !== id) history.replaceState(null, '', '#' + id);
$('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus');
$('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', el.dataset.id === id));
$('dName').textContent = s.name; $('dNet').textContent = netName(s) + (s.site ? ' · ' + s.site : '') + (s.costModel ? ' · ' + s.costModel : '');
$('dOn').innerHTML = s.enabled ? '<span class="ok"><span class="dot"></span>ON</span>' : '<span class="warn"><span class="dot"></span>OFF' + (s.fails >= 10 ? ' (postback failed 10 times)' : '') + '</span>';
$('togBtn').textContent = s.enabled ? 'Disable' : 'Enable';
$('tiles').innerHTML = [CR.tile({ k: 'Clicks, 30 d', v: fmt(s.hits30 || 0), hi: true }), CR.tile({ k: 'Unique, 30 d', v: fmt(s.unique30 || 0) }), CR.tile({ k: 'Conversions, 30 d', v: fmt(s.conv30 || 0) }), CR.tile({ k: 'Postbacks sent', v: fmt(s.sent || 0), note: s.lastAt ? 'last ' + ago(s.lastAt) + ' · ' + s.lastStatus : 'none yet' }), CR.tile({ k: 'Links using it', v: fmt(s.links || 0) })].join('');
const gb = TG && TG.NETWORKS[s.template], bf = gb ? TG.bestFor(s.template) : [];
$('dGuide').hidden = !gb;
if (gb) $('dGuide').innerHTML = (gb.f.length ? '<span>Sells</span>' + gTags(s.template) : gTags(s.template)) + (bf.length ? '<span>· Best for: <b>' + esc(bf.join(', ')) + '</b></span>' : (gb.note ? '<span>' + esc(gb.note) + '</span>' : '')) + '<span class="grow"></span><a href="/traffic-guide">Which traffic for which offer &rarr;</a>';
renderUrl(s); renderPb(s, null); renderSettings(s);
if (!quiet) window.scrollTo({ top: 0 });
try { DET = await CR.get('/api/my/sources/' + id); } catch (e) { DET = null; }
if (SEL === id && DET) renderPb(DET.source, DET.log || []);
}
// -- Campaign URL
function renderUrl(s) {
const sel = $('urlRot');
sel.innerHTML = ROT.length ? ROT.map(r => '<option value="' + r.id + '"' + (r.sourceId === s.id ? ' data-att="1"' : '') + '>' + esc(r.name) + (r.sourceId === s.id ? ' (uses this source)' : '') + '</option>').join('') : '<option value="">No links yet</option>';
const att = ROT.find(r => r.sourceId === s.id); const pick = (URL_ROT && ROT.find(r => r.id === URL_ROT)) ? URL_ROT : (att ? att.id : (ROT[0] ? ROT[0].id : null));
if (pick != null) sel.value = String(pick);
$('prmRows').innerHTML = (s.params || []).length ? s.params.map(p => '<div class="rw"><span class="mono">' + esc(p.key) + '</span><span class="mono" style="overflow-wrap:anywhere">' + esc(p.token) + '</span><span class="muted">' + esc(p.label || (p.role === 'externalId' ? 'click id' : p.role === 'cost' ? 'cost of the click' : '')) + '</span></div>').join('') : '<div class="rw"><span class="muted">No params. Add the network\'s macros under Settings.</span></div>';
buildUrl(s);
}
async function buildUrl(s) {
const rid = $('urlRot').value; const r = ROT.find(x => String(x.id) === String(rid));
if (!r) { $('urlOut').textContent = 'Make a link first, then come back for its campaign URL.'; $('urlNote').innerHTML = '<a href="/links">Open Links</a>'; return; }
URL_ROT = r.id;
try { const out = await api('/api/my/sources/' + s.id + '/url', { rotationId: r.id }); $('urlOut').textContent = out.url; }
catch (e) { $('urlOut').textContent = e.message; }
const attached = r.sourceId === s.id;
$('urlNote').innerHTML = 'Paste this as the destination URL in ' + esc(netName(s) === 'Custom' ? (s.site || s.name) : netName(s)) + '. ' + (attached ? 'This link is pointed at this source, so its conversions reach the network\'s postback.' : 'This link is not pointed at this source yet: <button class="btn sm" type="button" id="urlAttach">Point it here</button> so its conversions reach the network\'s postback.');
const b = $('urlAttach'); if (b) b.addEventListener('click', async () => { try { await api('/api/my/rotations/' + r.id, { sourceId: s.id }); r.sourceId = s.id; toast('Link now uses ' + s.name); ROT = []; await load(true); } catch (e) { toast(e.message, true); } });
}
$('urlRot').addEventListener('change', () => { const s = S.find(x => x.id === SEL); if (s) buildUrl(s); });
$('urlCopy').addEventListener('click', () => { const t = $('urlOut').textContent; if (/^https?:/.test(t)) CR.copy(t); });
// -- Postback
function renderPb(s, log) {
$('pbUrl').textContent = s.postbackUrl || 'No postback URL yet. Add the network\'s conversion URL under Settings; until then this source still tags your campaign URL and shows up in Reports.';
$('pbEvents').innerHTML = EVENTS.map(e => '<button type="button" class="chip' + ((s.events || []).includes(e) ? ' on' : '') + '" data-ev="' + e + '">' + esc(EV_LABEL[e] || e) + '</button>').join('');
$('pbEvents').querySelectorAll('[data-ev]').forEach(b => b.addEventListener('click', async () => { const ev = (s.events || []).slice(); const i = ev.indexOf(b.dataset.ev); if (i >= 0) ev.splice(i, 1); else ev.push(b.dataset.ev); if (!ev.length) return toast('Keep at least one event', true); try { await api('/api/my/sources/' + s.id, { events: ev }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } }));
$('pbTest').disabled = !s.postbackUrl;
$('pbStatus').textContent = s.lastAt ? 'last delivery ' + ago(s.lastAt) + ': ' + s.lastStatus + ' · ' + fmt(s.sent || 0) + ' sent' + (s.fails ? ' · ' + s.fails + ' failing in a row' : '') : (s.postbackUrl ? 'nothing sent yet' : '');
if (log == null) { $('logRows').innerHTML = '<div class="rw"><span class="muted">loading</span></div>'; return; }
$('logRows').innerHTML = log.length ? log.map(l => '<div class="rw"><span class="mono muted" style="font-size:11px">' + new Date(l.ts).toLocaleString() + '</span><span>' + esc(l.event) + (l.test ? ' <span class="tag dim">test</span>' : '') + '</span><span class="mono" style="font-size:11px;overflow-wrap:anywhere">' + esc(l.url) + '</span><span class="' + (l.ok ? 'ok' : 'bad') + '">' + (l.ok ? 'ok ' + l.status : 'failed ' + (l.status || esc(l.note || ''))) + '</span><span class="r num">' + fmt(l.ms) + '</span></div>').join('') : '<div class="rw"><span class="muted">No deliveries yet. Send a test, or wait for the first conversion from this source.</span></div>';
}
$('pbTest').addEventListener('click', async () => { const s = S.find(x => x.id === SEL); if (!s) return; const b = $('pbTest'); b.disabled = true; try { const r = await api('/api/my/sources/' + s.id, { test: true }); toast(r.ok ? 'Test delivered, HTTP ' + r.status : 'Test failed: ' + (r.status || r.note), !r.ok); } catch (e) { toast(e.message, true); } b.disabled = false; await load(true); });
// -- Settings (params editor rows live in PE until Save)
function renderSettings(s) {
$('sName').value = s.name; $('sSite').value = s.site || ''; $('sCost').value = s.costModel || ''; $('sMethod').value = s.method || 'GET'; $('sPb').value = s.postbackUrl || '';
PE = (s.params || []).map(p => ({ key: p.key, token: p.token, label: p.label || '' }));
renderPe();
}
function renderPe() {
$('peRows').innerHTML = PE.length ? PE.map((p, i) => '<div class="rw"><select class="field" data-k="' + i + '">' + KEYS.map(k => '<option value="' + k + '"' + (k === p.key ? ' selected' : '') + '>' + k + '</option>').join('') + '</select><input class="field mono" data-t="' + i + '" value="' + esc(p.token) + '" placeholder="{click_id}" maxlength="60" aria-label="Macro token"><input class="field" data-l="' + i + '" value="' + esc(p.label) + '" placeholder="Label" maxlength="40" aria-label="Label"><button class="btn sm danger" type="button" data-x="' + i + '" aria-label="Remove">&times;</button></div>').join('')
: '<div class="rw"><span class="muted">No params yet. Add clickid with the network\'s click id macro first.</span></div>';
$('peRows').querySelectorAll('[data-k]').forEach(el => el.addEventListener('change', () => { PE[el.dataset.k].key = el.value; }));
$('peRows').querySelectorAll('[data-t]').forEach(el => el.addEventListener('input', () => { PE[el.dataset.t].token = el.value; }));
$('peRows').querySelectorAll('[data-l]').forEach(el => el.addEventListener('input', () => { PE[el.dataset.l].label = el.value; }));
$('peRows').querySelectorAll('[data-x]').forEach(el => el.addEventListener('click', () => { PE.splice(Number(el.dataset.x), 1); renderPe(); }));
}
$('peAdd').addEventListener('click', () => { if (PE.length >= (LIMITS.params || 20)) return toast('Up to ' + (LIMITS.params || 20) + ' params', true); const used = new Set(PE.map(p => p.key)); const k = KEYS.find(x => !used.has(x)) || 's1'; PE.push({ key: k, token: '', label: '' }); renderPe(); const last = $('peRows').querySelector('[data-t="' + (PE.length - 1) + '"]'); if (last) last.focus(); });
$('sSave').addEventListener('click', async () => { const s = S.find(x => x.id === SEL); if (!s) return; try { await api('/api/my/sources/' + s.id, { name: $('sName').value, site: $('sSite').value, costModel: $('sCost').value, method: $('sMethod').value, postbackUrl: $('sPb').value.trim(), params: PE }); toast('Saved'); load(true); } catch (e) { toast(e.message, true); } });
$('togBtn').addEventListener('click', async () => { const s = S.find(x => x.id === SEL); if (!s) return; try { await api('/api/my/sources/' + s.id, { enabled: !s.enabled }); toast(s.enabled ? 'Source off: its postback will not fire' : 'Source on'); load(true); } catch (e) { toast(e.message, true); } });
$('delBtn').addEventListener('click', async () => { const s = S.find(x => x.id === SEL); if (!s) return; if (!await dialog({ title: 'Delete ' + s.name + '?', text: 'Links pointed at it keep working but lose the source; its click history stays in Reports as a deleted source.', ok: 'Delete', danger: true })) return; try { await api('/api/my/sources/' + s.id, { remove: true }); SEL = null; history.replaceState(null, '', location.pathname); toast('Deleted'); ROT = []; load(); } catch (e) { toast(e.message, true); } });
// -- New source: step 1 pick a network, step 2 the short form
async function newSource() {
if (!CAT.length) { try { CAT = (await CR.get('/api/sources/catalog')).catalog || []; } catch (e) {} }
let chosen = null;
const row = c => '<div class="cat" data-key="' + esc(c.key) + '" role="button" tabindex="0"><div><b>' + esc(c.name) + '</b><span class="site">' + esc(c.site || '') + (c.costModel ? ' · ' + esc(c.costModel) : '') + '</span>' + (gTags(c.key) ? '<div class="fm">' + gTags(c.key) + '</div>' : '') + '</div><div class="tags">' + (c.hasClickId ? '' : '<span class="tag warn" title="This network has no click id macro and no postback. The source still tags your campaign URL and shows in Reports.">no click id</span>') + (c.hasPostback ? '<span class="tag ok">postback</span>' : (c.hasClickId ? '<span class="tag dim">no postback</span>' : '')) + (c.verified ? '' : '<span class="tag dim" title="Macros copied from public docs, not yet checked against a live account">unverified</span>') + '</div></div>';
const p1 = dialog({ title: 'New source', text: 'Pick the network you buy traffic on. Its macros and postback come prefilled; you can change anything later under Settings. Search by name or by format (pop, push, native...). Not sure which fits your offer? See the Traffic guide.',
html: '<input class="field catf" id="catFilter" type="search" placeholder="Search ' + CAT.length + ' networks by name or site" aria-label="Search networks"><div class="catlist" id="catList">' + CAT.map(row).join('') + '</div>', ok: 'Custom (define your own)', no: 'Cancel' });
const host = $('crModalHost');
const wire = () => host.querySelectorAll('.cat').forEach(el => { const go = () => { chosen = el.dataset.key; host.querySelector('#dlgOk').click(); }; el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); go(); } }); });
wire();
const flt = host.querySelector('#catFilter'); flt.focus();
flt.addEventListener('input', () => { const q = flt.value.trim().toLowerCase(); const list = CAT.filter(c => !q || c.name.toLowerCase().includes(q) || (c.site || '').toLowerCase().includes(q) || c.key.includes(q) || gText(c.key).toLowerCase().includes(q)); host.querySelector('#catList').innerHTML = list.length ? list.map(row).join('') : '<div class="cat"><span class="muted">No network by that name. Use Custom and paste its macros yourself.</span></div>'; wire(); });
flt.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); const first = host.querySelector('.cat[data-key]'); if (first) first.click(); } });
const ok = await p1; if (!ok) return;
const tpl = chosen ? CAT.find(c => c.key === chosen) : null;
let v, body;
if (tpl) {
const fields = [{ k: 'name', label: 'Name for you', value: tpl.name, max: 60 }].concat((tpl.slots || []).map((sl, i) => ({ k: 'slot' + i, label: sl + (/\(optional\)/i.test(sl) ? '' : ' (from your ' + tpl.name + ' account)'), mono: true, max: 120 })));
const prev = '<div class="prev"><div><b>' + esc(tpl.name) + '</b> <span class="muted">' + esc(tpl.site || '') + '</span></div>'
+ (tpl.params.length ? '<dl>' + tpl.params.map(p => '<dt>' + esc(p.key) + '</dt><dd>' + esc(p.token) + (p.label ? ' <span class="muted">' + esc(p.label) + '</span>' : '') + '</dd>').join('') + '</dl>' : '<div class="muted">No macros listed for this network.</div>')
+ (tpl.hasPostback ? '<div class="mono">' + esc(tpl.postbackUrl) + '</div>' : '<div class="warn">' + (tpl.hasClickId ? 'No postback known for this network: it tags the campaign URL and shows in Reports. Paste its conversion URL under Settings if it has one.' : 'This network has no click id macro and no postback. The source tags your campaign URL and shows in Reports, nothing more.') + '</div>')
+ (tpl.notes ? '<div class="muted">' + esc(tpl.notes) + '</div>' : '') + '</div>';
v = await dialog({ title: 'New source: ' + tpl.name, html: prev, fields, ok: 'Create source' }); if (!v) return;
const slots = {}; (tpl.slots || []).forEach((sl, i) => { slots[sl] = v['slot' + i]; });
body = { template: tpl.key, name: v.name, slots };
} else {
v = await dialog({ title: 'New source: custom', text: 'Paste the macros exactly as the network expands them. One row for the click id is set up; add more under Settings.', fields: [{ k: 'name', label: 'Name', placeholder: 'My push network', max: 60 }, { k: 'site', label: 'Network site', placeholder: 'network.com', mono: true, max: 80 }, { k: 'clickid', label: 'Click id macro', value: '{clickid}', mono: true, max: 60 }, { k: 'postbackUrl', label: 'Postback URL (optional), {clickid} and {payout} where the network wants them', placeholder: 'https://network.example/postback?cid={clickid}&payout={payout}', mono: true }], ok: 'Create source' }); if (!v) return;
body = { template: 'custom', name: v.name, site: v.site, params: v.clickid.trim() ? [{ key: 'clickid', token: v.clickid.trim(), label: 'Click id' }] : [], postbackUrl: v.postbackUrl.trim() };
}
try { const r = await api('/api/my/sources', body); SEL = r.source.id; toast('Source created. Copy its campaign URL.'); await load(true); } catch (e) { toast(e.message, true); }
}
$('newBtn').addEventListener('click', newSource); $('newBtn2').addEventListener('click', newSource);
$('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); });
$('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); });
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
const showTab = name => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x.dataset.tab === name)); ['url', 'pb', 'settings'].forEach(t => { $('tab-' + t).hidden = t !== name; }); };
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab)));
CR.requireSession(() => { load(); });
})();