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>
This commit is contained in:
martbost
2026-10-12 11:16:24 -05:00
parent d1a25e72f2
commit 211eb5a0e8
22 changed files with 2429 additions and 49 deletions
+2 -1
View File
@@ -8,6 +8,7 @@ window.CR = (function () {
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"/>'],
@@ -23,7 +24,7 @@ window.CR = (function () {
];
// 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', '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)
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; }
+1
View File
@@ -176,6 +176,7 @@ label.lbl{display:grid;gap:5px;font-size:10.5px;font-weight:700;letter-spacing:.
.rail{position:fixed;top:auto;bottom:0;left:0;right:0;height:auto;flex-direction:row;justify-content:space-around;padding:6px 6px calc(6px + env(safe-area-inset-bottom,0px));border-right:0;border-top:1px solid var(--chrome-line);z-index:30}
.rail .mark,.rail .sp,.railtog,.rail .lbl,.rail a.rsec{display:none} .rail a.on::before{display:none}
.app.wide{grid-template-columns:1fr} .app.wide .rail{align-items:center;padding:6px 6px calc(6px + env(safe-area-inset-bottom,0px))} .app.wide .rail a{width:40px;justify-content:center;padding:0}
.app.wide .rail a .lbl{display:none} .rail a,.app.wide .rail a{width:34px;height:38px} /* ten entries since Sources joined the rail (2026-10-12): icons only, 34px each, so the bar fits a 360px phone */
.main{padding-bottom:64px;min-height:auto}
.topbar{padding:10px 16px;flex-wrap:wrap;gap:10px 14px} .topbar .readout{display:none}
.strip{flex-wrap:wrap;gap:8px 16px;padding:8px 16px}
+10 -4
View File
@@ -1,7 +1,7 @@
// LinkSpin Links workspace (Control Room). Rotator API + postbacks + share kit. Uses the shared shell (cr-shell.js).
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null;
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null, SRC = []; // SRC = the member's traffic sources (sources.js, 2026-10-12)
CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '<button class="btn pri" id="newBtn" type="button">+ New spin</button>' });
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
const clicks7 = r => r.hits7 || 0;
@@ -72,6 +72,7 @@
let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; }
ROT = (r.rotations || []).slice().sort((a, b) => clicks7(b) - clicks7(a)); HOSTS = r.hosts || [];
try { const lh = await api('/api/my/link-hosts'); LH = (lh && lh.hosts) || []; } catch (e) { LH = []; } // link domains by channel (domains.js, 2026-10-10)
try { SRC = (await CR.get('/api/my/sources')).sources || []; } catch (e) { SRC = []; }
const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0);
CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days');
renderList();
@@ -137,14 +138,19 @@
function renderShare(r) {
const url = linkUrl(r);
const byChannel = LH.filter(h => h.channel !== 'reserve').map(h => ['Best link for ' + (h.label || h.channel), 'https://' + h.host + '/r/' + r.code + (h.note ? ' (' + h.note + ')' : '')]);
const kit = byChannel.concat([
// traffic source (2026-10-12): when the link is pointed at one, the first row is the exact campaign URL for that network
const src = SRC.find(s => s.id === r.sourceId) || null;
const campaign = src ? [['Campaign URL for ' + src.name, url + ((src.params || []).length ? '?' + src.params.map(p => p.key + '=' + p.token).join('&') : '')]] : [['Tracker-ready link', url + '?clickid={clickid}&s1={source} (replace the braces with your network\'s macros)']];
const kit = campaign.concat(byChannel, [
['Short post', 'One link, every page I promote, in turn. Take a look: ' + url],
['Email or Telegram line', 'Here is the link I use for everything: ' + url + ' (it always sends you to the right page).'],
['Tracker-ready link', url + '?clickid={clickid}&s1={source} (replace the braces with your network\'s macros)'],
['Sub-id split test', url + '?s1=email-A and ' + url + '?s1=email-B (each shows up under Sources)'],
]);
$('shareKit').innerHTML = kit.map(([t, body], i) => '<div class="panel" style="padding:10px 12px"><div style="display:flex;justify-content:space-between;align-items:center;gap:8px"><b>' + esc(t) + '</b><button class="btn sm" type="button" data-cp="' + i + '">Copy</button></div><div class="mono muted" style="font-size:12px;overflow-wrap:anywhere;margin-top:6px" id="kit-' + i + '">' + esc(body) + '</div></div>').join('');
const picker = '<div class="panel" style="padding:10px 12px"><div style="display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end"><label class="lbl" style="margin:0">Traffic source for this link<select class="field" id="srcSel"><option value="">None (generic tracker macros)</option>' + SRC.map(s => '<option value="' + s.id + '"' + (s.id === r.sourceId ? ' selected' : '') + '>' + esc(s.name) + (s.site ? ' · ' + esc(s.site) : '') + '</option>').join('') + '</select></label><a class="btn sm" href="/sources">Manage sources</a></div>'
+ '<div class="muted" style="font-size:11.5px;margin-top:6px">' + (src ? 'Paste the campaign URL below as the destination in ' + esc(src.site || src.name) + '. Conversions from this link fire ' + esc(src.name) + '\'s postback' + (src.postbackUrl ? '' : ' once one is set under Sources') + '.' : 'A source fills in the network\'s macros for you and tells that network when a click converts. Pick one, or make one under Sources.') + '</div></div>';
$('shareKit').innerHTML = picker + kit.map(([t, body], i) => '<div class="panel" style="padding:10px 12px"><div style="display:flex;justify-content:space-between;align-items:center;gap:8px"><b>' + esc(t) + '</b><button class="btn sm" type="button" data-cp="' + i + '">Copy</button></div><div class="mono muted" style="font-size:12px;overflow-wrap:anywhere;margin-top:6px" id="kit-' + i + '">' + esc(body) + '</div></div>').join('');
$('shareKit').querySelectorAll('[data-cp]').forEach(b => b.addEventListener('click', () => CR.copy($('kit-' + b.dataset.cp).textContent)));
$('srcSel').addEventListener('change', async () => { try { await api('/api/my/rotations/' + r.id, { sourceId: $('srcSel').value }); toast($('srcSel').value ? 'Source saved' : 'Source removed'); load(true); } catch (e) { toast(e.message, true); } });
}
// the rotation's own hours editor on the Hours tab. Not redrawn while the member is mid-edit (the 60 s refresh would eat their taps).
let RH = null; // { rid, dirty }
+4
View File
@@ -48,6 +48,10 @@
$('pgBars').querySelectorAll('i b').forEach(b => { b.style.background = 'var(--sig)'; });
$('pgTiles').innerHTML = mini([['Views', fmt(pg.views)], ['Unique', fmt(pg.uniques)], ['Clicks through', fmt(pg.clicks)], ['Leads', fmt(pg.leads)]]);
$('pgRows').innerHTML = (pg.byPage || []).length ? pg.byPage.map(x => '<div class="rw"><a href="/pages" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.title) + '</b><br><span class="mono muted" style="font-size:11px">' + esc(x.type) + ' · ' + (x.status === 'published' ? '<span class="ok">live</span>' : 'draft') + '</span></a><span class="r num">' + fmt(x.views) + '</span><span class="r num">' + fmt(x.uniques) + '</span><span class="r num">' + fmt(x.clicks) + '</span><span class="r num">' + fmt(x.leads) + '</span></div>').join('') : '<div class="rw"><span class="muted">No pages yet. <a href="/pages">Make one</a>.</span></div>';
// -- Traffic sources (2026-10-12): per source, and per placement value the network's macro carried
const ts = s.sources || [], pl = s.placements || [];
$('tsRows').innerHTML = ts.length ? ts.map(x => '<div class="rw"><a href="/sources#' + esc(x.id) + '" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.name) + '</b>' + (x.site ? '<br><span class="mono muted" style="font-size:11px">' + esc(x.site) + '</span>' : '') + '</a><span class="r num">' + fmt(x.hits) + '</span><span class="r num">' + fmt(x.unique) + '</span><span class="r num">' + fmt(x.conv) + (x.unique ? ' <span class="muted" style="font-size:10px">' + (x.conv / x.unique * 100).toFixed(1) + '%</span>' : '') + '</span></div>').join('') : '<div class="rw"><span class="muted">No clicks from a traffic source yet. Point a link at one under <a href="/sources">Sources</a>.</span></div>';
$('plRows').innerHTML = pl.length ? pl.map(x => '<div class="rw"><span><b>' + esc(x.source) + '</b><br><span class="mono muted" style="font-size:11px">' + esc(x.key) + ' = ' + esc(x.k) + '</span></span><span class="r num">' + fmt(x.n) + '</span><span class="r num">' + fmt(x.conv) + '</span></div>').join('') : '<div class="rw"><span class="muted">Nothing yet. Placements appear once a source\'s zone or placement macro rides in on clicks.</span></div>';
const zn = s.zones || { byDay: [], byZone: [] };
// bar = all views, lighter inner share = the ones that were NOT viewable
dayBars('znBars', 'znAxis', zn.byDay, d => d.views, d => d.views - d.viewable, 'no zone views yet');
+139
View File
@@ -0,0 +1,139 @@
// 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: '<button class="btn pri" type="button" id="newBtn">+ New source</button>' });
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' };
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('');
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></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.',
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)); 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(); });
})();