a0daf7925a
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
244 lines
35 KiB
JavaScript
244 lines
35 KiB
JavaScript
// 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, 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><button class="btn pri" id="bsNewBtn" type="button" hidden>+ New Banner Spin</button>' });
|
|
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
|
|
const clicks7 = r => r.hits7 || 0;
|
|
const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' };
|
|
|
|
// ── dayparting: grid = 7 strings of 24 chars '1'/'0', index 0 = Sunday; null = always on ──
|
|
const ALL = '1'.repeat(24), NONE = '0'.repeat(24);
|
|
const rowOf = (a, b) => { let s = ''; for (let h = 0; h < 24; h++) s += h >= a && h < b ? '1' : '0'; return s; };
|
|
const PRESETS = { always: null, business: [NONE, rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), rowOf(8, 18), NONE], evenings: new Array(7).fill(rowOf(17, 23)), weekends: [ALL, NONE, NONE, NONE, NONE, NONE, ALL] };
|
|
const ZONES = [['visitor', "Visitor's local time"], ['America/Chicago', 'Chicago (Central)'], ['America/New_York', 'New York (Eastern)'], ['America/Los_Angeles', 'Los Angeles (Pacific)'], ['Europe/London', 'London'], ['Europe/Berlin', 'Berlin'], ['Asia/Kolkata', 'India'], ['Asia/Manila', 'Manila'], ['Asia/Singapore', 'Singapore'], ['Australia/Sydney', 'Sydney']];
|
|
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ORDER = [1, 2, 3, 4, 5, 6, 0];
|
|
const ranges = s => { const out = []; let a = -1; for (let h = 0; h <= 24; h++) { const on = h < 24 && s[h] === '1'; if (on && a < 0) a = h; if (!on && a >= 0) { out.push(a + '-' + h); a = -1; } } return out.join(', '); };
|
|
function hoursText(hours) {
|
|
if (!hours || hours.every(s => s === ALL)) return 'Always on';
|
|
if (hours.every(s => s === hours[0])) return 'Every day ' + ranges(hours[0]);
|
|
const wk = [1, 2, 3, 4, 5], we = [0, 6], off = s => !s.includes('1');
|
|
if (wk.every(i => hours[i] === hours[1]) && we.every(i => off(hours[i]))) return 'Mon-Fri ' + ranges(hours[1]);
|
|
if (wk.every(i => off(hours[i])) && hours[0] === hours[6]) return 'Weekends' + (hours[6] === ALL ? '' : ' ' + ranges(hours[6]));
|
|
const n = hours.join('').split('1').length - 1; return 'Custom, ' + n + ' of 168 hours';
|
|
}
|
|
const tzText = tz => !tz || tz === 'visitor' ? "visitor's local time" : ((ZONES.find(z => z[0] === tz) || [])[1] || tz.split('/').pop().replace(/_/g, ' ')) + ' time';
|
|
const hoursChip = (hours, tz) => hoursText(hours) + (hours ? ', ' + tzText(tz) : '');
|
|
// the inline 7 x 24 editor. o = { hours, tz (undefined = no zone picker), heat (7x24 counts), best, onSave(hours, tz), onCancel }
|
|
function hoursEditor(host, o) {
|
|
let grid = (o.hours || new Array(7).fill(ALL)).map(s => s.split('')); let tz = o.tz || 'visitor';
|
|
const other = tz !== 'visitor' && !ZONES.some(z => z[0] === tz);
|
|
const max = o.heat ? Math.max(1, ...o.heat.map(d => Math.max(...d))) : 0;
|
|
host.innerHTML = '<div class="he">'
|
|
+ '<div class="he-presets"><span class="muted" style="font-size:11px">Presets</span>' + [['always', 'Always on'], ['business', 'Business, Mon-Fri 8-18'], ['evenings', 'Evenings, 17-23'], ['weekends', 'Weekends']].map(p => '<button class="btn sm" type="button" data-p="' + p[0] + '">' + p[1] + '</button>').join('')
|
|
+ '<button class="btn sm" type="button" data-p="best"' + (o.best && o.best.ready ? '' : ' disabled') + '>Use my best hours</button></div>'
|
|
+ (o.tz !== undefined ? '<div class="he-tz"><label class="lbl" style="margin:0">Time zone<select class="field" data-tz>' + ZONES.map(z => '<option value="' + z[0] + '"' + (z[0] === tz ? ' selected' : '') + '>' + esc(z[1]) + '</option>').join('') + '<option value="other"' + (other ? ' selected' : '') + '>Other (type a zone name)</option></select></label><input class="field mono" data-tzo type="text" placeholder="Area/City, like America/Denver"' + (other ? ' value="' + esc(tz) + '"' : ' hidden') + '></div>' : '<div class="muted" style="font-size:11px">Hours follow the link\'s time zone: ' + esc(tzText(o.rotTz)) + '.</div>')
|
|
+ '<div class="he-wrap"><div class="he-grid" data-grid><span></span>' + new Array(24).fill(0).map((_, h) => '<span class="hl">' + (h < 10 ? '0' + h : h) + '</span>').join('')
|
|
+ ORDER.map(wd => '<span class="dlb" data-day="' + wd + '" title="Flip the whole day">' + DAYS[wd] + '</span>' + new Array(24).fill(0).map((_, h) => '<span class="c" data-wd="' + wd + '" data-h="' + h + '"' + (o.heat && o.heat[wd][h] ? ' style="--heat:' + (0.12 + 0.55 * o.heat[wd][h] / max).toFixed(2) + '" title="' + o.heat[wd][h] + ' unique visitors, ' + DAYS[wd] + ' ' + h + ':00"' : ' title="' + DAYS[wd] + ' ' + h + ':00"') + '></span>').join('')).join('') + '</div></div>'
|
|
+ '<div class="he-sum" data-sum></div>'
|
|
+ '<div class="muted" style="font-size:11px" data-best>' + (o.best ? (o.best.ready ? 'Your best hours are the top quarter of weekday-hour cells by unique visitors over the last 30 days (' + fmt(o.best.hits) + ' clicks). Tinted cells show where your clicks land.' : '"Use my best hours" unlocks after ' + fmt(o.best.need) + ' clicks in 30 days; ' + fmt(o.best.hits) + ' so far.') : '') + '</div>'
|
|
+ '<div class="acts"><button class="btn pri" type="button" data-save>Save hours</button><button class="btn" type="button" data-cancel>Cancel</button><span class="muted" style="font-size:11px">Hours are 0 to 23; 8-18 means 8:00 up to 18:00.</span></div></div>';
|
|
const cells = {}; host.querySelectorAll('.c').forEach(c => { cells[c.dataset.wd + ':' + c.dataset.h] = c; if (o.heat && o.heat[c.dataset.wd][c.dataset.h]) c.classList.add('heat'); });
|
|
const paint = () => { for (const k in cells) { const [wd, h] = k.split(':'); cells[k].classList.toggle('on', grid[wd][h] === '1'); } const hs = grid.map(d => d.join('')); host.querySelector('[data-sum]').innerHTML = esc(hoursText(hs.every(s => s === ALL) ? null : hs)) + (o.tz !== undefined ? ' <small>' + esc(tzText(tz)) + '</small>' : ''); };
|
|
const set = (wd, h, v) => { grid[wd][h] = v; };
|
|
let painting = null;
|
|
const g = host.querySelector('[data-grid]');
|
|
const cellAt = e => { const el = document.elementFromPoint(e.clientX, e.clientY); return el && el.classList.contains('c') && g.contains(el) ? el : null; };
|
|
g.addEventListener('pointerdown', e => { const c = cellAt(e); if (!c) return; e.preventDefault(); painting = grid[c.dataset.wd][c.dataset.h] === '1' ? '0' : '1'; set(c.dataset.wd, c.dataset.h, painting); paint(); });
|
|
g.addEventListener('pointermove', e => { if (painting == null) return; const c = cellAt(e); if (c && grid[c.dataset.wd][c.dataset.h] !== painting) { set(c.dataset.wd, c.dataset.h, painting); paint(); } });
|
|
const stop = () => { painting = null; }; g.addEventListener('pointerup', stop); g.addEventListener('pointercancel', stop); g.addEventListener('pointerleave', stop);
|
|
host.querySelectorAll('.dlb').forEach(l => l.addEventListener('click', () => { const wd = l.dataset.day; const v = grid[wd].every(x => x === '1') ? '0' : '1'; grid[wd] = new Array(24).fill(v); paint(); }));
|
|
host.querySelectorAll('[data-p]').forEach(b => b.addEventListener('click', () => { const p = b.dataset.p; const src = p === 'best' ? (o.best && o.best.hours) : PRESETS[p]; grid = (src || new Array(7).fill(ALL)).map(s => s.split('')); paint(); }));
|
|
const sel = host.querySelector('[data-tz]'), oth = host.querySelector('[data-tzo]');
|
|
if (sel) { sel.addEventListener('change', () => { if (sel.value === 'other') { oth.hidden = false; oth.focus(); tz = oth.value.trim() || 'visitor'; } else { oth.hidden = true; tz = sel.value; } paint(); }); oth.addEventListener('input', () => { tz = oth.value.trim() || 'visitor'; paint(); }); }
|
|
host.querySelector('[data-save]').addEventListener('click', () => { const hs = grid.map(d => d.join('')); o.onSave(hs.every(s => s === ALL) ? null : hs, o.tz !== undefined ? tz : undefined); });
|
|
host.querySelector('[data-cancel]').addEventListener('click', () => o.onCancel && o.onCancel());
|
|
host.heState = () => ({ hours: grid.map(d => d.join('')), tz }); // so a redraw can keep unsaved taps
|
|
paint();
|
|
}
|
|
window.LSHours = { editor: hoursEditor, text: hoursText, chip: hoursChip }; // shared with the Banner Spin builder (banner-spin.js, 2026-10-18)
|
|
// ── health readouts ──
|
|
const ago = ts => { 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 mdy = ts => new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
|
const healthCls = h => !h ? '' : h.state === 'ok' ? 'ok' : h.state === 'slow' ? 'warn' : 'bad';
|
|
function healthLine(d) {
|
|
const h = d.health; if (!h) return 'Not checked yet; the first check runs within 30 minutes';
|
|
if (d.autoPaused) return (h.state === 'parked' ? 'Parked page' : h.state === 'dead' ? 'Dead page' : 'Back up') + ', auto-paused ' + mdy(d.autoPaused) + (h.state === 'ok' || h.state === 'slow' ? ', resumes after ' + (2 - (h.passes || 0)) + ' more clean check' + (2 - (h.passes || 0) === 1 ? '' : 's') : ', checked again every 6 hours');
|
|
if (h.state === 'ok' || h.state === 'slow') return 'Checked ' + ago(h.checkedAt) + ', ' + h.code + ' in ' + fmt(h.ms) + ' ms' + (h.note ? ', ' + h.note : '');
|
|
return 'Checked ' + ago(h.checkedAt) + ', ' + (h.note || h.state) + (d.active ? ', strike ' + h.fails + ' of 3' + (h.fails >= 3 ? ', kept live' : ', pauses at 3') : '');
|
|
}
|
|
let HE = null; // the destination editor that is open: { rid, did }
|
|
|
|
async function load(keep) {
|
|
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);
|
|
const TT = r.tier; const capTxt = TT ? (TT.unlimited ? ' links (' + TT.label + ', unlimited)' : ' of ' + TT.max + ' links (' + TT.label + ')') : (' link' + (ROT.length === 1 ? '' : 's'));
|
|
if (!/^#b/.test(location.hash)) CR.sub(ROT.length + capTxt + ' · ' + fmt(tot7) + ' clicks in 7 days');
|
|
renderList();
|
|
if (/^#b/.test(location.hash)) { renderList(); return; } // the Banner Spin view owns the page (banner-spin.js)
|
|
const want = SEL != null ? SEL : (Number(location.hash.slice(1)) || null);
|
|
if (want != null && ROT.find(x => x.id === want)) return select(want, true);
|
|
if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; }
|
|
else select(ROT[0].id, true);
|
|
}
|
|
function renderList() {
|
|
const q = FILTER.trim().toLowerCase();
|
|
const rows = ROT.filter(x => !q || x.name.toLowerCase().includes(q) || x.code.includes(q));
|
|
$('listCount').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's');
|
|
$('items').innerHTML = rows.length ? rows.map(x => { const h = health(x); return '<div class="item' + (x.id === SEL ? ' on' : '') + '" data-id="' + x.id + '" role="button" tabindex="0">'
|
|
+ '<div><div class="nm">' + esc(x.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + (x.conversions ? ' <span class="tag ok">' + x.conversions + ' conv</span>' : '') + '</div><div class="cd">' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '</div></div>'
|
|
+ '<div class="rt"><span class="n">' + fmt(clicks7(x)) + '</span><span class="muted" style="font-size:10px">7 d</span></div></div>'; }).join('')
|
|
: '<div class="empty"><div class="muted">' + (ROT.length ? 'No link matches that filter.' : 'No links yet.') + '</div></div>';
|
|
$('items').querySelectorAll('.item').forEach(el => { const go = () => select(Number(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 r = ROT.find(x => x.id === id); if (!r) return;
|
|
if (String(location.hash.slice(1)) !== String(id)) history.replaceState(null, '', '#' + id);
|
|
$('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus');
|
|
$('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id));
|
|
$('dName').textContent = r.name; $('dUrl').textContent = linkUrl(r);
|
|
const h = health(r); $('dLive').innerHTML = '<span class="' + h.cls + '"><span class="dot"></span>' + h.t + '</span>';
|
|
$('pauseBtn').textContent = r.paused ? 'Resume' : 'Pause';
|
|
$('fallback').value = r.fallback || '';
|
|
const fh = r.fallbackHealth; $('fallbackHealth').textContent = r.fallback ? (fh ? 'Fallback checked ' + ago(fh.checkedAt) + ': ' + (fh.state === 'ok' || fh.state === 'slow' ? fh.code + ' in ' + fmt(fh.ms) + ' ms' : (fh.note || fh.state)) + (fh.frameBlocked ? ', blocks frames' : '') : 'Fallback not checked yet') : '';
|
|
$('hoursChip').textContent = hoursChip(r.hours, r.tz); $('hoursChip').classList.toggle('set', !!r.hours);
|
|
renderTiles(r, STATS[id]);
|
|
renderDest(r); renderShare(r); renderRotHours(r, STATS[id]);
|
|
if (!quiet) window.scrollTo({ top: 0 });
|
|
loadStats(r.id);
|
|
}
|
|
function renderDest(r) {
|
|
const total = r.destinations.filter(d => d.active).reduce((n, d) => n + d.weight, 0) || 1;
|
|
const auto = r.destinations.filter(d => d.autoPaused);
|
|
const prevHost = $('destRows').querySelector('[data-he]'); const prev = prevHost && HE && Number(prevHost.dataset.he) === HE.did && prevHost.heState ? prevHost.heState() : null;
|
|
$('autoNote').hidden = !auto.length;
|
|
if (auto.length) $('autoNote').textContent = 'LinkSpin paused ' + (auto.length === 1 ? 'one destination' : auto.length + ' destinations') + ' automatically after three failed checks: ' + auto.map(d => (d.label || d.url.replace(/^https?:\/\//, '')).slice(0, 40)).join(', ') + '. It comes back on its own after two clean checks, or fix the address and press Resume.';
|
|
$('destRows').innerHTML = r.destinations.length ? r.destinations.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0; const h = d.health;
|
|
return '<div class="rw" data-did="' + d.id + '"><div><div class="dl"><span class="hdot ' + healthCls(h) + '" title="' + esc(healthLine(d)) + '"></span><span style="font-weight:700">' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '</span>' + (d.hours ? '<button class="hchip set" type="button" data-hc="' + d.id + '" title="This destination has its own hours">' + esc(hoursText(d.hours)) + '</button>' : '') + (h && h.frameBlocked ? '<span class="tag warn" title="This page refuses to load inside a frame (X-Frame-Options or CSP). Traffic exchanges that frame your link will show it blank.">no frames</span>' : '') + '</div>'
|
|
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(d.url) + '</div><div class="muted" style="font-size:11px" data-hl="' + d.id + '">' + esc(healthLine(d)) + '</div></div>'
|
|
+ '<div class="wrow"><div class="bar" style="width:70px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + d.weight + '" data-w="' + d.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
|
|
+ '<span class="r num">' + fmt(d.hits || 0) + '</span><span class="r num">' + fmt(d.uniques || 0) + '</span>'
|
|
+ '<span class="tag ' + (d.active ? 'ok' : d.autoPaused ? 'bad' : 'dim') + '">' + (d.active ? 'LIVE' : d.autoPaused ? 'AUTO-PAUSED' : 'PAUSED') + '</span>'
|
|
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-hc="' + d.id + '" title="Hours for this destination" aria-label="Hours for this destination"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg></button><button class="btn sm" type="button" data-t="' + d.id + '">' + (d.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + d.id + '" aria-label="Remove">×</button></span></div>'
|
|
+ (HE && HE.rid === r.id && HE.did === d.id ? '<div class="rw edit" data-he="' + d.id + '"></div>' : ''); }).join('')
|
|
: '<div class="rw"><span class="muted">No destinations yet. Add the first page below; until then the link sends people to the fallback.</span></div>';
|
|
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop · health checked every 30 min';
|
|
const openEditor = did => { const d = r.destinations.find(q => q.id === did); if (!d) return; HE = { rid: r.id, did }; renderDest(r); };
|
|
$('destRows').querySelectorAll('[data-hc]').forEach(b => b.addEventListener('click', () => { if (HE && HE.rid === r.id && HE.did === Number(b.dataset.hc)) { HE = null; renderDest(r); } else openEditor(Number(b.dataset.hc)); }));
|
|
const heHost = $('destRows').querySelector('[data-he]');
|
|
if (heHost) { const d = r.destinations.find(q => q.id === Number(heHost.dataset.he)); const s = STATS[r.id];
|
|
hoursEditor(heHost, { hours: prev ? prev.hours : d.hours, rotTz: r.tz, heat: s && s.best ? s.best.cells : null, best: s && s.best, onCancel: () => { HE = null; renderDest(r); },
|
|
onSave: async hours => { try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { hours }); HE = null; toast(hours ? 'Hours saved' : 'Destination is always on'); load(true); } catch (e) { toast(e.message, true); } } });
|
|
if (heHost.scrollIntoView) heHost.scrollIntoView({ block: 'nearest' }); }
|
|
$('destRows').querySelectorAll('[data-w]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/rotations/' + r.id + '/dest/' + i.dataset.w, { weight: i.value }); toast('Weight saved'); load(true); } catch (e) { toast(e.message, true); } }));
|
|
$('destRows').querySelectorAll('[data-t]').forEach(b => b.addEventListener('click', async () => { const d = r.destinations.find(q => q.id === Number(b.dataset.t)); try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { active: !d.active }); load(true); } catch (e) { toast(e.message, true); } }));
|
|
$('destRows').querySelectorAll('[data-x]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this destination?', text: 'Its click history stays in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/rotations/' + r.id + '/dest/' + b.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } }));
|
|
}
|
|
let LH = [];
|
|
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 + ')' : '')]);
|
|
// 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).'],
|
|
['Sub-id split test', url + '?s1=email-A and ' + url + '?s1=email-B (each shows up under Sources)'],
|
|
]);
|
|
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 }
|
|
function renderRotHours(r, s) {
|
|
const host = $('rotHours');
|
|
if (RH && RH.rid === r.id && RH.dirty && host.firstChild) return;
|
|
RH = { rid: r.id, dirty: false };
|
|
hoursEditor(host, { hours: r.hours, tz: r.tz || 'visitor', heat: s && s.best ? s.best.cells : null, best: s && s.best,
|
|
onCancel: () => { RH = null; renderRotHours(r, STATS[r.id]); },
|
|
onSave: async (hours, tz) => { try { await api('/api/my/rotations/' + r.id, { hours, tz }); RH = null; toast(hours ? 'Hours saved' : 'Link is always on'); load(true); } catch (e) { toast(e.message, true); } } });
|
|
host.addEventListener('pointerdown', () => { if (RH) RH.dirty = true; }, { once: true });
|
|
host.addEventListener('change', () => { if (RH) RH.dirty = true; }, { once: true });
|
|
$('offNote').textContent = s ? ((s.offHours ? fmt(s.offHours) + ' click' + (s.offHours === 1 ? '' : 's') + ' arrived outside the link\'s hours and went to the fallback (all time, ' + fmt(r.offHours30 || 0) + ' in 30 days).' : 'No clicks have gone to the off-hours fallback yet.')) : '';
|
|
}
|
|
const kv = rows => rows && rows.length ? rows.map(x => '<span style="overflow-wrap:anywhere">' + esc(x.k) + '</span><span class="bar"><i style="width:' + Math.round(x.n / (rows[0].n || 1) * 100) + '%"></i></span><span class="r num">' + fmt(x.n) + '</span>').join('') : '<span class="muted">nothing yet</span><span></span><span></span>';
|
|
function renderTiles(r, s) {
|
|
let series = null, delta = null;
|
|
if (s && s.days) { // per-day clicks: last 7 days as the sparkline, delta against the 7 before
|
|
const by = {}; s.days.forEach(d => { by[d.day] = d.n; }); const day = i => new Date(Date.now() - i * 86400000).toISOString().slice(0, 10);
|
|
series = []; for (let i = 6; i >= 0; i--) series.push(by[day(i)] || 0);
|
|
let prior = 0; for (let i = 13; i >= 7; i--) prior += by[day(i)] || 0;
|
|
delta = CR.delta(series.reduce((a, b) => a + b, 0), prior, 'vs prior 7 d');
|
|
}
|
|
$('tiles').innerHTML = [
|
|
CR.tile({ k: 'Served, 7 d', v: fmt(r.hits7 || 0), hi: true, series, delta }),
|
|
CR.tile({ k: 'Unique, all time', v: fmt(r.uniques || 0) }), CR.tile({ k: 'Clicks, all time', v: fmt(r.hits || 0) }), CR.tile({ k: 'Bots dropped', v: fmt(r.bots || 0) }),
|
|
CR.tile({ k: 'Conversions', v: fmt(r.conversions || 0) }), CR.tile({ k: 'Live destinations', v: r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length })].join('');
|
|
}
|
|
async function loadStats(id) {
|
|
let s = STATS[id]; if (!s) { try { s = await CR.get('/api/my/rotations/' + id + '/stats'); } catch (e) { return; } STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); }
|
|
if (SEL !== id) return;
|
|
{ const r = ROT.find(x => x.id === id); if (r) { renderTiles(r, s); if (!(RH && RH.rid === id && RH.dirty)) renderRotHours(r, s); } }
|
|
const hmax = Math.max(1, ...s.hours); $('hourBars').innerHTML = s.hours.map((n, i) => '<i class="' + (n >= hmax * 0.6 ? '' : 'dim') + '" style="height:' + Math.round(n / hmax * 100) + '%" title="' + i + ':00 · ' + n + '"></i>').join('');
|
|
$('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country); $('subRows').innerHTML = kv(s.subs); $('convRows').innerHTML = kv(s.conversions);
|
|
const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.length ? dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ') : '';
|
|
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => d.n));
|
|
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
|
|
$('dayBars').innerHTML = days.length ? days.map(d => '<i class="' + (days.length >= 3 && d.n === dmax ? 'hi' : '') + '" style="height:' + Math.round(d.n / dmax * 100) + '%" title="' + d.day + ' · ' + d.n + '"></i>').join('') : '';
|
|
$('dayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no clicks recorded yet</span>';
|
|
}
|
|
// postbacks (account level)
|
|
async function loadPb() {
|
|
try { PB = await CR.get('/api/my/postbacks'); } catch (e) { return; }
|
|
$('pbInUrl').textContent = PB.inboundUrl + '?key=' + PB.key + '&lsid={lsid}&event=sale&value=0.00';
|
|
const rows = PB.postbacks || [];
|
|
$('pbRows').innerHTML = rows.length ? rows.map(p => '<div class="rw"><div><b>' + esc(p.name) + '</b><br><span class="mono muted" style="font-size:11px">' + p.method + ' · sent ' + fmt(p.sent) + (p.lastAt ? ' · last ' + esc(String(p.lastStatus)) : '') + '</span></div><div class="mono" style="font-size:11px;overflow-wrap:anywhere">' + esc(p.url) + '</div><div>' + p.events.map(e => '<span class="tag dim">' + e + '</span>').join(' ') + '</div><div>' + (p.enabled ? '<span class="tag ok">ON</span>' : '<span class="tag warn">OFF' + (p.fails >= 10 ? ' · failed 10x' : '') + '</span>') + '</div><div style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap"><button class="btn sm" type="button" data-test="' + p.id + '">Test</button><button class="btn sm" type="button" data-tog="' + p.id + '">' + (p.enabled ? 'Off' : 'On') + '</button><button class="btn sm" type="button" data-edit="' + p.id + '">Edit</button><button class="btn sm danger" type="button" data-del="' + p.id + '" aria-label="Remove">×</button></div></div>').join('')
|
|
: '<div class="rw"><span class="muted">No postbacks yet. Add your tracker\'s postback URL and pick which events fire it.</span></div>';
|
|
const log = PB.log || []; $('pbFoot').textContent = log.length ? 'last delivery: ' + new Date(log[0].ts).toLocaleString() + ' · ' + log[0].name + ' · ' + log[0].event + ' · ' + (log[0].ok ? 'ok ' + log[0].status : 'failed ' + (log[0].status || log[0].note)) + ' · ' + log.filter(l => l.ok).length + ' of the last ' + log.length + ' succeeded' : 'no deliveries yet';
|
|
$('pbRows').querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', async () => { b.disabled = true; try { const r = await api('/api/my/postbacks/' + b.dataset.test, { 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; loadPb(); }));
|
|
$('pbRows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const p = rows.find(x => x.id === b.dataset.tog); try { await api('/api/my/postbacks/' + p.id, { enabled: !p.enabled }); loadPb(); } catch (e) { toast(e.message, true); } }));
|
|
$('pbRows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this postback?', ok: 'Remove', danger: true })) return; try { await api('/api/my/postbacks/' + b.dataset.del, { remove: true }); loadPb(); } catch (e) { toast(e.message, true); } }));
|
|
$('pbRows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => pbForm(rows.find(x => x.id === b.dataset.edit))));
|
|
}
|
|
async function pbForm(p) {
|
|
const ev = (PB && PB.events) || ['join', 'wallet', 'purchase', 'external'];
|
|
const v = await dialog({ title: p ? 'Edit postback' : 'New postback', text: 'Your tracker or network gives you a postback URL with macros. Paste it; LinkSpin fills the click id it saw on the link.',
|
|
fields: [{ k: 'name', label: 'Name', value: p ? p.name : '', placeholder: 'BeMob', max: 60 }, { k: 'url', label: 'URL template', value: p ? p.url : '', placeholder: 'https://tracker.example/postback?cid={clickid}&payout={payout}&txid={txid}', mono: true, type: 'url' }, { k: 'events', label: 'Events, comma separated: ' + ev.join(', '), value: p ? p.events.join(',') : 'join,purchase' }, { k: 'method', label: 'Method, GET or POST', value: p ? p.method : 'GET', max: 4 }], ok: p ? 'Save' : 'Create' });
|
|
if (!v) return;
|
|
try { if (p) await api('/api/my/postbacks/' + p.id, v); else await api('/api/my/postbacks', v); toast(p ? 'Saved' : 'Postback added'); loadPb(); } catch (e) { toast(e.message, true); }
|
|
}
|
|
async function newSpin() {
|
|
const v = await dialog({ title: 'New spin', text: 'Name it for you, not for visitors. You add the pages next.', fields: [{ k: 'name', label: 'Name', placeholder: 'IAP main invite', max: 80 }, { k: 'url', label: 'First page to send people to (optional)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' });
|
|
if (!v || !v.name.trim()) return;
|
|
try { const r = await api('/api/my/rotations', { name: v.name }); const id = r.rotation.id; if (v.url && v.url.trim()) await api('/api/my/rotations/' + id + '/dest', { url: v.url.trim(), weight: 10 }); SEL = id; toast('Link created'); await load(true); } catch (e) { toast(e.message, true); }
|
|
}
|
|
$('newBtn').addEventListener('click', newSpin); $('newBtn2').addEventListener('click', newSpin);
|
|
$('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); });
|
|
$('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) CR.copy(linkUrl(r)); });
|
|
$('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); });
|
|
$('renameBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: r.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/rotations/' + r.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } });
|
|
$('pauseBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { paused: !r.paused }); toast(r.paused ? 'Live again' : 'Paused: visitors go to the fallback'); load(true); } catch (e) { toast(e.message, true); } });
|
|
$('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; history.replaceState(null, '', location.pathname); toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
|
|
$('addBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const url = $('addUrl').value.trim(); if (!url) { $('addUrl').focus(); return; } try { await api('/api/my/rotations/' + r.id + '/dest', { url, label: $('addLabel').value, weight: $('addWeight').value }); $('addUrl').value = ''; $('addLabel').value = ''; toast('Destination added'); load(true); } catch (e) { toast(e.message, true); } });
|
|
$('addUrl').addEventListener('keydown', e => { if (e.key === 'Enter') $('addBtn').click(); });
|
|
$('fallback').addEventListener('change', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { fallback: $('fallback').value.trim() }); toast('Fallback saved'); load(true); } catch (e) { toast(e.message, true); } });
|
|
const showTab = name => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x.dataset.tab === name)); ['dest', 'hours', 'sources', 'report', 'share'].forEach(t => { $('tab-' + t).hidden = t !== name; }); };
|
|
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab)));
|
|
$('hoursChip').addEventListener('click', () => { showTab('hours'); const h = $('rotHours'); if (h.scrollIntoView) h.scrollIntoView({ block: 'start', behavior: 'smooth' }); });
|
|
$('checkBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const b = $('checkBtn'); b.disabled = true; b.textContent = 'Checking';
|
|
try { const out = await api('/api/my/rotations/' + r.id + '/health'); const i = ROT.findIndex(x => x.id === r.id); if (i >= 0 && out.rotation) ROT[i] = out.rotation; const fresh = out.rotation || r; renderDest(fresh); select(r.id, true);
|
|
const bad = fresh.destinations.filter(d => d.health && (d.health.state === 'dead' || d.health.state === 'parked')).length; toast('Checked ' + fresh.destinations.length + ' destination' + (fresh.destinations.length === 1 ? '' : 's') + (bad ? ', ' + bad + ' failing' : ', all answering')); }
|
|
catch (e) { toast(e.message, true); } b.disabled = false; b.textContent = 'Check now'; });
|
|
$('pbNew').addEventListener('click', () => pbForm(null));
|
|
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
|
|
window.LSLinks = { reload: () => load(true) }; // the Banner Spin view switches back here
|
|
CR.requireSession(() => { load(); loadPb(); if (window.BannerSpin) window.BannerSpin.ready(); setInterval(() => { if (!document.hidden) load(true); }, 60000); });
|
|
})();
|