Banner Spin phase 3: reports, health checks, postbacks verified, admin switch button

- bannerspin.js: every image load also counted raw per placement (bots/prefetch and servers/mail image proxies kept apart from views); one aggregation for the Stats tab and a new summary() for Reports: per banner (views, uniques, clicks, CTR, match rate, conversions), per placement with a "caches banners" flag, by Central day, country and device, bots shown separately; WINNER badge once two live banners have 1,000 views each and one leads on CTR. Click params now keep the banner macro (same list as spin links). Owner pause/resume clears an auto-pause; a new image or target resets health.
- health.js: the 30-minute pass also checks each live banner: image must load as an image (magic bytes) at the Banner Spin size, target must pass the spin-link checks (a spin-link target only has to exist). 3 failures pause, 2 clean passes resume, the last live banner is never auto-paused; owner gets an inbox notice. checkBannerSpins() for admin.
- server.js (own blocks): health.init gets bannerspin; /api/my/reports adds bannerSpins; POST /api/admin/bannerspins/health runs the checks now.
- Builder: health line + AUTO-PAUSED tag on every banner row; Stats tab adds uniques, WINNER, CACHED placements, loads, country/device, bots line.
- Reports screen: Banner Spin section + Banner views/clicks tiles beside spin links.
- Admin > Member content: real Banner Spin on/off button (with confirm) and "Run banner checks".
- Traffic-source postbacks on Banner Spin clicks verified end to end (network click id, event, payout, lsid reach the source postback).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-20 05:39:50 -05:00
parent a9994e708d
commit f93bca81a7
9 changed files with 334 additions and 55 deletions
+122 -32
View File
@@ -28,7 +28,12 @@
// below a tier keeps everything serving; it only stops new ones.
//
// Moderation. Admin can take one banner or a whole Banner Spin offline (a neutral blank image + the fallback link), or
// switch the whole feature off. Store: DATA_DIR/bannerspin.json (atomic writes).
// switch the whole feature off (a button in Admin > Member content since phase 3). Store: DATA_DIR/bannerspin.json (atomic writes).
//
// Phase 3 (2026-10-20, "Reports and health"): every image load is also counted raw per placement (bots, prefetches and
// servers / mail image proxies kept apart from views), which feeds the "caches banners" flag; stats() and summary() share
// one aggregation (per banner, per placement, by Central day, country and device, a winner once two banners have 1,000
// views each); health.js checks each live banner's image and target every 30 minutes (b.health, b.autoPaused).
'use strict';
const fs = require('fs');
const path = require('path');
@@ -83,6 +88,11 @@ const vkey = (req, ts) => crypto.createHash('sha256').update(new Date(ts || Date
function vkeys(req) { const now = Date.now(); const k = [vkey(req, now)]; if (now % DAY < NOTE_TTL) k.push(vkey(req, now - DAY)); return k; }
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT.test(ua); };
const isPrefetch = req => /prefetch|prerender|preview/i.test([req.headers.purpose, req.headers['sec-purpose'], req.headers['x-purpose'], req.headers['x-moz']].filter(Boolean).join(' '));
// a server fetching the image, not a browser (phase 3, 2026-10-20): mail image proxies and plain HTTP libraries. Kept out of
// impressions like bots, but counted per placement, because a site that copies banners to its own server shows up this way.
const PROXY = /GoogleImageProxy|ggpht\.com|YahooMailProxy|ImageProxy|^(php|java|go-http-client|okhttp|axios|node-fetch|undici|libwww-perl|apache-httpclient|guzzlehttp|ruby)\b/i;
// '' = a browser view (counted), 'pre' = prefetch, 'bot' = bot or no UA, 'srv' = a server or image proxy
const loaderKind = req => isPrefetch(req) ? 'pre' : isBot(req) ? 'bot' : PROXY.test(String(req.headers['user-agent'] || '')) ? 'srv' : '';
// the placement: the page the banner sits on (the browser's referrer, else its origin), www stripped
function hostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, '').slice(0, 80); } catch (e) { return ''; } }
@@ -98,18 +108,33 @@ function findNote(keys, s, h) {
function sweep() { const now = Date.now(); for (const [k, a] of NOTES) { const keep = a.filter(n => now - n.ts <= NOTE_TTL); if (keep.length) NOTES.set(k, keep); else NOTES.delete(k); } for (const [k, t] of SEEN) if (now - t > DEDUPE_MS) SEEN.delete(k); }
// ── counters ──
// a day record: b = counted views per banner, h = per placement host per banner, u = uniques sample per banner,
// bt = bot + prefetch loads, sv = server / image-proxy loads, z = per placement host { r: every load, s: loads with no browser, k: top loaders sample }
const dayRec = sid => { const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; return s[day] = s[day] || { b: {}, h: {}, u: {}, z: {} }; };
function bump(sid, bid, host, v) {
const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
const d = dayRec(sid);
d.b[bid] = (d.b[bid] || 0) + 1; const hk = host || '(none)'; const hh = d.h[hk] = d.h[hk] || {}; hh[bid] = (hh[bid] || 0) + 1;
const u = d.u[bid] = d.u[bid] || []; const p = v.slice(0, 8); if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p);
DIRTY = true;
}
// every image load (counted or not), for bots shown separately and the "caches banners" flag
const LOADERS_CAP = 10;
function rawLoad(sid, host, v, kind) {
const d = dayRec(sid); const hk = host || '(none)'; const z = d.z[hk] = d.z[hk] || { r: 0, s: 0, k: {} };
z.r++; if (kind === 'bot' || kind === 'srv') z.s++;
const p = v.slice(0, 8); if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + 1;
if (kind === 'bot' || kind === 'pre') d.bt = (d.bt || 0) + 1; else if (kind === 'srv') d.sv = (d.sv || 0) + 1;
DIRTY = true;
}
function mergeInto(base, add) {
for (const [sid, days] of Object.entries(add.d)) { const s = base.d[sid] = base.d[sid] || {};
for (const [day, x] of Object.entries(days)) { const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
for (const [b, n] of Object.entries(x.b)) d.b[b] = (d.b[b] || 0) + n;
for (const [h, m] of Object.entries(x.h)) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
for (const [b, arr] of Object.entries(x.u)) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); } } }
for (const [b, n] of Object.entries(x.b || {})) d.b[b] = (d.b[b] || 0) + n;
for (const [h, m] of Object.entries(x.h || {})) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
for (const [b, arr] of Object.entries(x.u || {})) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); }
if (x.bt) d.bt = (d.bt || 0) + x.bt; if (x.sv) d.sv = (d.sv || 0) + x.sv;
if (x.z) { d.z = d.z || {}; for (const [h, zz] of Object.entries(x.z)) { let z = d.z[h]; if (!z) { const key = Object.keys(d.z).length >= HOSTS_CAP ? '(other)' : h; z = d.z[key] = d.z[key] || { r: 0, s: 0, k: {} }; }
z.r += zz.r || 0; z.s += zz.s || 0; for (const [p, n] of Object.entries(zz.k || {})) if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + n; } } } }
return base;
}
function flush() {
@@ -162,7 +187,8 @@ function pub(s, extra) {
return Object.assign({ id: s.id, code: s.code, name: s.name, size: s.size, mode: s.mode || 'weight', owner: s.owner, created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '',
fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', hours: s.hours || null, tz: s.tz || 'visitor', sourceId: s.sourceId || '',
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, w: b.w || 0, h: b.h || 0, bytes: b.bytes || 0, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff, hours: b.hours || null, added: b.added,
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h) })),
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h),
autoPaused: b.autoPaused || 0, health: b.health ? { state: b.health.state, note: b.health.note || '', checkedAt: b.health.checkedAt || 0, fails: b.health.fails || 0, image: b.health.image || null, target: b.health.target || null } : null })),
imps: sum(imps), imps30: sum(imps30), fallbackImps: imps[0] || 0, clicks: sum(cl), matched: Object.values(cl).reduce((a, o) => a + o.m, 0), conversions: conv }, extra || {});
}
async function list(owner) { return mine(owner).map(s => pub(s)); }
@@ -203,10 +229,10 @@ async function updateBanner(owner, id, bid, body) {
const b = s.banners.find(x => x.id === Number(bid)); if (!b) return { error: 'No such banner.' };
if (body.remove) { s.banners = s.banners.filter(x => x !== b); J.save(); return { ok: true, spin: pub(s) }; }
if (body.weight != null) b.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
if (body.active != null) b.active = !!body.active;
if (body.active != null) { b.active = !!body.active; delete b.autoPaused; } // the owner's own pause / resume wins over the health checker
if (body.label != null) b.label = String(body.label).trim().slice(0, 60);
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); }
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; }
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); delete b.health; }
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; delete b.health; }
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) b.hours = h.hours; else delete b.hours; }
J.save(); return { ok: true, spin: pub(s) };
}
@@ -243,7 +269,8 @@ function choose(s, req, opts) {
const off = s.paused || !rotator.isOn(s.hours, cell);
const b = off ? null : pick(s, cell, v);
const out = b ? { banner: b } : (s.fallbackImage ? { fallback: true } : { blank: true, fallback: true });
if (!isBot(req) && !isPrefetch(req)) {
const kind = loaderKind(req); rawLoad(String(s.id), hostOf(req), v, kind);
if (!kind) {
const bid = b ? b.id : 0; const host = hostOf(req);
note(v, s.id, host, bid);
const k = v + '|' + s.id + '|' + bid; const last = SEEN.get(k);
@@ -287,7 +314,7 @@ async function click(code, req, reqHost) {
if (!url) { const first = s.banners.find(q => q.active && !q.adminOff && q.target); url = first ? first.target : null; } // no fallback set: the first live banner beats a dead end
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {}
const ua = String(req.headers['user-agent'] || ''); const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|banner|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
const id = 'k' + crypto.randomBytes(6).toString('hex').slice(0, 11);
J.db.clicks.push({ id, s: s.id, b: b ? b.id : 0, ts: Date.now(), v: keys[0], h: h || undefined, m, bot, c: country || undefined, dv: device, q: Object.keys(q).length ? q : undefined, sr: s.sourceId || undefined });
if (J.db.clicks.length > 200000) J.db.clicks = J.db.clicks.slice(-150000);
@@ -308,28 +335,87 @@ async function convert(lsid, ev, facts) {
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
}
// ── stats: per banner and per placement (impressions, clicks, CTR, match rate), last 30 Central days by day ──
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
// sinceTs = 0 means all time (the builder); Reports passes its range. Day keys are Central time.
const WIN_MIN = 1000; // a winner needs this many views on every banner it is compared with
const ctrOf = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null;
const mrOf = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
function agg(spins, sinceTs) {
const sinceDay = sinceTs ? ctDay(sinceTs) : '';
const ids = new Set(spins.map(s => s.id));
const blank = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0, bots: 0, botClicks: 0, srv: 0, raw: 0, top: {} });
const at = (o, k) => (o[k] = o[k] || blank());
const per = {}, hosts = {}, days = {}, T = blank();
for (const s of spins) for (const [day, d] of Object.entries(countsOf(s.id))) {
if (sinceDay && day < sinceDay) continue;
const dd = at(days, day);
for (const [b, n] of Object.entries(d.b || {})) { at(per, s.id + ':' + b).imps += n; dd.imps += n; T.imps += n; }
for (const [b, arr] of Object.entries(d.u || {})) { at(per, s.id + ':' + b).uniq += arr.length; dd.uniq += arr.length; T.uniq += arr.length; }
for (const [h, m] of Object.entries(d.h || {})) for (const n of Object.values(m)) at(hosts, h).imps += n;
dd.bots += d.bt || 0; T.bots += d.bt || 0; dd.srv += d.sv || 0; T.srv += d.sv || 0;
for (const [h, z] of Object.entries(d.z || {})) { const o = at(hosts, h); o.raw += z.r || 0; o.srv += z.s || 0; for (const [k, n] of Object.entries(z.k || {})) o.top[k] = (o.top[k] || 0) + n; }
}
const country = {}, device = {};
for (const c of J.db.clicks) {
if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue;
const dd = at(days, ctDay(c.ts));
if (c.bot) { T.botClicks++; dd.botClicks++; continue; }
const ok = c.m === 'exact' || c.m === 'note';
for (const o of [at(per, c.s + ':' + c.b), at(hosts, c.h || '(none)'), dd, T]) { o.clicks++; if (ok) o.matched++; else if (c.m === 'none') o.unmatched++; }
const k = c.c || '(none)'; country[k] = (country[k] || 0) + 1; const dv = c.dv || '(none)'; device[dv] = (device[dv] || 0) + 1;
}
const convBy = {};
for (const c of J.db.conv) { if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue; at(per, c.s + ':' + c.b).conv++; T.conv++; at(days, ctDay(c.ts)).conv++; const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
return { per, hosts, days, T, country, device, convBy };
}
// the "caches banners" flag: a placement whose image loads come from a server instead of browsers, or whose clicks
// cannot be tied to a view (a copied image never asks us, so the click arrives with no note). '' when it looks normal.
function cacheFlag(o) {
if (o.srv >= 5 && o.srv >= o.raw * 0.5) return 'Most image loads here come from a server, not a browser (' + o.srv + ' of ' + o.raw + '). This site most likely copies banners to its own server, so the rotation is frozen there.';
const top = Math.max(0, ...Object.values(o.top || {}));
if (o.raw >= 50 && top >= o.raw * 0.8 && o.clicks <= o.raw * 0.01) return 'One loader made ' + Math.round(top / o.raw * 100) + '% of the ' + o.raw + ' image loads here and almost nobody clicks. This site most likely caches banners, so the rotation is frozen there.';
// more clicks than views alone is not enough (one visitor's reloads count once a minute, clicks are not deduped): a copy also leaves the clicks unmatched
if (o.clicks >= 10 && o.clicks > o.imps && o.matched / o.clicks < 0.5) return 'More clicks (' + o.clicks + ') than views we served (' + o.imps + '). This site shows a copy of the banner, so the rotation is frozen there and clicks go to the fallback.';
if (o.clicks >= 10 && o.matched / o.clicks < 0.3) return 'Only ' + Math.round(o.matched / o.clicks * 100) + '% of clicks here match a view. This site most likely caches banners, so the rotation is frozen there.';
return '';
}
// winner: among the live banners of one Banner Spin with at least WIN_MIN views each, the one with the best CTR (strictly ahead)
function winnerOf(rows) {
const q = rows.filter(r => r.imps >= WIN_MIN && r.ctr != null).sort((a, b) => b.ctr - a.ctr);
return q.length >= 2 && q[0].ctr > q[1].ctr ? q[0].id : 0;
}
const listOf = m => Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n }));
const dayRows = (days, sinceDay) => Object.entries(days).filter(([d]) => !sinceDay || d >= sinceDay).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks, bots: o.bots, botClicks: o.botClicks, servers: o.srv, conv: o.conv }));
const placementRows = hosts => Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), loads: o.raw, serverLoads: o.srv, caches: cacheFlag(o) }))
.filter(p => p.imps || p.clicks || p.loads).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30);
async function stats(owner, id) {
const s = findMine(owner, id); if (!s) return null;
const cnt = countsOf(s.id); const clicks = J.db.clicks.filter(c => c.s === s.id && !c.bot);
const per = {}; const at = (o, k) => (o[k] = o[k] || { imps: 0, clicks: 0, matched: 0, uniq: 0 });
const hosts = {}; const days = {};
for (const [day, d] of Object.entries(cnt)) {
for (const [b, n] of Object.entries(d.b)) { at(per, b).imps += n; at(days, day).imps += n; }
for (const [b, arr] of Object.entries(d.u)) at(per, b).uniq += arr.length;
for (const [hh, m] of Object.entries(d.h)) for (const n of Object.values(m)) at(hosts, hh).imps += n;
const A = agg([s], 0); const z = blank0();
const banners = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
const win = winnerOf(banners.filter(b => b.active)); for (const b of banners) b.winner = b.id === win;
const fb = A.per[s.id + ':0'] || z;
return { spin: pub(s), totals: { imps: A.T.imps, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, uniquesSampled: A.T.uniq, conversions: A.T.conv, bots: A.T.botClicks, botLoads: A.T.bots, serverLoads: A.T.srv },
banners, winner: win, winMin: WIN_MIN, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctrOf(fb) },
placements: placementRows(A.hosts), days: dayRows(A.days, ctDay(Date.now() - 30 * DAY)), country: listOf(A.country), device: listOf(A.device),
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
const blank0 = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0 });
// Reports screen: every Banner Spin the member owns over the last `days`, totals + per banner + per placement + day / country / device
async function summary(owner, days) {
const list = mine(owner); const n = Math.max(1, Math.min(365, Number(days) || 30)); const since = Date.now() - n * DAY;
const A = agg(list, since); const z = blank0(); const banners = [];
for (const s of list) {
const rows = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { spinId: s.id, spin: s.name, code: s.code, size: s.size, id: b.id, label: b.label || 'Banner ' + b.id, image: b.image, active: !!b.active, autoPaused: !!b.autoPaused, imps: o.imps, uniques: o.uniq, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
const win = winnerOf(rows.filter(r => r.active)); for (const r of rows) { r.winner = r.id === win; banners.push(r); }
}
for (const c of clicks) { const ok = c.m === 'exact' || c.m === 'note'; const o = at(per, c.b); o.clicks++; if (ok) o.matched++; const ho = at(hosts, c.h || '(none)'); ho.clicks++; if (ok) ho.matched++; const dd = at(days, ctDay(c.ts)); dd.clicks++; if (ok) dd.matched++; }
const ctr = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null; const mr = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
const conv = J.db.conv.filter(c => c.s === s.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } const convB = {}; for (const c of conv) convB[c.b] = (convB[c.b] || 0) + 1;
const banners = s.banners.map(b => { const o = per[b.id] || { imps: 0, clicks: 0, matched: 0, uniq: 0 }; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctr(o), matchRate: mr(o), conversions: convB[b.id] || 0 }; });
const fb = per[0] || { imps: 0, clicks: 0, matched: 0, uniq: 0 };
const tot = { imps: 0, clicks: clicks.length, matched: 0, uniq: 0 }; for (const o of Object.values(per)) { tot.imps += o.imps; tot.matched += o.matched; tot.uniq += o.uniq; }
const since = ctDay(Date.now() - 30 * DAY);
return { spin: pub(s), totals: { imps: tot.imps, clicks: tot.clicks, ctr: ctr(tot), matchRate: mr(tot), matched: tot.matched, unmatched: clicks.filter(c => c.m === 'none').length, uniquesSampled: tot.uniq, conversions: conv.length, bots: J.db.clicks.filter(c => c.s === s.id && c.bot).length },
banners, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctr(fb) },
placements: Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctr(o), matchRate: mr(o) })).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30),
days: Object.entries(days).filter(([d]) => d >= since).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
banners.sort((a, b) => b.imps - a.imps || b.clicks - a.clicks);
const spins = list.map(s => { let imps = 0, clicks = 0, conv = 0; for (const b of s.banners.concat([{ id: 0 }])) { const o = A.per[s.id + ':' + b.id]; if (o) { imps += o.imps; clicks += o.clicks; conv += o.conv; } } return { id: s.id, name: s.name, code: s.code, size: s.size, imps, clicks, ctr: imps ? Math.round(clicks / imps * 10000) / 100 : null, conversions: conv }; }).sort((a, b) => b.imps - a.imps);
return { count: list.length, totals: { imps: A.T.imps, uniques: A.T.uniq, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, conversions: A.T.conv, bots: A.T.bots, botClicks: A.T.botClicks, serverLoads: A.T.srv },
days: dayRows(A.days, ctDay(since)), country: listOf(A.country), device: listOf(A.device), banners: banners.slice(0, 50), placements: placementRows(A.hosts), spins, winMin: WIN_MIN,
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, c]) => ({ k, n: c })) };
}
// ── admin ──
@@ -372,5 +458,9 @@ function readImage(name) {
if (buf.length <= MAX_BYTES) { IMG.set(name, rec); IMG_BYTES += buf.length; while (IMG_BYTES > 32 * 1024 * 1024) { const [k, v] = IMG.entries().next().value; IMG.delete(k); IMG_BYTES -= v.buf.length; } }
return rec;
}
const _test = { notes: () => NOTES, flush, vkey };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, _test };
// raw access for health.js (phase 3): the same store and save, and where a banner image lives ({ file } on disk or { url })
const rawSpins = () => J.db.spins;
const save = () => J.save();
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
+104 -6
View File
@@ -10,7 +10,12 @@
const fs = require('fs');
const path = require('path');
let rotator = null, DATA_DIR = null, notify = null;
// Banner Spin (phase 3, 2026-10-20): the same pass also checks every live banner. Its IMAGE must load as an image
// (PNG / GIF / JPEG / WebP by magic bytes, an uploaded file read from disk, a pasted one fetched) at the Banner Spin's size,
// and its TARGET must pass check() above (a spin-link target only has to exist: its destinations are checked as spin
// links). Same counters: three failing checks pause the banner (b.active = false, b.autoPaused), two clean passes resume
// it, auto-paused ones are re-checked every 6 hours, and the last live banner of a Banner Spin is NEVER auto-paused.
let rotator = null, DATA_DIR = null, notify = null, bannerspin = null;
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36 LinkSpinHealth/1.0';
const TIMEOUT = 10000, SLOW = 6000, MAX_REDIRECTS = 5, PARALLEL = 4, FAILS_TO_PAUSE = 3, PASSES_TO_RESUME = 2;
const RECHECK_PAUSED = 6 * 3600 * 1000, MANUAL_GAP = 60 * 1000;
@@ -20,7 +25,7 @@ const L = { file: () => path.join(DATA_DIR, 'health-log.json'), db: null,
load() { try { this.db = JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch (e) { this.db = { events: [] }; } },
add(ev) { if (!this.db) this.load(); this.db.events.push(Object.assign({ ts: Date.now(), day: ctDay(Date.now()) }, ev)); if (this.db.events.length > 500) this.db.events = this.db.events.slice(-400); try { fs.writeFileSync(this.file(), JSON.stringify(this.db)); } catch (e) {} } };
function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; L.load(); }
function init(opts) { rotator = opts.rotator; DATA_DIR = opts.dataDir; notify = opts.notify || null; bannerspin = opts.bannerspin || null; L.load(); }
// one request with a hard timeout; returns the Response or throws
async function req(url, method, signalMs) {
@@ -116,12 +121,105 @@ async function runAll(jobs) {
let i = 0; const workers = new Array(Math.min(PARALLEL, jobs.length)).fill(0).map(async () => { while (i < jobs.length) { const j = jobs[i++]; try { await j(); } catch (e) {} } });
if (workers.length) await Promise.all(workers);
}
// ── Banner Spin banners ──
const MAGIC = buf => buf.length >= 12 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 ? 'image/png' : buf.length >= 6 && buf.slice(0, 4).toString('latin1') === 'GIF8' ? 'image/gif'
: buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff ? 'image/jpeg' : buf.length >= 12 && buf.slice(0, 4).toString('latin1') === 'RIFF' && buf.slice(8, 12).toString('latin1') === 'WEBP' ? 'image/webp' : '';
async function headBytes(res, max) {
if (!res.body) return Buffer.alloc(0);
const reader = res.body.getReader(); const chunks = []; let n = 0;
try { while (n < max) { const { done, value } = await reader.read(); if (done) break; chunks.push(Buffer.from(value)); n += value.length; } } catch (e) {}
try { reader.cancel().catch(() => {}); } catch (e) {}
return Buffer.concat(chunks);
}
// one banner image -> { state: ok | broken | size, note, w, h, ms }
async function checkImage(src, size) {
const t0 = Date.now(); const [W, H] = size || [0, 0];
const where = bannerspin && bannerspin.imageSource ? bannerspin.imageSource(src) : null;
if (!where) return { state: 'broken', note: 'No image address', w: 0, h: 0, ms: 0 };
let buf, type = '';
if (where.file) {
try { buf = fs.readFileSync(where.file); } catch (e) { return { state: 'broken', note: 'The uploaded image file is missing', w: 0, h: 0, ms: Date.now() - t0 }; }
} else {
try {
const { res } = await follow(where.url, 'GET');
if (res.status >= 400 || res.status < 200) { try { res.body && res.body.cancel && res.body.cancel().catch(() => {}); } catch (e) {} return { state: 'broken', note: 'The image address answers HTTP ' + res.status, w: 0, h: 0, ms: Date.now() - t0 }; }
type = String(res.headers.get('content-type') || '').toLowerCase();
buf = await headBytes(res, 65536);
} catch (e) { return { state: 'broken', note: (e && e.name === 'AbortError') ? 'The image did not load in 10 s' : 'The image address could not be reached', w: 0, h: 0, ms: Date.now() - t0 }; }
}
const mime = MAGIC(buf); const ms = Date.now() - t0;
if (!mime) return { state: 'broken', note: /^text\/html/.test(type) ? 'The image address returns a web page, not an image' : 'The file is not a readable image', w: 0, h: 0, ms };
const d = mime === 'image/webp' ? { w: 0, h: 0 } : bannerspin.dims(buf, mime);
if (d.w && d.h && W && (d.w !== W || d.h !== H)) return { state: 'size', note: 'The image is ' + d.w + 'x' + d.h + '; this Banner Spin is ' + W + 'x' + H, w: d.w, h: d.h, ms };
return { state: 'ok', note: d.w ? '' : 'Loads as an image (size not readable)', w: d.w, h: d.h, ms };
}
// one banner target -> the spin-link check shape. A spin link only has to still exist.
async function checkTarget(s, b) {
if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; return r ? { state: 'ok', code: 0, ms: 0, note: 'Spin link /r/' + r.code + ' (its pages are checked as spin links)' } : { state: 'dead', code: 0, ms: 0, note: 'The spin link this banner points at was deleted' }; }
if (!b.target) return { state: 'dead', code: 0, ms: 0, note: 'No target set' };
return check(String(b.target).replace(/\{[a-z0-9_]{1,24}\}/gi, 'x')); // macros filled with a placeholder, like a real click would
}
// apply both results to the banner: counters, auto-pause (never the last live banner), auto-resume
function applyBanner(s, b, img, tgt) {
const prev = b.health || {}; const now = Date.now();
const bad = img.state !== 'ok' || failing(tgt.state);
const fails = bad ? (prev.fails || 0) + 1 : 0, passes = bad ? 0 : (prev.passes || 0) + 1;
const note = img.state !== 'ok' ? img.note : failing(tgt.state) ? (tgt.state === 'parked' ? 'Target is a parked page' : 'Target page is down') + (tgt.note ? ' (' + tgt.note + ')' : '') : tgt.state === 'slow' ? 'Target is slow' + (tgt.note ? ' (' + tgt.note + ')' : '') : '';
b.health = { state: img.state !== 'ok' ? 'image' : tgt.state, note, checkedAt: now, fails, passes,
image: { state: img.state, note: img.note || '', w: img.w || 0, h: img.h || 0 }, target: { state: tgt.state, code: tgt.code || 0, ms: tgt.ms || 0, note: tgt.note || '' } };
if (b.active && !b.adminOff && fails >= FAILS_TO_PAUSE) {
const others = s.banners.filter(x => x !== b && x.active && !x.adminOff);
if (!others.length) { b.health.note = note + '. Kept live: it is the last live banner in this Banner Spin.'; return null; }
b.active = false; b.autoPaused = now; b.health.passes = 0;
L.add({ ev: 'pause', bs: s.id, b: b.id, url: b.image, state: b.health.state, note });
return { kind: 'paused', text: note + ', auto-paused ' + when(now) };
}
if (!b.active && b.autoPaused && passes >= PASSES_TO_RESUME) {
b.active = true; delete b.autoPaused; b.health.fails = 0;
L.add({ ev: 'resume', bs: s.id, b: b.id, url: b.image, state: b.health.state });
return { kind: 'resumed', text: 'Back up, resumed ' + when(now) };
}
return null;
}
async function tellBanner(s, b, change) {
if (!notify || !change || change.kind !== 'paused') return;
const esc = x => String(x).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>LinkSpin paused one banner in your Banner Spin <b>' + esc(s.name) + '</b> because it failed three checks in a row.</p>'
+ '<p>' + esc(b.label || 'Banner ' + b.id) + '<br>' + esc((b.health && b.health.note) || '') + '</p>'
+ '<p>Your other banners keep rotating. If it comes back, LinkSpin resumes it on its own after two clean checks. You can also fix the image or the target, or resume it yourself, under Links, Banner Spins.</p>';
try { await notify(s.owner, 'A banner in ' + s.name + ' was paused', html); } catch (e) {}
}
// the banner jobs for one pass. force = check auto-paused ones now too (admin "run checks"); onlyId = one Banner Spin
function bannerJobs(force, onlyId, onChange) {
if (!bannerspin || !bannerspin.rawSpins || (bannerspin.live && !bannerspin.live())) return [];
const now = Date.now(); const jobs = [];
for (const s of bannerspin.rawSpins()) {
if (s.adminOff || (onlyId && s.id !== Number(onlyId))) continue;
const size = bannerspin.SIZES[s.size];
for (const b of s.banners) {
if (b.adminOff) continue;
const due = (b.active) || (b.autoPaused && (force || !b.health || now - (b.health.checkedAt || 0) >= RECHECK_PAUSED));
if (!due) continue;
jobs.push(async () => { const [img, tgt] = await Promise.all([checkImage(b.image, size), checkTarget(s, b)]); const ch = applyBanner(s, b, img, tgt); onChange(); if (ch) await tellBanner(s, b, ch); });
}
}
return jobs;
}
// admin "run the checks now" for Banner Spins (no once-a-minute limit; auto-paused banners are re-checked at once)
let bannerRunning = false;
async function checkBannerSpins(opts) {
opts = opts || {}; if (bannerRunning) return { error: 'A check is already running.' }; bannerRunning = true;
let n = 0; try { const jobs = bannerJobs(true, opts.id, () => { n++; }); await runAll(jobs); } finally { bannerRunning = false; if (n && bannerspin) bannerspin.save(); }
return { ok: true, checked: n };
}
let running = false;
// the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by
async function tick() {
if (running || !rotator) return { skipped: true }; running = true;
const now = Date.now(); const jobs = []; let changed = false, n = 0;
const now = Date.now(); const jobs = []; let changed = false, n = 0, bn = 0;
try {
jobs.push(...bannerJobs(false, 0, () => { bn++; })); // Banner Spin banners, same pass, same 4-at-once limit
for (const r of rotator.rawRotations()) {
for (const d of r.destinations) {
const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED));
@@ -131,8 +229,8 @@ async function tick() {
if (r.fallback) jobs.push(async () => { const c = await check(r.fallback); r.fallbackHealth = { state: c.state, code: c.code, ms: c.ms, checkedAt: Date.now(), note: c.note, frameBlocked: !!c.frameBlocked }; changed = true; });
}
await runAll(jobs);
} finally { running = false; if (changed) rotator.save(); }
return { checked: n };
} finally { running = false; if (changed) rotator.save(); if (bn && bannerspin) bannerspin.save(); }
return { checked: n, banners: bn };
}
// "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback
const lastManual = new Map();
@@ -146,4 +244,4 @@ async function checkRotation(owner, id) {
return { ok: true, rotation: rotator.pub(r) };
}
function recent() { if (!L.db) L.load(); return L.db.events.slice(-50).reverse(); }
module.exports = { init, tick, check, checkRotation, recent };
module.exports = { init, tick, check, checkRotation, recent, checkImage, checkBannerSpins };
+7 -1
View File
@@ -218,6 +218,12 @@
</div>
<div class="pane" id="pane-content" hidden>
<!-- Banner Spin feature switch (2026-10-20): the whole feature off = every placement shows a neutral blank image and clicks go to each fallback -->
<div class="card" id="bsSwitchCard" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:12px">
<div style="flex:1;min-width:220px"><b>Banner Spin</b> <span class="st" id="bsSwitchState">...</span><div class="small muted" id="bsSwitchNote">Switching it off blanks every member's Banner Spin at once (a neutral blank image, clicks to each fallback). Members keep everything and it comes back as it was.</div></div>
<button type="button" class="btn small" id="bsSwitchBtn" disabled>...</button>
<button type="button" class="btn small sec" id="bsHealthBtn" title="Check every live banner's image and target now">Run banner checks</button>
</div>
<div class="ct-totals" id="ctTotals"></div>
<div class="card">
<div class="card-head"><h3>Everything members made</h3><span class="sub" id="ctSub">newest first</span></div>
@@ -472,6 +478,6 @@
</div>
<script src="/assets/common.js?v=20261018p25"></script>
<script src="/assets/admin.js?v=20261018e1"></script>
<script src="/assets/admin.js?v=20261020bs3"></script>
</body>
</html>
+17
View File
@@ -611,7 +611,24 @@
if ($('ctFrom').value) sp.set('from', $('ctFrom').value); if ($('ctTo').value) sp.set('to', $('ctTo').value);
if ($('ctFlagged').checked) sp.set('flagged', '1'); if (fresh === true) sp.set('fresh', '1');
CT.data = await api('/api/admin/content?' + sp.toString()); drawContent();
loadBsSwitch().catch(e => { $('bsSwitchState').textContent = 'could not load'; });
}
// ── Banner Spin feature switch (2026-10-20): the button for POST /api/admin/bannerspins { off }, plus "run the checks now" ──
async function loadBsSwitch() {
const r = await api('/api/admin/bannerspins'); const off = !!(r.settings && r.settings.off); const t = r.totals || {};
$('bsSwitchState').className = 'st ' + (off ? 'rejected' : 'active'); $('bsSwitchState').textContent = off ? 'switched off' : 'live';
const b = $('bsSwitchBtn'); b.textContent = off ? 'Switch Banner Spin back on' : 'Switch Banner Spin off'; b.dataset.off = off ? '1' : '0'; b.className = 'btn small' + (off ? '' : ' sec'); b.disabled = false;
$('bsSwitchNote').textContent = (off ? 'Off: every placement shows a neutral blank image and clicks go to each fallback. ' : 'Live. Switching it off blanks every member\'s Banner Spin at once (a neutral blank image, clicks to each fallback). ')
+ ctN(t.spins) + ' Banner Spin' + (t.spins === 1 ? '' : 's') + ', ' + ctN(t.banners) + ' banners. Members keep everything; it comes back exactly as it was.';
}
$('bsSwitchBtn').addEventListener('click', busy($('bsSwitchBtn'), async () => {
const turnOff = $('bsSwitchBtn').dataset.off !== '1';
if (turnOff && !await IAP.confirmBox('Switch Banner Spin off for every member? Every placement shows a blank image until you switch it back on.', { title: 'Switch Banner Spin off', ok: 'Switch it off', cancel: 'Keep it on' })) return;
await api('/api/admin/bannerspins', { off: turnOff }, 'POST'); IAP.status(turnOff ? 'Banner Spin is switched off.' : 'Banner Spin is live again.', 'ok'); await loadBsSwitch();
}));
$('bsHealthBtn').addEventListener('click', busy($('bsHealthBtn'), async () => {
const r = await api('/api/admin/bannerspins/health', {}, 'POST'); IAP.status('Checked ' + ctN(r.checked) + ' banner' + (r.checked === 1 ? '' : 's') + '.', 'ok'); await loadContent(true);
}));
const ctReload = (fresh) => loadContent(fresh).catch(e => IAP.status(e.message, 'bad'));
$('ctQ').addEventListener('input', () => { clearTimeout(CT.timer); CT.timer = setTimeout(() => { CT.page = 1; ctReload(); }, 250); });
['ctFrom', 'ctTo', 'ctFlagged'].forEach(id => $(id).addEventListener('change', () => { CT.page = 1; ctReload(); }));
+28 -6
View File
@@ -76,6 +76,18 @@
CR.tile({ k: 'Click match rate', v: t ? pct(t.matchRate) : (s.clicks ? Math.round(s.matched / s.clicks * 100) + '%' : '-') }), CR.tile({ k: 'Conversions', v: fmt(s.conversions) }),
CR.tile({ k: 'Live banners', v: s.banners.filter(b => b.active && !b.adminOff).length + ' / ' + s.banners.length })].join('');
}
// health line under each banner (phase 3): the 30-minute image + target check, auto-pause and auto-resume
const ctTime = ts => new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT';
function healthLine(b) {
const h = b.health;
if (b.adminOff) return '';
if (!h) return '<span class="muted bhl" data-bhealth="none">Not checked yet. LinkSpin checks each image and target every 30 minutes.</span>';
const bad = h.state === 'image' || h.state === 'dead' || h.state === 'parked';
if (b.autoPaused) return '<span class="bm bhl" data-bhealth="paused">Auto-paused ' + ctTime(b.autoPaused) + ': ' + esc(h.note) + '. It comes back on its own after two clean checks, or fix it and press Resume.</span>';
if (bad) return '<span class="bm bhl" data-bhealth="failing">' + esc(h.note) + (/Kept live/.test(h.note) ? '' : ' (' + h.fails + ' of 3 failed checks pause it)') + ' · checked ' + ctTime(h.checkedAt) + '</span>';
if (h.state === 'slow') return '<span class="wm bhl" data-bhealth="slow">' + esc(h.note) + ' · checked ' + ctTime(h.checkedAt) + '</span>';
return '<span class="okm bhl" data-bhealth="ok">Image and target OK · checked ' + ctTime(h.checkedAt) + '</span>';
}
const targetText = b => { if (b.link) { const r = ROT.find(x => x.id === b.link); return r ? 'Spin link: ' + r.name + ' (/r/' + r.code + ')' : 'Spin link (deleted)'; } return b.target; };
function renderBanners(s) {
const total = s.banners.filter(b => b.active && !b.adminOff).reduce((n, b) => n + b.weight, 0) || 1;
@@ -84,10 +96,11 @@
return '<div class="rw" data-bid="' + b.id + '"><div style="display:grid;gap:5px;min-width:0"><img class="bthumb" src="' + esc(b.image) + '" alt="" width="' + W + '" height="' + H + '" loading="lazy" referrerpolicy="no-referrer">'
+ '<div style="font-weight:700">' + esc(b.label || 'Banner ' + b.id) + (b.hours ? ' <button class="hchip set" type="button" data-bh="' + b.id + '">' + esc(LSHours.text(b.hours)) + '</button>' : '') + '</div>'
+ '<div class="mono muted" style="font-size:11px;overflow-wrap:anywhere">' + esc(targetText(b)) + '</div>'
+ '<div style="font-size:11px">' + (b.w ? '<span class="' + (b.warn ? 'wm' : 'okm') + '">' + b.w + 'x' + b.h + (b.bytes ? ', ' + kb(b.bytes) : '') + (b.warn ? ', not ' + esc(s.size) : ', fits') + '</span>' : '<span class="muted">pasted image, size not checked</span>') + '</div></div>'
+ '<div style="font-size:11px">' + (b.w ? '<span class="' + (b.warn ? 'wm' : 'okm') + '">' + b.w + 'x' + b.h + (b.bytes ? ', ' + kb(b.bytes) : '') + (b.warn ? ', not ' + esc(s.size) : ', fits') + '</span>' : '<span class="muted">pasted image, size not checked</span>') + '</div>'
+ '<div>' + healthLine(b) + '</div></div>'
+ '<div class="wrow"><div class="bar" style="width:60px"><i style="width:' + share + '%"></i></div><input class="field mono" type="number" min="1" max="100" value="' + b.weight + '" data-w="' + b.id + '" aria-label="Weight"><span class="mono muted" style="font-size:11px">' + share + '%</span></div>'
+ '<span class="r num"><span class="ml">Views </span>' + fmt(b.imps) + '</span><span class="r num"><span class="ml">Clicks </span>' + fmt(b.clicks) + '</span>'
+ '<span class="tag ' + (b.adminOff ? 'bad' : b.active ? 'ok' : 'dim') + '">' + (b.adminOff ? 'OFFLINE' : b.active ? 'LIVE' : 'PAUSED') + '</span>'
+ '<span class="tag ' + (b.adminOff ? 'bad' : b.autoPaused ? 'warn' : b.active ? 'ok' : 'dim') + '">' + (b.adminOff ? 'OFFLINE' : b.autoPaused ? 'AUTO-PAUSED' : b.active ? 'LIVE' : 'PAUSED') + '</span>'
+ '<span style="display:flex;gap:6px;justify-content:flex-end"><button class="btn sm" type="button" data-bh="' + b.id + '" title="Hours for this banner" aria-label="Hours for this banner"><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="' + b.id + '">' + (b.active ? 'Pause' : 'Resume') + '</button><button class="btn sm danger" type="button" data-x="' + b.id + '" aria-label="Remove">&times;</button></span></div>'
+ (BHE && BHE.sid === s.id && BHE.bid === b.id ? '<div class="rw edit" data-he="' + b.id + '"></div>' : ''); }).join('')
: '<div class="rw"><span class="muted">No banners yet. Add the first one below. Until then every placement shows the fallback.</span></div>';
@@ -207,12 +220,21 @@
async function loadStats(id) {
let st = STATS[id]; if (!st) { try { st = await CR.get('/api/my/bannerspins/' + id + '/stats'); } catch (e) { return; } STATS[id] = st; setTimeout(() => { delete STATS[id]; }, 30000); }
if (SEL !== id) return; const s = cur(); if (s) renderTiles(s, st);
const row = (name, o, extra) => '<div class="rw"><span style="overflow-wrap:anywhere">' + name + '</span><span class="r num">' + fmt(o.imps) + '</span><span class="r num">' + fmt(o.clicks) + '</span><span class="r num">' + (o.ctr == null ? '-' : o.ctr + '%') + '</span><span class="r num">' + (o.matchRate == null ? '-' : o.matchRate + '%') + '</span><span class="r num">' + (extra == null ? '' : fmt(extra)) + '</span></div>';
$('bsStB').innerHTML = st.banners.length ? st.banners.map(b => row('<img src="' + esc(b.image) + '" alt="" style="max-height:28px;max-width:120px;vertical-align:middle;margin-right:6px" referrerpolicy="no-referrer">' + esc(b.label || 'Banner ' + b.id), b, b.conversions)).join('') + (st.fallback.imps || st.fallback.clicks ? row('<span class="muted">Fallback</span>', Object.assign({ matchRate: null }, st.fallback), null) : '') : '<div class="rw"><span class="muted">No banners yet.</span></div>';
$('bsStP').innerHTML = st.placements.length ? st.placements.map(p => row(esc(p.host), p, null)).join('') : '<div class="rw"><span class="muted">No views yet. Put the code on a page and load it.</span></div>';
// seven columns: name, views, second number (uniques for a banner, every image load for a placement), clicks, CTR, matched, last
const cell = (label, v) => '<span class="r num"><span class="ml">' + label + ' </span>' + v + '</span>';
const row = (name, o, second, secondLabel, last, lastLabel) => '<div class="rw"><span style="overflow-wrap:anywhere">' + name + '</span>' + cell('Views', fmt(o.imps)) + cell(secondLabel, second == null ? '-' : fmt(second)) + cell('Clicks', fmt(o.clicks))
+ cell('CTR', o.ctr == null ? '-' : o.ctr + '%') + cell('Matched', o.matchRate == null ? '-' : o.matchRate + '%') + '<span class="r num">' + (last == null ? '' : (lastLabel ? '<span class="ml">' + lastLabel + ' </span>' : '') + last) + '</span></div>';
$('bsStB').innerHTML = st.banners.length ? st.banners.map(b => row('<img src="' + esc(b.image) + '" alt="" style="max-height:28px;max-width:120px;vertical-align:middle;margin-right:6px" referrerpolicy="no-referrer">' + esc(b.label || 'Banner ' + b.id) + (b.winner ? '<span class="bswin" data-winner="' + b.id + '">WINNER</span>' : ''), b, b.uniques, 'Unique', fmt(b.conversions), 'Conv')).join('')
+ (st.fallback.imps || st.fallback.clicks ? row('<span class="muted">Fallback</span>', Object.assign({ matchRate: null }, st.fallback), null, 'Unique', null) : '') : '<div class="rw"><span class="muted">No banners yet.</span></div>';
const wm = st.winMin || 1000;
$('bsWinNote').textContent = st.winner ? 'WINNER = the best click rate among banners with at least ' + fmt(wm) + ' views each. LinkSpin never changes the weights for you: raise the winner or pause the rest when you are ready.' : 'A WINNER badge appears once two or more live banners have ' + fmt(wm) + ' views each and one leads on click rate. Unique viewers are counted per day from a sample.';
$('bsStP').innerHTML = st.placements.length ? st.placements.map(p => row(esc(p.host === '(none)' ? 'No referrer (email, apps, privacy settings)' : p.host) + (p.caches ? '<span class="bscache" data-caches="' + esc(p.host) + '"><b>Caches banners:</b> ' + esc(p.caches) + '</span>' : ''), p, p.loads, 'Loads', p.caches ? '<span class="tag warn" title="' + esc(p.caches) + '">CACHED</span>' : '', '')).join('') : '<div class="rw"><span class="muted">No views yet. Put the code on a page and load it.</span></div>';
const kv = (rows, empty) => rows && rows.length ? rows.map(x => '<span>' + 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">' + empty + '</span><span></span><span></span>';
$('bsStC').innerHTML = kv(st.country, 'no clicks yet'); $('bsStD').innerHTML = kv(st.device, 'no clicks yet');
$('bsStBots').textContent = 'Shown separately and never counted as views or clicks: ' + fmt(st.totals.botLoads || 0) + ' bot and prefetch image loads, ' + fmt(st.totals.serverLoads || 0) + ' loads by servers or mail image proxies, ' + fmt(st.totals.bots || 0) + ' bot clicks.';
const days = st.days || []; const dmax = Math.max(1, ...days.map(d => d.imps));
$('bsDayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('bsDayBars').innerHTML = days.map(d => '<i style="height:' + Math.round(d.imps / dmax * 100) + '%" title="' + d.day + ' · ' + d.imps + ' views, ' + d.clicks + ' clicks"></i>').join('');
$('bsDayBars').innerHTML = days.map(d => '<i style="height:' + Math.round(d.imps / dmax * 100) + '%" title="' + d.day + ' · ' + d.imps + ' views, ' + d.clicks + ' clicks, ' + ((d.bots || 0) + (d.servers || 0)) + ' bot or server loads"></i>').join('');
$('bsDayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no views recorded yet</span>';
const t = st.totals; $('bsStNote').textContent = 'Views are counted on the server: bots and link previews are left out and one visitor reloading counts once a minute per banner. Matched = clicks we could tie to the banner that visitor saw (' + fmt(t.matched) + ' matched, ' + fmt(t.unmatched) + ' went to the fallback). About ' + fmt(t.uniquesSampled) + ' unique visitors (sampled).';
}
+16 -1
View File
@@ -20,7 +20,10 @@
CR.tile({ k: 'Bots dropped', v: fmt(t.bots), series: sb, delta: CR.delta(b1, b0, 'vs prior'), note: t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : '' }),
CR.tile({ k: 'Joins', v: fmt(t.joins), note: t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : '' }),
CR.tile({ k: 'Buyers', v: fmt(t.purchases), hi: true, note: t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : '' }),
CR.tile({ k: 'Partner conversions', v: fmt(t.external) })].join('');
CR.tile({ k: 'Partner conversions', v: fmt(t.external) }),
// Banner Spin totals beside spin links (2026-10-20)
CR.tile({ k: 'Banner views', v: fmt(((s.bannerSpins || {}).totals || {}).imps), note: ((s.bannerSpins || {}).count || 0) + ' Banner Spin' + (((s.bannerSpins || {}).count || 0) === 1 ? '' : 's') }),
CR.tile({ k: 'Banner clicks', v: fmt(((s.bannerSpins || {}).totals || {}).clicks), note: ((s.bannerSpins || {}).totals || {}).ctr != null ? s.bannerSpins.totals.ctr + '% CTR' : '' })].join('');
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => Math.max(d.u, d.b)));
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('dayBars').innerHTML = days.map(d => '<i class="' + (days.length >= 3 && d.u === dmax && d.u ? 'hi' : d.u ? '' : 'dim') + '" style="height:' + Math.round(d.u / dmax * 100) + '%" title="' + d.day + ' · ' + d.u + ' unique, ' + d.b + ' bots"></i>').join('');
@@ -52,6 +55,18 @@
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>';
// -- Banner Spins (2026-10-20): views by Central day (bots and servers as the lighter bar), per banner with the winner, per placement with the cache flag
const bs = s.bannerSpins || { totals: {}, days: [], banners: [], placements: [], country: [], device: [] }; const bt = bs.totals || {};
// outer bar = views + bot / server loads, inner lighter share = the bot / server part
dayBars('bsBars', 'bsAxis', bs.days, d => d.imps + (d.bots || 0) + (d.servers || 0), d => (d.bots || 0) + (d.servers || 0), 'no banner views yet');
$('bsTiles').innerHTML = mini([['Views', fmt(bt.imps)], ['Clicks', fmt(bt.clicks)], ['CTR', bt.ctr == null ? '-' : bt.ctr + '%'], ['Match rate', bt.matchRate == null ? '-' : bt.matchRate + '%'], ['Unique (daily)', fmt(bt.uniques)], ['Conversions', fmt(bt.conversions)]]);
$('bsCountry').innerHTML = kv(bs.country, 0); $('bsDevice').innerHTML = kv(bs.device, 0);
$('bsBotNote').textContent = 'Never counted as views or clicks, shown here so you can see them: ' + fmt(bt.bots) + ' bot and prefetch image loads, ' + fmt(bt.serverLoads) + ' loads by servers or mail image proxies, ' + fmt(bt.botClicks) + ' bot clicks.';
$('bsRowsB').innerHTML = (bs.banners || []).length ? bs.banners.map(x => '<div class="rw"><a href="/links#b' + x.spinId + '" style="text-decoration:none;color:var(--ink)"><b>' + esc(x.label) + '</b>' + (x.winner ? '<span class="bswin" data-winner="' + x.spinId + ':' + x.id + '">WINNER</span>' : '') + '<br><span class="mono muted" style="font-size:11px">' + esc(x.spin) + ' · ' + esc(x.size) + (x.autoPaused ? ' · <span class="warn">auto-paused</span>' : x.active ? '' : ' · paused') + '</span></a><span class="r num">' + fmt(x.imps) + '</span><span class="r num">' + fmt(x.uniques) + '</span><span class="r num">' + fmt(x.clicks) + '</span><span class="r num">' + (x.ctr == null ? '-' : x.ctr + '%') + '</span><span class="r num">' + fmt(x.conversions) + '</span></div>').join('')
: '<div class="rw"><span class="muted">' + (bs.count ? 'No banners yet.' : 'No Banner Spins yet. <a href="/links#b">Make one</a> (opens with your own $25 package).') + '</span></div>';
$('bsWinNote').textContent = 'WINNER = the best click rate in its Banner Spin once two or more live banners have ' + fmt(bs.winMin || 1000) + ' views each. Unique viewers are counted per day from a sample.';
$('bsRowsP').innerHTML = (bs.placements || []).length ? bs.placements.slice(0, 15).map(x => '<div class="rw"><span style="overflow-wrap:anywhere"><b>' + esc(x.host === '(none)' ? 'No referrer (email, apps)' : x.host) + '</b>' + (x.caches ? ' <span class="tag warn">CACHED</span><span class="bscache" data-caches="' + esc(x.host) + '">' + esc(x.caches) + '</span>' : '') + '</span><span class="r num">' + fmt(x.imps) + '</span><span class="r num">' + fmt(x.clicks) + '</span><span class="r num">' + (x.ctr == null ? '-' : x.ctr + '%') + '</span><span class="r num">' + (x.matchRate == null ? '-' : x.matchRate + '%') + '</span></div>').join('')
: '<div class="rw"><span class="muted">No placements yet. Put a Banner Spin\'s code on a page and its host shows here.</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');
+8 -5
View File
@@ -72,8 +72,10 @@
.tierbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:12.5px}
.modes{display:grid;gap:8px} .modes label{display:flex;gap:8px;align-items:flex-start;cursor:pointer} .modes input{margin-top:3px}
.bsr .ml{display:none}
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 90px 80px 70px 80px 70px}
@media (max-width:900px){.bsr .ml{display:inline;color:var(--muted);font-size:11px}.bsr .rw .r{text-align:left}.bsr .hd,.st3 .hd{display:none}.bsr .rw{grid-template-columns:1fr 1fr}.st3 .rw{grid-template-columns:1fr 1fr 1fr}.addg{grid-template-columns:1fr}}
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 80px 70px 70px 64px 74px 56px}
.st3 .ml{display:none} .bhl{font-size:11.5px} .bswin{background:var(--ok);color:#fff;border-radius:3px;padding:1px 6px;font-size:10px;font-weight:700;letter-spacing:.06em;margin-left:6px;vertical-align:middle}
.bscache{display:block;margin-top:3px;font-size:11px;color:var(--warn)} .bsbreak{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
@media (max-width:900px){.bsr .ml,.st3 .ml{display:inline;color:var(--muted);font-size:11px}.bsr .rw .r,.st3 .rw .r{text-align:left}.bsr .hd,.st3 .hd{display:none}.bsr .rw{grid-template-columns:1fr 1fr}.st3 .rw{grid-template-columns:1fr 1fr 1fr}.st3 .rw>:first-child{grid-column:1/-1}.addg{grid-template-columns:1fr}.bsbreak{grid-template-columns:1fr}}
@media (max-width:760px){.bsr .rw{grid-template-columns:1fr}.tgt{grid-template-columns:1fr}.vsw{padding:8px 10px 0}.vsw button{padding:6px 10px;font-size:14px}}
</style>
</head>
@@ -221,8 +223,9 @@
<div class="note" style="margin-top:10px"><b>Paid ad networks</b> copy your image to their own servers when you upload a creative, so it will not rotate there. Use the script tag or the image address on sites, blogs, forums and safelists that load the image from us.</div>
</div>
<div id="bs-stats" hidden>
<div class="panel"><h2>By banner</h2><div class="tbl st3"><div class="hd"><span>Banner</span><span class="r">Views</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span class="r">Conv</span></div><div id="bsStB"></div></div></div>
<div class="panel" style="margin-top:12px"><h2>By placement (the page the banner sits on)</h2><div class="tbl st3"><div class="hd"><span>Placement</span><span class="r">Views</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span></span></div><div id="bsStP"></div></div></div>
<div class="panel"><h2>By banner</h2><div class="tbl st3"><div class="hd"><span>Banner</span><span class="r">Views</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span class="r">Conv</span></div><div id="bsStB"></div></div><div class="muted" style="font-size:11.5px;margin-top:6px" id="bsWinNote"></div></div>
<div class="panel" style="margin-top:12px"><h2>By placement (the page the banner sits on)</h2><div class="tbl st3"><div class="hd"><span>Placement</span><span class="r">Views</span><span class="r">Loads</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span><span></span></div><div id="bsStP"></div></div></div>
<div class="panel" style="margin-top:12px"><h2>Clicks by country and device</h2><div class="bsbreak"><div class="kv" id="bsStC"></div><div class="kv" id="bsStD"></div></div><div class="muted" style="font-size:11.5px;margin-top:6px" id="bsStBots"></div></div>
<div class="panel" style="margin-top:12px"><h2>Views by day, Central time, last 30</h2><div class="bars" id="bsDayBars"></div><div class="axis" id="bsDayAxis"></div><div class="muted" style="font-size:11.5px" id="bsStNote"></div></div>
</div>
</div>
@@ -239,6 +242,6 @@
</div>
<script src="/assets/cr-shell.js?v=20261018c"></script>
<script src="/assets/links.js?v=20261018bs"></script>
<script src="/assets/banner-spin.js?v=20261018bs"></script>
<script src="/assets/banner-spin.js?v=20261020bs3"></script>
</body>
</html>
+21 -2
View File
@@ -19,8 +19,10 @@
.bars.stack i{position:relative}.bars.stack i b{position:absolute;left:0;right:0;bottom:0;display:block;background:var(--line);border-radius:2px 2px 0 0}.bars i.ghost{background:var(--line)}
.mini{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin-top:10px}.mini .m{background:var(--panel-2);border:1px solid var(--line);border-radius:6px;padding:8px 10px;display:grid;gap:2px}.mini .m .k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.mini .m .v{font-family:var(--display);font-weight:700;font-size:20px;color:var(--ink);font-variant-numeric:tabular-nums}
.pages .hd,.pages .rw,.zones .hd,.zones .rw{grid-template-columns:minmax(0,1fr) 60px 60px 60px 60px;gap:8px}
.bsb .hd,.bsb .rw{grid-template-columns:minmax(0,1fr) 60px 60px 56px 56px 50px;gap:8px} .bsp .hd,.bsp .rw{grid-template-columns:minmax(0,1fr) 70px 60px 60px 64px;gap:8px}
.bswin{background:var(--ok);color:#fff;border-radius:3px;padding:1px 6px;font-size:10px;font-weight:700;letter-spacing:.06em;margin-left:6px} .bscache{display:block;font-size:11px;color:var(--warn);margin-top:2px}
.srcs .hd,.srcs .rw{grid-template-columns:minmax(0,1fr) 70px 70px 60px;gap:8px} .plc .hd,.plc .rw{grid-template-columns:minmax(0,1fr) 70px 60px;gap:8px}
@media (max-width:900px){.two,.grid2,.sect{grid-template-columns:1fr}.body{padding:12px 16px}.mini{grid-template-columns:repeat(2,minmax(0,1fr))}.pages .hd,.pages .rw,.zones .hd,.zones .rw{grid-template-columns:minmax(0,1fr) 48px 48px 48px 48px;gap:6px;padding:10px 12px;font-size:12px}}
@media (max-width:900px){.two,.grid2,.sect{grid-template-columns:1fr}.body{padding:12px 16px}.mini{grid-template-columns:repeat(2,minmax(0,1fr))}.pages .hd,.pages .rw,.zones .hd,.zones .rw{grid-template-columns:minmax(0,1fr) 48px 48px 48px 48px;gap:6px;padding:10px 12px;font-size:12px}.bsb .hd,.bsb .rw{grid-template-columns:minmax(0,1fr) 44px 44px 40px 44px 34px;gap:5px;padding:10px 12px;font-size:12px}.bsp .hd,.bsp .rw{grid-template-columns:minmax(0,1fr) 48px 44px 44px 48px;gap:6px;padding:10px 12px;font-size:12px}}
</style>
</head>
<body>
@@ -58,6 +60,23 @@
<div class="panel"><h2>By traffic source</h2><div class="tbl srcs"><div class="hd"><span>Source</span><span class="r">Clicks</span><span class="r">Unique</span><span class="r">Conv.</span></div><div id="tsRows"></div></div><div class="muted" style="margin-top:8px">A click counts for a source when the link it hit was pointed at that source at the time. Conversions are joins, leads, wallets, purchases and partner reports matched to those clicks. <a href="/sources">Open Sources</a></div></div>
<div class="panel"><h2>Placements</h2><div class="tbl plc"><div class="hd"><span>Source · placement</span><span class="r">Clicks</span><span class="r">Conv.</span></div><div id="plRows"></div></div><div class="muted" style="margin-top:8px">The value the network's zone, placement, site, campaign, creative, banner or keyword macro carried on the click, top 12. Use it to cut the placements that click and never convert.</div></div>
</div>
<!-- Banner Spins: one image URL + one click URL rotating the member's banners; views, clicks, CTR, match rate, placements (2026-10-20) -->
<div class="sec">Banner Spins</div>
<div class="two sect" id="bsSect">
<div class="panel">
<div class="ph"><h2>Banner views by day</h2><div class="legend"><span><i style="background:var(--accent)"></i>views</span><span><i style="background:var(--line)"></i>bots and servers</span></div></div>
<div class="bars" id="bsBars" style="height:150px"></div><div class="axis" id="bsAxis"></div>
<div class="mini" id="bsTiles"></div>
<div class="grid2" style="margin-top:12px">
<div><div class="sec" style="margin-bottom:6px">Clicks by country</div><div class="kv" id="bsCountry"></div></div>
<div><div class="sec" style="margin-bottom:6px">Clicks by device</div><div class="kv" id="bsDevice"></div></div>
</div>
<div class="muted" id="bsBotNote" style="margin-top:8px"></div>
</div>
<div class="panel"><h2>By banner</h2><div class="tbl bsb"><div class="hd"><span>Banner</span><span class="r">Views</span><span class="r">Unique</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Conv.</span></div><div id="bsRowsB"></div></div>
<div class="muted" style="margin-top:8px" id="bsWinNote"></div></div>
</div>
<div class="panel"><h2>Banner placements</h2><div class="tbl bsp"><div class="hd"><span>Placement (the page the banner sits on)</span><span class="r">Views</span><span class="r">Clicks</span><span class="r">CTR</span><span class="r">Matched</span></div><div id="bsRowsP"></div></div><div class="muted" style="margin-top:8px">Matched = clicks we could tie to the banner that visitor saw; the rest went to the fallback. A placement marked CACHED copies banners to its own server, so the rotation is frozen there. <a href="/links#b">Open Banner Spins</a></div></div>
<!-- Zones: ad-slot impressions on the member's own sites and the credits they earned (2026-10-10) -->
<div class="sec">Zones</div>
<div class="two sect">
@@ -71,6 +90,6 @@
</div>
</div>
<script src="/assets/cr-shell.js?v=20261018c"></script>
<script src="/assets/reports.js?v=20261012a"></script>
<script src="/assets/reports.js?v=20261020bs3"></script>
</body>
</html>
+11 -2
View File
@@ -581,7 +581,7 @@ async function boot() {
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources });
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
health.init({ rotator, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) });
health.init({ rotator, bannerspin, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) });
setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000);
setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000);
setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
@@ -2297,6 +2297,11 @@ const server = http.createServer(async (req, res) => {
if (b.off != null || b.grant) { const r = bannerspin.setGlobal(b); content.invalidate(); return json(res, r.error ? 400 : 200, r); }
return json(res, 200, { spins: bannerspin.adminAll(), settings: bannerspin.settings(), totals: bannerspin.totals() }, { 'Cache-Control': 'no-store' });
}
// Banner Spin health checks now (phase 3, 2026-10-20): { id } for one Banner Spin, else all; auto-paused banners are re-checked at once
if (p === '/api/admin/bannerspins/health' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
const b = await readBody(req); const r = await health.checkBannerSpins({ id: Number(b.id) || 0 }); content.invalidate(); return json(res, r.error ? 429 : 200, r);
}
m = /^\/api\/admin\/bannerspins\/(\d+)$/.exec(p);
if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
@@ -2419,7 +2424,9 @@ const server = http.createServer(async (req, res) => {
const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30));
// spins (the rotator summary, spread at the top level so older report screens keep working) + pages + zones (2026-10-10)
const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]);
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, days: spins.days, range: days }), { 'Cache-Control': 'no-store' });
// Banner Spins beside spin links (phase 3, 2026-10-20)
let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); }
return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days }), { 'Cache-Control': 'no-store' });
}
// -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs.
if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' });
@@ -2770,6 +2777,8 @@ const server = http.createServer(async (req, res) => {
let items = [];
try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {}
// a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15)
// built-in lessons shipped with the code (catalog/training.json, Banner Spin 2026-10-20): appended unless the volume list already has the same id
try { const extra = JSON.parse(fs.readFileSync(path.join(__dirname, 'catalog', 'training.json'), 'utf8')); if (Array.isArray(extra)) for (const it of extra) if (it && it.id && !items.some(x => x && x.id === it.id)) items.push(it); } catch (e) {}
const scT = siteConfig(); items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL)));
if (!items.length) items = [{ title: 'Getting started with LinkSpin',
desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.',