Compare commits

...

6 Commits

Author SHA1 Message Date
martbost a736d68c30 Merge LinkSpin knowledge-base chatbot (Banner Spin answer moved into a KB entry)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:52:02 -05:00
martbost 32c85c4fae Merge Banner Spin phases 3-4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:50:02 -05:00
martbost f404749fb0 Banner health: a size mismatch is a warning, not an auto-pause (the builder allows it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:50:00 -05:00
martbost d9342d8141 Banner Spin phase 4: chatbot, training lesson, promo tools, release note draft, QA
- chatbot.js: canned Banner Spin answer (ahead of the ad-edit and spin-link answers) + FACTS (what it is, tiers, embeds, matching, Gmail and paid-network limits, reports, health); KNOWLEDGE_DATE 2026-10-20.
- Training: catalog/training.json ships a written Banner Spin lesson, appended to /api/training unless the volume list has the same id; lesson text keeps its paragraphs (pre-line).
- Promo tools: "What is Banner Spin?" in the objection bank + an X post.
- docs/release-drafts/2026-10-20-banner-spin.json: release note in the releases store shape, NOT published.
- qa/bannerspin.mjs: health auto-pause/resume with a corrupted upload, a dead target and the last-live rule; winner; bots/servers apart; caches flag; source postback; Reports API + screen; admin switch button; chatbot; training; promo; draft. 75/75.
- Cache tags bumped: banner-spin.js, reports.js, admin.js, my.js, promo.js (20261020bs3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:39:52 -05:00
martbost f93bca81a7 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>
2026-10-20 05:39:50 -05:00
martbost 541457bc24 Chat knowledge base: the assistant answers from maintained entries (port of InstantAdPay's kb.js)
- kb.js: entries { id, title, questions, answer, tags, pattern, handoff, order, source, updated } in DATA_DIR/kb.json (temp file + rename). BM25 over title, question variants and tags (answer at a low weight) with word bigrams; the top hits go into the system prompt as KNOWLEDGE BASE, and when nothing fits the prompt says to answer "I'm not sure, ask support" (Help at SITE_URL/help).
- One source: chatbot.js CANNED seeds the KB (ids c-*, regex = instant-answer pattern, same first-match order); kb-seed.js seeds the network notes from the home page, the wallets guide FAQ, the earning guide and the Coinbase support reply in LinkSpin wording (f-*). The fast path serves the KB entry; the in-code CANNED only answers if the KB store fails. Unedited seeds follow code changes, edited ones are left alone, deleted seeds stay deleted.
- Admin > Knowledge base: list, search, filter by source, add, edit, delete, Try a question. Em dashes in admin input become commas.
- chatbot.js: reasoning off for deepseek (as on IAP), keepalive-padded OpenRouter replies parsed, OPENROUTER_URL override for tests, KNOWLEDGE_DATE 2026-10-20. New public GET /api/chat/kb-stamp.
- QA: qa/kb-retrieval.cjs (12 sample questions rank the right entry first), qa/kb-chat.mjs (local copy + mock OpenRouter), bash qa/run.sh kb; walk lists admin#kb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:38:46 -05:00
23 changed files with 2274 additions and 1122 deletions
+122 -32
View File
@@ -28,7 +28,12 @@
// below a tier keeps everything serving; it only stops new ones. // 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 // 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'; 'use strict';
const fs = require('fs'); const fs = require('fs');
const path = require('path'); 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; } 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 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(' ')); 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 // 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 ''; } } 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); } 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 ── // ── 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) { 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; 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); 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; 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) { function mergeInto(base, add) {
for (const [sid, days] of Object.entries(add.d)) { const s = base.d[sid] = base.d[sid] || {}; 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 [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 [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 [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, 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; return base;
} }
function flush() { 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 || '', 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 || '', 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, 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 || {}); 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)); } 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.' }; 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.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.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.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.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; } 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; } 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) }; 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 off = s.paused || !rotator.isOn(s.hours, cell);
const b = off ? null : pick(s, cell, v); const b = off ? null : pick(s, cell, v);
const out = b ? { banner: b } : (s.fallbackImage ? { fallback: true } : { blank: true, fallback: true }); 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); const bid = b ? b.id : 0; const host = hostOf(req);
note(v, s.id, host, bid); note(v, s.id, host, bid);
const k = v + '|' + s.id + '|' + bid; const last = SEEN.get(k); 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 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) {} 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 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); 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 }); 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); 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 || '' }; 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) { async function stats(owner, id) {
const s = findMine(owner, id); if (!s) return null; 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 A = agg([s], 0); const z = blank0();
const per = {}; const at = (o, k) => (o[k] = o[k] || { imps: 0, clicks: 0, matched: 0, uniq: 0 }); 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 hosts = {}; const days = {}; const win = winnerOf(banners.filter(b => b.active)); for (const b of banners) b.winner = b.id === win;
for (const [day, d] of Object.entries(cnt)) { const fb = A.per[s.id + ':0'] || z;
for (const [b, n] of Object.entries(d.b)) { at(per, b).imps += n; at(days, day).imps += n; } 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 },
for (const [b, arr] of Object.entries(d.u)) at(per, b).uniq += arr.length; banners, winner: win, winMin: WIN_MIN, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctrOf(fb) },
for (const [hh, m] of Object.entries(d.h)) for (const n of Object.values(m)) at(hosts, hh).imps += n; 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 })) };
} }
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 blank0 = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0 });
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; // Reports screen: every Banner Spin the member owns over the last `days`, totals + per banner + per placement + day / country / device
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; async function summary(owner, days) {
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 list = mine(owner); const n = Math.max(1, Math.min(365, Number(days) || 30)); const since = Date.now() - n * DAY;
const fb = per[0] || { imps: 0, clicks: 0, matched: 0, uniq: 0 }; const A = agg(list, since); const z = blank0(); const banners = [];
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; } for (const s of list) {
const since = ctDay(Date.now() - 30 * DAY); 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 }; });
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 }, const win = winnerOf(rows.filter(r => r.active)); for (const r of rows) { r.winner = r.id === win; banners.push(r); }
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), banners.sort((a, b) => b.imps - a.imps || b.clicks - a.clicks);
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 })) }; 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 ── // ── 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; } } 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; return rec;
} }
const _test = { notes: () => NOTES, flush, vkey }; // raw access for health.js (phase 3): the same store and save, and where a banner image lives ({ file } on disk or { url })
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 }; 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 };
+9
View File
@@ -0,0 +1,9 @@
[
{
"id": "banner-spin",
"group": "Banner Spin",
"title": "Banner Spin: one banner slot, a whole campaign",
"desc": "Banner Spin gives you one image address and one click address that rotate up to 25 banners, each with its own target page or spin link. Put it in one banner slot on a traffic exchange, a safelist, a forum signature or your own site once, then change the banners from your Control Room whenever you like. Nobody has to update anything on their side.\n\nWho gets it. It is a free add-on that opens with your own package of $25 or more. Starter holds 2 Banner Spins with 5 banners each. Builder (level 2 open, 2 qualifying buyers) holds 5 with 15 each. Leader (level 3 open, 5 qualifying buyers) holds 10 with 25 each. If you drop below a tier, everything you built keeps serving; you just cannot add more until you are back.\n\nStep 1, name and size. Open Links, switch to Banner Spins and press New Banner Spin. Pick one size: a slot on an exchange has one size, so every banner in a Banner Spin should be that exact size (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250 or 320x50). Set a fallback page: that is where a click goes when we cannot tell which banner the visitor saw.\n\nStep 2, add banners. Upload a JPG, PNG or GIF (animated is fine, 150 KB at most) or paste an https image address. The builder previews it at real size and warns you when it is the wrong size. Pick where a click goes: any page, or one of your own spin links, so a banner can rotate pages behind it too.\n\nStep 3, weights and mode. A banner with weight 20 shows twice as often as one with 10. Random by weight picks again on every view. One per visitor shows the same person the same banner all day, which keeps a split test clean on exchanges that reload pages. You can also give the whole Banner Spin, or one banner, its own hours.\n\nStep 4, get the code. Open Get the code and copy the embed that fits the place: the image address plus click address for exchanges, safelists and downline builders; the HTML snippet for your own site or blog; the script tag wherever scripts are allowed (it writes the banner and its own link together, so every click lands on the right target); the forum code for signatures. Every link domain answers every code, so if one domain ever has trouble you swap only the domain.\n\nWhere it will not rotate. Paid ad networks copy your image to their own servers when you upload a creative, so it freezes on one banner there: upload real banners to them instead. Gmail and some mail apps fetch images once through their own proxy, so most email readers see one banner and their clicks go to the fallback. For email, use a Banner Spin with a single banner (still tracked) and swap it when you want a change.\n\nReading the numbers. The Stats tab and the Reports screen show views, unique viewers, clicks, click rate, match rate and conversions for every banner and every placement (the page your banner sits on), by day, country and device. Bots, link previews and servers are never counted as views; they are shown on their own line. A WINNER badge appears once two or more live banners have 1,000 views each and one leads on click rate. LinkSpin never changes your weights for you: raise the winner or pause the rest when you are ready. A placement marked CACHED copies banners to its own server, so the rotation is frozen there; spend your credits elsewhere.\n\nHealth checks. Every 30 minutes LinkSpin checks each live banner: the image must load as an image of the right size, and its target must not be dead or parked. Three failures in a row pause that banner and it comes back on its own after two clean checks. The last live banner in a Banner Spin is never paused. You see the status on every banner row.\n\nTeach it forward. When someone in your line buys their first $25 package, show them this lesson and help them build their first Banner Spin with two banners for the same offer. Two weeks of numbers tell them which banner to keep.",
"docUrl": "/links#b"
}
]
+114 -42
View File
@@ -7,18 +7,27 @@
// //
// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED answers and FACTS below in the same commit. // HOUSE RULE: whenever a site feature changes, update BOTH the CANNED answers and FACTS below in the same commit.
// Plain words, no em dashes, never a promise of income. // Plain words, no em dashes, never a promise of income.
//
// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is the one
// source the assistant answers from. Each CANNED regex becomes its entry's instant-answer pattern (same order,
// first match wins), and for everything else the best-matching entries go into the system prompt. Admin >
// Knowledge base edits entries; an edited entry is no longer refreshed from the code. If the KB store fails,
// the in-code CANNED list still answers.
const { SITE_HOST, SITE_URL } = require('./host'); const { SITE_HOST, SITE_URL } = require('./host');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const https = require('https'); const https = require('https');
const http = require('http');
const kb = require('./kb');
const kbSeed = require('./kb-seed');
let DATA_DIR = null; let DATA_DIR = null;
let chain = null; let chain = null;
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b'; const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
const KNOWLEDGE_DATE = '2026-10-18'; // the day the CANNED answers and FACTS below were last checked against the site const KNOWLEDGE_DATE = '2026-10-20'; // the day the CANNED answers and FACTS below were last checked against the site
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; } function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
function key() { function key() {
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
@@ -29,74 +38,115 @@ function enabled() { return !!key(); }
// handoff: true makes the widget offer "Send this to support" under the answer (help desk, 2026-10-16) // handoff: true makes the widget offer "Send this to support" under the answer (help desk, 2026-10-16)
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at linkspin|someone|a (human|person|real person))|support (email|address|ticket|team|desk|page)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at linkspin|someone|a (human|person|real person))|support (email|address|ticket|team|desk|page)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
const CANNED = [ const CANNED = [
{ re: SUPPORT_RE, handoff: true, { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a ticket?'], tags: ['support', 'help', 'ticket', 'contact'],
re: SUPPORT_RE, handoff: true,
a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' }, a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' },
{ re: /\b(fix|change|edit|update|correct|replace|wrong|broken|typo)\b.{0,40}\b(link|url|image|banner|picture|headline|text|name)\b.{0,30}\b(ad|ads|campaign|campaigns|banner)\b|\b(edit|fix|change|update) (my |an |the |this )?(ad|ads|campaign|banner|login ad|text ad)\b/i, // Banner Spin (2026-10-20), ahead of the ad-editing and spin-link answers, which also match "banner" and "rotate"
{ id: 'banner-spin', title: 'Banner Spin: one image link that rotates your banners', q: ['What is Banner Spin?', 'How do I rotate several banners in one ad slot?', 'Who gets Banner Spin?'], tags: ['banner spin', 'banners', 'rotator', 'traffic exchange'],
re: /banner ?spins?\b|rotat\w* (my |several |multiple |many |a few |\d+ )?banners|banners? rotat|(one|single) (image|banner) (url|address|link)/i,
a: 'Banner Spin gives you one image address and one click address that rotate up to 25 banners, each with its own target page or spin link, so one banner slot on a traffic exchange, safelist, forum or your own site carries a whole campaign. It is a free add-on that opens with your own package of $25 or more: Starter holds 2 Banner Spins of 5 banners, Builder (level 2 open, 2 qualifying buyers) 5 of 15, Leader (level 3 open, 5 qualifying buyers) 10 of 25. Build it under Links, Banner Spins (' + SITE_URL + '/links#b) and copy one of four embeds: the image + click pair for exchanges and safelists, the HTML snippet for your site, the script tag (it writes the banner and its own link, so every click matches exactly) or the forum code. A click goes to the banner that visitor saw; one we cannot match goes to your fallback. It will not rotate inside paid ad networks (they copy the image when you upload a creative) or in Gmail (its image proxy keeps one copy), so use a single-banner Banner Spin for email. The Stats tab and Reports show views, clicks, CTR, match rate and conversions per banner and per placement, a WINNER badge once two banners have 1,000 views each, and a CACHED flag on sites that copy banners. Every live banner is checked every 30 minutes and paused after three failed checks, never the last live one.' },
{ id: 'edit-ad', title: 'Edit an ad: link, image or text', q: ['How do I change the link on my ad?', 'Can I fix a typo in my ad?', 'How do I replace my banner image?'], tags: ['ads', 'edit', 'banner', 'campaign'],
re: /\b(fix|change|edit|update|correct|replace|wrong|broken|typo)\b.{0,40}\b(link|url|image|banner|picture|headline|text|name)\b.{0,30}\b(ad|ads|campaign|campaigns|banner)\b|\b(edit|fix|change|update) (my |an |the |this )?(ad|ads|campaign|banner|login ad|text ad)\b/i,
a: 'Open Ads in your Control Room (' + SITE_URL + '/ads) and press Edit on the ad. You can change where the click goes, the banner image (upload a new one or paste a link), the headline and line of a text ad, and the ad name. A login ad shows your page itself, so its link is the whole ad. The first edit of every ad is free, your one correction; each edit after that costs a small credit fee (100 credits at the moment, shown before you save), taken from earned credits first. The type, size, budget, countries, schedule and audience stay as they are; for those, start a new ad. A new link is checked the same way as a new ad, so it has to load and, for banner and text ads, allow framing.' }, a: 'Open Ads in your Control Room (' + SITE_URL + '/ads) and press Edit on the ad. You can change where the click goes, the banner image (upload a new one or paste a link), the headline and line of a text ad, and the ad name. A login ad shows your page itself, so its link is the whole ad. The first edit of every ad is free, your one correction; each edit after that costs a small credit fee (100 credits at the moment, shown before you save), taken from earned credits first. The type, size, budget, countries, schedule and audience stay as they are; for those, start a new ad. A new link is checked the same way as a new ad, so it has to load and, for banner and text ads, allow framing.' },
{ re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i, { id: 'login-ads', title: 'Login ad slots', q: ['How do login ads work?', 'How do I book a login ad?'], tags: ['login ad', 'slot', 'purchased credits'],
re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i,
a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 3 member slots run at once because they share the same sign-ins, first come first served; when all 3 are taken the Ads screen says so and a place opens when a running slot ends its 30 days. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy one from Ads, New ad, Login ad.' }, a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 3 member slots run at once because they share the same sign-ins, first come first served; when all 3 are taken the Ads screen says so and a place opens when a running slot ends its 30 days. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy one from Ads, New ad, Login ad.' },
{ re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i, { id: 'vs-iap', title: 'LinkSpin and InstantAdPay: the difference', q: ['What is the difference between LinkSpin and InstantAdPay?', 'Is this the same as InstantAdPay?', 'Why another site?'], tags: ['instantadpay', 'iap', 'sister site', 'network'],
re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i,
a: 'InstantAdPay is the ad marketplace: you buy ad packages there, earn credits by viewing ads, and get paid when your line buys. LinkSpin is the tool side of the same network: a link rotator, a page builder and ad zones for your own sites, free with an email address. Its packages buy ad delivery across the LinkSpin viewer, every member zone and the partner network, and they pay your sponsor line the same way, inside the purchase transaction. Same people above and below you, same wallet, and your InstantAdPay username and profile carry over when you sign in with the same email.' }, a: 'InstantAdPay is the ad marketplace: you buy ad packages there, earn credits by viewing ads, and get paid when your line buys. LinkSpin is the tool side of the same network: a link rotator, a page builder and ad zones for your own sites, free with an email address. Its packages buy ad delivery across the LinkSpin viewer, every member zone and the partner network, and they pay your sponsor line the same way, inside the purchase transaction. Same people above and below you, same wallet, and your InstantAdPay username and profile carry over when you sign in with the same email.' },
{ re: /(pyramid|ponzi|scam|scheme|mlm|legit)/i, { id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is LinkSpin legit?', 'Is this an MLM?'], tags: ['pyramid', 'scam', 'legit', 'mlm'],
re: /(pyramid|ponzi|scam|scheme|mlm|legit)/i,
a: 'Fair question. A pyramid pays for recruiting with no product. LinkSpin sells advertising: an ad package buys real ad delivery (banner, text and login ads across the ad viewer, every member zone and the partner network), and the free tools, spin links, pages and zones, work with no purchase at all. The referral split is a fixed rule in a verified contract on Polygon, 50 percent to the direct sponsor, 20 to level 2, 10 to level 3 and 10 plus 10 to two admin wallets, paid in the same transaction as the purchase. Nobody is paid for recruiting without a sale, nothing is held, and no income is promised. Read the code and every payout yourself at ' + SITE_URL + '/contract and ' + SITE_URL + '/ledger.' }, a: 'Fair question. A pyramid pays for recruiting with no product. LinkSpin sells advertising: an ad package buys real ad delivery (banner, text and login ads across the ad viewer, every member zone and the partner network), and the free tools, spin links, pages and zones, work with no purchase at all. The referral split is a fixed rule in a verified contract on Polygon, 50 percent to the direct sponsor, 20 to level 2, 10 to level 3 and 10 plus 10 to two admin wallets, paid in the same transaction as the purchase. Nobody is paid for recruiting without a sale, nothing is held, and no income is promised. Read the code and every payout yourself at ' + SITE_URL + '/contract and ' + SITE_URL + '/ledger.' },
{ re: /(withdraw|cash ?out|payout request|minimum payout|pending (payment|payout|commission))/i, { id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'Where is my pending payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'],
re: /(withdraw|cash ?out|payout request|minimum payout|pending (payment|payout|commission))/i,
a: 'There are no withdrawals here, ever. When someone in your line buys a package, the contract pays your share straight to your own wallet in the same transaction as the purchase, so there is nothing to request and nothing pending. Credits are the other thing you can have, and they never cash out: they only buy ad delivery.' }, a: 'There are no withdrawals here, ever. When someone in your line buys a package, the contract pays your share straight to your own wallet in the same transaction as the purchase, so there is nothing to request and nothing pending. Credits are the other thing you can have, and they never cash out: they only buy ad delivery.' },
{ re: /(how (do|does) (the )?payouts? work|how (much|do i|does one|can i) (earn|get paid|make)|commission|percent(age)?|the split|split (the|a) (package|purchase)|who gets paid|where does the money go)/i, { id: 'split', title: 'How payouts work: the split', q: ['How do payouts work?', 'How much do I earn?', 'Where does the money go?'], tags: ['payout', 'split', 'commission', 'levels'],
re: /(how (do|does) (the )?payouts? work|how (much|do i|does one|can i) (earn|get paid|make)|commission|percent(age)?|the split|split (the|a) (package|purchase)|who gets paid|where does the money go)/i,
a: 'Every package splits the same way, in the same Polygon transaction it sells in: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, and 10 plus 10 percent to the two admin wallets. Level 1 pays you from your referral\'s very first qualifying purchase once your payouts are switched on. Level 2 opens after two of your people buy a qualifying package ($25 or larger; the $10 door does not count), level 3 after five. A level with no qualified member passes up the line to the next qualified person, then to the platform; nothing waits in a balance. Those numbers are constants in the verified contract at ' + SITE_URL + '/contract. No income is promised: nobody earns unless real ad buying happens in their line.' }, a: 'Every package splits the same way, in the same Polygon transaction it sells in: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, and 10 plus 10 percent to the two admin wallets. Level 1 pays you from your referral\'s very first qualifying purchase once your payouts are switched on. Level 2 opens after two of your people buy a qualifying package ($25 or larger; the $10 door does not count), level 3 after five. A level with no qualified member passes up the line to the next qualified person, then to the platform; nothing waits in a balance. Those numbers are constants in the verified contract at ' + SITE_URL + '/contract. No income is promised: nobody earns unless real ad buying happens in their line.' },
{ re: /(free member|free account|for free|without (a )?(wallet|buying|purchase)|do i (have|need) to (buy|pay|purchase)|what do (i|free members|members) get|what is free|is it free|costs? nothing)/i, { id: 'free-account', title: 'What a free account gets', q: ['What do free members get?', 'Is it free?', 'Do I have to buy anything?'], tags: ['free account', 'tools', 'credits'],
re: /(free member|free account|for free|without (a )?(wallet|buying|purchase)|do i (have|need) to (buy|pay|purchase)|what do (i|free members|members) get|what is free|is it free|costs? nothing)/i,
a: 'A free account gets the whole toolset: spin links (one short link that rotates every page you promote, with weights, a fallback and a report by source), the page builder (bridge, review and squeeze pages from a scan of any offer, leads to your own list), zones (an ad slot on your own site that pays ad credits per viewable impression), audiences (first-party retargeting), reports, promo tools and the blog. Free members earn ad credits by running zones, viewing the daily ad set, watching videos, making verified visits and signing in daily. Credits buy your own banner and text ads at one cent each and never cash out. POL, the real crypto, only ever reaches a wallet through the contract split when a package sells in your line, and you can switch payouts on without buying anything.' }, a: 'A free account gets the whole toolset: spin links (one short link that rotates every page you promote, with weights, a fallback and a report by source), the page builder (bridge, review and squeeze pages from a scan of any offer, leads to your own list), zones (an ad slot on your own site that pays ad credits per viewable impression), audiences (first-party retargeting), reports, promo tools and the blog. Free members earn ad credits by running zones, viewing the daily ad set, watching videos, making verified visits and signing in daily. Credits buy your own banner and text ads at one cent each and never cash out. POL, the real crypto, only ever reaches a wallet through the contract split when a package sells in your line, and you can switch payouts on without buying anything.' },
{ re: /(qualif|unlock level|open level|level ?2|level ?3|pass.?up|two buyers|five buyers)/i, { id: 'qualification', title: 'Qualification: levels 2 and 3', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up'],
re: /(qualif|unlock level|open level|level ?2|level ?3|pass.?up|two buyers|five buyers)/i,
a: 'Level 1, half of every package your direct referrals buy, pays from their first qualifying purchase once your payouts are on. Level 2 (20 percent) opens after two of your people buy a qualifying package, $25 or larger. Level 3 (10 percent) opens after five. The $10 door package is for trying the ads and does not count toward opening levels. Until a level opens, its share passes up the line to the next qualified member, then to the platform, and it never comes back, so leaders qualify before their teams\' teams buy. Qualification is counted by the contract, never expires and cannot be bought.' }, a: 'Level 1, half of every package your direct referrals buy, pays from their first qualifying purchase once your payouts are on. Level 2 (20 percent) opens after two of your people buy a qualifying package, $25 or larger. Level 3 (10 percent) opens after five. The $10 door package is for trying the ads and does not count toward opening levels. Until a level opens, its share passes up the line to the next qualified member, then to the platform, and it never comes back, so leaders qualify before their teams\' teams buy. Qualification is counted by the contract, never expires and cannot be bought.' },
{ re: /(what('s| is) (a |an )?(ad )?zone|zones?\b|embed|script tag|publisher|site owner|my (own )?(web)?site|ad slot|viewable)/i, { id: 'zones', title: 'Ad zones on your own site', q: ['What is an ad zone?', 'How do I put ads on my website?', 'What sizes are the zones?'], tags: ['zones', 'publisher', 'embed', 'website'],
re: /(what('s| is) (a |an )?(ad )?zone|zones?\b|embed|script tag|publisher|site owner|my (own )?(web)?site|ad slot|viewable)/i,
a: 'A zone is an ad slot on your own site: one script tag, nine standard sizes (728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50). Each load shows a LinkSpin member campaign first, then a network ad, then our house banner if nothing paid fits. You earn ad credits per viewable impression (half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day): 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, or 1 per 8 on a Verified zone the admin has reviewed. A new zone earns after its first 100 on-site views with at least 40 percent viewable, and paid ads serve only on the site you declared, so copying the tag elsewhere earns nothing. Everything is explained at ' + SITE_URL + '/publishers and you add zones under Zones in your Control Room.' }, a: 'A zone is an ad slot on your own site: one script tag, nine standard sizes (728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50). Each load shows a LinkSpin member campaign first, then a network ad, then our house banner if nothing paid fits. You earn ad credits per viewable impression (half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day): 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, or 1 per 8 on a Verified zone the admin has reviewed. A new zone earns after its first 100 on-site views with at least 40 percent viewable, and paid ads serve only on the site you declared, so copying the tag elsewhere earns nothing. Everything is explained at ' + SITE_URL + '/publishers and you add zones under Zones in your Control Room.' },
{ re: /(traffic ?sources?|postback|macros?|propeller ?ads|zeropark|adsterra|exoclick|hilltop ?ads|rich ?ads|traffic ?stars|pop ?ads|campaign url|buy(ing)? traffic|paid traffic|ad network|s2s|conversion (pixel|tracking))/i, { id: 'sources', title: 'Traffic sources and postbacks', q: ['How do I track traffic I buy?', 'How do postbacks work?', 'Can I use PropellerAds or Zeropark?'], tags: ['sources', 'postback', 'paid traffic', 'ad network'],
re: /(traffic ?sources?|postback|macros?|propeller ?ads|zeropark|adsterra|exoclick|hilltop ?ads|rich ?ads|traffic ?stars|pop ?ads|campaign url|buy(ing)? traffic|paid traffic|ad network|s2s|conversion (pixel|tracking))/i,
a: 'Sources, in your Control Room, is for traffic you buy on networks like PropellerAds, Zeropark, Adsterra or ExoClick. Pick the network from the catalog (or define your own), fill in your account details, and the source remembers that network\'s macros and conversion postback. Point a spin link at it and the Share kit gives you the exact campaign URL to paste into the network, macros included. When a click from that source joins, leaves a lead, links a wallet or buys, LinkSpin fires the network\'s own postback with its click id, so the network learns what converts, and Reports breaks clicks and conversions down by source and by the zone or placement the macro carried. The older account-level Postbacks on the Links screen still work for your tracker.' }, a: 'Sources, in your Control Room, is for traffic you buy on networks like PropellerAds, Zeropark, Adsterra or ExoClick. Pick the network from the catalog (or define your own), fill in your account details, and the source remembers that network\'s macros and conversion postback. Point a spin link at it and the Share kit gives you the exact campaign URL to paste into the network, macros included. When a click from that source joins, leaves a lead, links a wallet or buys, LinkSpin fires the network\'s own postback with its click id, so the network learns what converts, and Reports breaks clicks and conversions down by source and by the zone or placement the macro carried. The older account-level Postbacks on the Links screen still work for your tracker.' },
{ re: /(spin ?link|rotat|short link|one link|weights?|fallback|split test|sub ?id|click ?id|daypart|health check|dead link|redirect)/i, { id: 'spin-links', title: 'Spin links (the rotator)', q: ['What is a spin link?', 'How do weights and the fallback work?', 'How do I rotate my links?'], tags: ['spin link', 'rotator', 'short link', 'weights'],
re: /(spin ?link|rotat|short link|one link|weights?|fallback|split test|sub ?id|click ?id|daypart|health check|dead link|redirect)/i,
a: 'A spin link is one short link that rotates between every page you promote. Behind it you set destinations with weights, pause any of them, and name a fallback for when everything else is off. Every click is recorded in one hop with the day, country, source and device, bots are filtered on the server, and click ids and sub ids (clickid, subid, s1 to s4 and the usual tracker names) ride through to the destination, so you can split-test by tagging the same link with different sub ids. Reports show it per link and across all of them. Set the hours of the day and week a spin or a destination runs (the local time of your visitor by default), and automatic health checks pause a dead or parked destination for you. You can try a spin with no account on the home page.' }, a: 'A spin link is one short link that rotates between every page you promote. Behind it you set destinations with weights, pause any of them, and name a fallback for when everything else is off. Every click is recorded in one hop with the day, country, source and device, bots are filtered on the server, and click ids and sub ids (clickid, subid, s1 to s4 and the usual tracker names) ride through to the destination, so you can split-test by tagging the same link with different sub ids. Reports show it per link and across all of them. Set the hours of the day and week a spin or a destination runs (the local time of your visitor by default), and automatic health checks pause a dead or parked destination for you. You can try a spin with no account on the home page.' },
{ re: /(page builder|bridge page|squeeze page|review page|sales page|advertorial|press release|landing page|build (a|me a) page|my pages?|lead capture|leads?\b)/i, { id: 'pages', title: 'The page builder', q: ['How do I build a bridge page?', 'Can I make a squeeze page?', 'Where do my leads go?'], tags: ['pages', 'page builder', 'bridge page', 'leads'],
re: /(page builder|bridge page|squeeze page|review page|sales page|advertorial|press release|landing page|build (a|me a) page|my pages?|lead capture|leads?\b)/i,
a: 'Pages is the built-in page builder. Paste the address of any offer you promote, LinkSpin scans its headline and points, you add your angle, and you get a bridge, review or squeeze page with your own leads list (CSV or webhook), published on LinkSpin\'s pages domain, lookfirst.page. Pick a design, palette and layout, or a niche preset that sets them for you with a matching hero image. Put the page behind a spin link to send traffic by weight. Sales, advertorial and press-release layouts are on the way. Open Pages in your Control Room; it is free.' }, a: 'Pages is the built-in page builder. Paste the address of any offer you promote, LinkSpin scans its headline and points, you add your angle, and you get a bridge, review or squeeze page with your own leads list (CSV or webhook), published on LinkSpin\'s pages domain, lookfirst.page. Pick a design, palette and layout, or a niche preset that sets them for you with a matching hero image. Put the page behind a spin link to send traffic by weight. Sales, advertorial and press-release layouts are on the way. Open Pages in your Control Room; it is free.' },
{ re: /(audience|retarget|pixel|p\.js|my visitors|show only to|never show to)/i, { id: 'audiences', title: 'Audiences and retargeting', q: ['How does retargeting work?', 'What is the pixel?', 'Can I show ads only to my visitors?'], tags: ['audiences', 'retargeting', 'pixel'],
re: /(audience|retarget|pixel|p\.js|my visitors|show only to|never show to)/i,
a: 'Audiences is first-party retargeting. Everyone who views your LinkSpin pages or your zones lands in "My visitors" for 30 days with no setup, and for any other site you control you paste a small pixel tag (/p.js). Then, on any banner or text campaign, choose "show only to" or "never show to" an audience. The match uses a LinkSpin cookie with a 24-hour fallback where browsers block cross-site cookies, and nothing personal is stored. It lives on the Zones screen.' }, a: 'Audiences is first-party retargeting. Everyone who views your LinkSpin pages or your zones lands in "My visitors" for 30 days with no setup, and for any other site you control you paste a small pixel tag (/p.js). Then, on any banner or text campaign, choose "show only to" or "never show to" an audience. The match uses a LinkSpin cookie with a 24-hour fallback where browsers block cross-site cookies, and nothing personal is stored. It lives on the Zones screen.' },
{ re: /(promo tools?|social posts?|email swipes?|banners? (kit|set)|text a friend|objection|hook videos?|angle (link|video|page)|share buttons?)/i, { id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners'],
re: /(promo tools?|social posts?|email swipes?|banners? (kit|set)|text a friend|objection|hook videos?|angle (link|video|page)|share buttons?)/i,
a: 'Promo tools (' + SITE_URL + '/tools#promo) holds everything personalised with your invite link: social posts, text-a-friend messages, email swipes, banners in the standard sizes, an objection-handling bank with honest replies, and the hook videos. There are five hook angles, each with its own join page and video: links (stop juggling links), pages (a bridge page in a minute), zones (your site pays you), audiences (reach your visitors again) and stack (the three tools, free). An angle link is your normal link with ?v= on the end, so every join and purchase still credits you.' }, a: 'Promo tools (' + SITE_URL + '/tools#promo) holds everything personalised with your invite link: social posts, text-a-friend messages, email swipes, banners in the standard sizes, an objection-handling bank with honest replies, and the hook videos. There are five hook angles, each with its own join page and video: links (stop juggling links), pages (a bridge page in a minute), zones (your site pays you), audiences (reach your visitors again) and stack (the three tools, free). An angle link is your normal link with ?v= on the end, so every join and purchase still credits you.' },
{ re: /\bblog\b|articles?|read more/i, { id: 'blog', title: 'The blog', q: ['Is there a blog?', 'Where are the articles?'], tags: ['blog', 'articles'],
re: /\bblog\b|articles?|read more/i,
a: 'The blog at ' + SITE_URL + '/blog has Marty\'s articles on building a line, advertising that pays and daily habits. Each article has its own page you can share, and there is an RSS feed at /blog/feed.xml.' }, a: 'The blog at ' + SITE_URL + '/blog has Marty\'s articles on building a line, advertising that pays and daily habits. Each article has its own page you can share, and there is an RSS feed at /blog/feed.xml.' },
{ re: /(price|cost|packages?|how much is|ladder|\$10|\$25|\$50|\$100|\$250|\$500|door package)/i, { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'What does the $10 door package do?', 'Which package should I buy?'], tags: ['packages', 'price', 'credits', 'qualification'],
re: /(price|cost|packages?|how much is|ladder|\$10|\$25|\$50|\$100|\$250|\$500|door package)/i,
a: 'Six packages, priced in dollars and settled in POL at the live rate: the $10 door (1,000 credits, for trying the ads; it does not count toward qualification), $25 Starter (2,500), $50 Builder (5,000), $100 Growth (10,000), $250 Leader (25,000) and $500 Network (50,000). One credit is one cent of ad delivery. Any package of $25 or more makes you a qualifying buyer for your sponsor. Buy under Credits in your Control Room; the live ladder is on the home page.' }, a: 'Six packages, priced in dollars and settled in POL at the live rate: the $10 door (1,000 credits, for trying the ads; it does not count toward qualification), $25 Starter (2,500), $50 Builder (5,000), $100 Growth (10,000), $250 Leader (25,000) and $500 Network (50,000). One credit is one cent of ad delivery. Any package of $25 or more makes you a qualifying buyer for your sponsor. Buy under Credits in your Control Room; the live ladder is on the home page.' },
{ re: /(credits?|impression|cpm|what do i get|what am i buying|one cent|1 cent)/i, { id: 'credits', title: 'What credits are and how you get them', q: ['What is a credit?', 'How do I get credits?', 'What am I buying?'], tags: ['credits', 'ad delivery', 'impressions'],
re: /(credits?|impression|cpm|what do i get|what am i buying|one cent|1 cent)/i,
a: 'One credit is one cent of ad delivery: banner, text and login ads shown across the LinkSpin ad viewer, every member zone and the partner network, managed from the Ads screen. Credits come two ways, bought in a package or earned free (zones, the daily ad set, videos, verified visits, daily sign-in). Earned credits spend on banner and text campaigns; a login-ad slot (1,000 purchased credits for 30 days) takes purchased credits only. Credits are advertising, not money: they never cash out and are never converted to crypto.' }, a: 'One credit is one cent of ad delivery: banner, text and login ads shown across the LinkSpin ad viewer, every member zone and the partner network, managed from the Ads screen. Credits come two ways, bought in a package or earned free (zones, the daily ad set, videos, verified visits, daily sign-in). Earned credits spend on banner and text campaigns; a login-ad slot (1,000 purchased credits for 30 days) takes purchased credits only. Credits are advertising, not money: they never cash out and are never converted to crypto.' },
{ re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i, { id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning'],
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
a: 'That red "this transaction will drain your wallet" screen is Trust Wallet\'s own safety rule, not a problem with the purchase: it blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet. SafePal, MetaMask and Phantom have no such block. Extra POL always stays yours. If the next try says WalletConnect disconnected, open the Wallet screen, disconnect, then connect again.' }, a: 'That red "this transaction will drain your wallet" screen is Trust Wallet\'s own safety rule, not a problem with the purchase: it blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet. SafePal, MetaMask and Phantom have no such block. Extra POL always stays yours. If the next try says WalletConnect disconnected, open the Wallet screen, disconnect, then connect again.' },
{ re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto|metamask|safepal|phantom|coinbase wallet)/i, { id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'safepal', 'metamask', 'moonpay', 'buy pol'],
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto|metamask|safepal|phantom|coinbase wallet)/i,
a: 'SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first under Settings, Active Networks) and any WalletConnect wallet work too. Trust Wallet works but blocks a purchase that spends most of its POL, so keep about double the package cost there. Never held crypto? Link your wallet, open Credits and tap Buy POL with a card: MoonPay opens with POL on Polygon and your own address filled in, you pay by card, Apple Pay or Google Pay (the first time needs an ID check), the POL lands in your wallet in minutes, then you buy the package. Keep a little extra POL for network fees.' }, a: 'SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first under Settings, Active Networks) and any WalletConnect wallet work too. Trust Wallet works but blocks a purchase that spends most of its POL, so keep about double the package cost there. Never held crypto? Link your wallet, open Credits and tap Buy POL with a card: MoonPay opens with POL on Polygon and your own address filled in, you pay by card, Apple Pay or Google Pay (the first time needs an ID check), the POL lands in your wallet in minutes, then you buy the package. Keep a little extra POL for network fees.' },
{ re: /(need (a )?wallet|crypto experience|how (do i|to) (join|sign ?up|register|sign in)|sign ?up|register|password|sign.?in code|six.?digit)/i, { id: 'join', title: 'How to join and sign in', q: ['How do I join?', 'Do I need a wallet?', 'Is there a password?'], tags: ['join', 'sign up', 'sign in', 'code'],
re: /(need (a )?wallet|crypto experience|how (do i|to) (join|sign ?up|register|sign in)|sign ?up|register|password|sign.?in code|six.?digit)/i,
a: 'Join free with just your email at ' + SITE_URL + '/join. A six-digit code signs you in, there is no password, and no wallet is needed to use the links, pages and zones. The wallet step comes later, inside your Control Room, when you want to be paid or to buy a package.' }, a: 'Join free with just your email at ' + SITE_URL + '/join. A six-digit code signs you in, there is no password, and no wallet is needed to use the links, pages and zones. The wallet step comes later, inside your Control Room, when you want to be paid or to buy a package.' },
{ re: /(referral link|invite link|share link|join link|my link|refer(ring)? (people|friends|someone))/i, { id: 'referral-link', title: 'My invite link', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools'],
re: /(referral link|invite link|share link|join link|my link|refer(ring)? (people|friends|someone))/i,
a: 'Your invite link is live the moment you sign in, free members included: ' + SITE_HOST + '/join/yourname. Promo tools lists it with the five angle versions (links, pages, zones, audiences, stack), each with a video and Copy and Share buttons; they are the same link with ?v= on the end, so every join and purchase credits you. One tip: switch on payouts (Credits screen, one transaction, no purchase needed) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' }, a: 'Your invite link is live the moment you sign in, free members included: ' + SITE_HOST + '/join/yourname. Promo tools lists it with the five angle versions (links, pages, zones, audiences, stack), each with a video and Copy and Share buttons; they are the same link with ?v= on the end, so every join and purchase credits you. One tip: switch on payouts (Credits screen, one transaction, no purchase needed) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
{ re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit|carr)|carry.?over|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor|same (team|sponsor|upline)|registry)/i, { id: 'sponsor', title: 'Who is my sponsor; wrong sponsor; carry-over', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Is my InstantAdPay sponsor carried over?'], tags: ['sponsor', 'carry-over', 'registry', 'invite link'],
re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit|carr)|carry.?over|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor|same (team|sponsor|upline)|registry)/i,
a: 'The invite link you opened most recently sets your sponsor, and the join page shows who you are joining under. It locks when you create your account, and your first purchase binds you to that sponsor on the contract. Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their sponsor carried over automatically from the network registry when no invite link was used, so the same people are above you here. Already joined under the wrong sponsor by mistake? Message support before your first purchase and the admin can move you.' }, a: 'The invite link you opened most recently sets your sponsor, and the join page shows who you are joining under. It locks when you create your account, and your first purchase binds you to that sponsor on the contract. Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their sponsor carried over automatically from the network registry when no invite link was used, so the same people are above you here. Already joined under the wrong sponsor by mistake? Message support before your first purchase and the admin can move you.' },
{ re: /(activat|switch(ed)? on payouts|payouts (on|off)|turn on payouts|get paid to my wallet|link (my |a )?wallet)/i, { id: 'activation', title: 'Switching on payouts', q: ['How do I switch on payouts?', 'How do I link my wallet?', 'How do I activate?'], tags: ['activation', 'payouts', 'link wallet'],
re: /(activat|switch(ed)? on payouts|payouts (on|off)|turn on payouts|get paid to my wallet|link (my |a )?wallet)/i,
a: 'Payouts switch on when your wallet is registered on the contract. That happens two ways: buy any package, or use the free activation on the Credits screen, one transaction that costs only network gas. First link the wallet that should receive your payouts (one signature, no transaction), then activate. From then on the contract pays your share of every qualifying purchase in your line straight to that wallet. Buying is never required to be paid at level 1; a $25 or larger package is what makes you a qualifying buyer for your own sponsor and funds your own ads.' }, a: 'Payouts switch on when your wallet is registered on the contract. That happens two ways: buy any package, or use the free activation on the Credits screen, one transaction that costs only network gas. First link the wallet that should receive your payouts (one signature, no transaction), then activate. From then on the contract pays your share of every qualifying purchase in your line straight to that wallet. Buying is never required to be paid at level 1; a $25 or larger package is what makes you a qualifying buyer for your own sponsor and funds your own ads.' },
{ re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|\bpol\b|polygon|matic/i, { id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Is it MATIC?'], tags: ['pol', 'polygon', 'crypto', 'network'],
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|\bpol\b|polygon|matic/i,
a: 'One coin, one network: POL, the native coin of Polygon. Packages are priced in dollars and settled in POL at the live rate, and every payout arrives as POL in your own Polygon wallet in the same transaction. No other coins, tokens or chains are used. Send POL on the Polygon network, never MATIC on Ethereum.' }, a: 'One coin, one network: POL, the native coin of Polygon. Packages are priced in dollars and settled in POL at the live rate, and every payout arrives as POL in your own Polygon wallet in the same transaction. No other coins, tokens or chains are used. Send POL on the Polygon network, never MATIC on Ethereum.' },
{ re: /(control room|dashboard|where (do|can) i (find|see)|which screen|menu|navigation|more tools|\/tools)/i, { id: 'control-room', title: 'The Control Room screens', q: ['Where do I find my links?', 'What is on the dashboard?', 'Which screen has my campaigns?'], tags: ['control room', 'dashboard', 'menu', 'tools'],
re: /(control room|dashboard|where (do|can) i (find|see)|which screen|menu|navigation|more tools|\/tools)/i,
a: 'Your Control Room has these screens: Links (spin links), Pages (the page builder), Zones (ad slots on your site plus Audiences), Ads (your campaigns and the daily ad set), Credits (buy packages, link your wallet, switch on payouts), Reports (every link in one view), Team (your line, three levels) and Wallet (what was paid to you). More, at ' + SITE_URL + '/tools, holds Promo tools, Training, the Pipeline follow-up board, My line and your Profile.' }, a: 'Your Control Room has these screens: Links (spin links), Pages (the page builder), Zones (ad slots on your site plus Audiences), Ads (your campaigns and the daily ad set), Credits (buy packages, link your wallet, switch on payouts), Reports (every link in one view), Team (your line, three levels) and Wallet (what was paid to you). More, at ' + SITE_URL + '/tools, holds Promo tools, Training, the Pipeline follow-up board, My line and your Profile.' },
{ re: /(holding tank|adopt|no sponsor|without a sponsor|orphan)/i, { id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'no sponsor'],
re: /(holding tank|adopt|no sponsor|without a sponsor|orphan)/i,
a: 'Members who join from the public site with no sponsor wait in the holding tank under More, My line. A member who has switched on payouts and bought their own qualifying package can adopt one, first come, with a 7-day window for the new member to link a wallet or buy; otherwise they return to the tank. Adopting sets the sponsor, and their first purchase then binds to the adopter on the contract.' }, a: 'Members who join from the public site with no sponsor wait in the holding tank under More, My line. A member who has switched on payouts and bought their own qualifying package can adopt one, first come, with a 7-day window for the new member to link a wallet or buy; otherwise they return to the tank. Adopting sets the sponsor, and their first purchase then binds to the adopter on the contract.' },
{ re: /(my line|downline|my team|who (is|are) (in|on) my|three levels|level 1\b)/i, { id: 'team', title: 'My line: the Team screen', q: ['How do I see my downline?', 'Who is in my team?'], tags: ['team', 'my line', 'downline', 'levels'],
re: /(my line|downline|my team|who (is|are) (in|on) my|three levels|level 1\b)/i,
a: 'Team shows your line as a working table, three levels deep: who joined through your link, who has switched on payouts, who has bought, and how many qualifying buyers each person has. The chip count is what opens your levels: two qualifying buyers ($25 or larger) open level 2, five open level 3.' }, a: 'Team shows your line as a working table, three levels deep: who joined through your link, who has switched on payouts, who has bought, and how many qualifying buyers each person has. The chip count is what opens your levels: two qualifying buyers ($25 or larger) open level 2, five open level 3.' },
{ re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, { id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?'], tags: ['balance', 'credits', 'campaigns'],
re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
a: 'One rule: your available balance is what is not committed to a live campaign. When you start a campaign its whole budget is set aside right then, so Available drops once and then sits still while the ad runs; the budget spends down inside that campaign on the Ads screen, where you can see delivered views and what is left. A paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live.' }, a: 'One rule: your available balance is what is not committed to a live campaign. When you start a campaign its whole budget is set aside right then, so Available drops once and then sits still while the ad runs; the budget spends down inside that campaign on the Ads screen, where you can see delivered views and what is left. A paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live.' },
{ re: /(safe|trust (you|this|the site)|rug|run away|disappear|hold(s|ing)? (my|the) (money|funds))/i, { id: 'safe', title: 'Is it safe? Who holds the money?', q: ['Is this safe?', 'Can you run away with the money?', 'Who holds the funds?'], tags: ['safe', 'contract', 'custody', 'trust'],
re: /(safe|trust (you|this|the site)|rug|run away|disappear|hold(s|ing)? (my|the) (money|funds))/i,
a: 'The money never touches us. A verified, immutable contract on Polygon splits every purchase in the same transaction, holds no balance, and has no pause switch or upgrade path. Credits live on the platform and are advertising, not money. Read the plain-language review and the verified source at ' + SITE_URL + '/contract, and watch every payout land at ' + SITE_URL + '/ledger.' } a: 'The money never touches us. A verified, immutable contract on Polygon splits every purchase in the same transaction, holds no balance, and has no pause switch or upgrade path. Credits live on the platform and are advertising, not money. Read the plain-language review and the verified source at ' + SITE_URL + '/contract, and watch every payout land at ' + SITE_URL + '/ledger.' }
]; ];
// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence)
function seeds() {
return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source,
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ);
}
// ---- facts for the AI fallback ---- // ---- facts for the AI fallback ----
function systemPrompt() { function systemPrompt(kbBlock) {
return `You are the assistant on LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property. return `You are the assistant on LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property.
FACTS: FACTS:
- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/<code>, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list, CSV or webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. Knowledge checked on ${KNOWLEDGE_DATE}. - PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/<code>, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list, CSV or webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. Knowledge checked on ${KNOWLEDGE_DATE}.
- BANNER SPIN (LIVE 2026-10-18, reports and health checks 2026-10-20): one image address (/i/<code>.gif on a link domain) and one click address (/c/<code>) that rotate up to 25 banners, each with its own target (any https page or one of the member's spin links), weights 1 to 100, random by weight on every view or one banner per visitor per day, the dayparting grid per Banner Spin and per banner, pause, a fallback page and an optional fallback banner image, and a traffic source so its conversions fire that network's postback. Built on the Links screen (${SITE_URL}/links#b). WHO GETS IT: a free add-on for members with their own package of $25 or more; tiers: Starter 2 Banner Spins x 5 banners, Builder (level 2 open, 2 qualifying buyers) 5 x 15, Leader (level 3 open, 5 qualifying buyers) 10 x 25; dropping below a tier keeps everything serving, it only stops new ones. One size per Banner Spin (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250, 320x50); JPG, PNG or GIF (animated is fine), 150 KB at most, uploads count toward the 10 files a day. EMBEDS: the image + click pair (traffic exchanges, safelists, downline builders), an HTML snippet (own sites, blogs, HTML email), a script tag (writes the banner and its own link, so every click matches exactly) and forum BBCode; every link domain answers every code. MATCHING: with the pair, the server remembers which banner a visitor saw on which page for 15 minutes and sends the click there; an unmatched click goes to the fallback. LIMITS: paid ad networks (Froggy, PropellerAds and the like) copy the image at upload, so it freezes on one banner there; Gmail and some mail apps fetch images through a caching proxy, so email readers mostly see one banner and clicks fall back: use a single-banner Banner Spin for email. REPORTS: per banner and per placement views, unique viewers (daily sample), clicks, CTR, match rate and conversions, by Central day, country and device, bots and server loads shown separately and never counted; a WINNER badge once two or more live banners have 1,000 views each and one leads on click rate (LinkSpin never changes weights by itself); a CACHED flag on a placement that copies banners to its own server; totals also on the Reports screen. HEALTH: every 30 minutes each live banner's image must load as an image of the right size and its target must pass the spin-link checks (dead, parked, slow); three failures in a row pause that banner, two clean passes resume it, the last live banner is never auto-paused, and the status shows on each banner row.
- PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor. - PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor.
- THE SPLIT, same transaction on Polygon, fixed in the contract: 50 percent direct sponsor, 20 percent level 2, 10 percent level 3, 10 percent + 10 percent to the two admin wallets. Level 1 pays from a referral's first qualifying purchase once the sponsor's payouts are on. Level 2 opens after two of the member's people buy a qualifying ($25 or larger) package, level 3 after five. An unfilled tier passes up the line to the next qualified member, then to the platform. Nothing is held, there are no withdrawals, no pending balances. Contract ${CONTRACT} on Polygon, verified on Polygonscan; plain-language review at ${SITE_URL}/contract; live ledger at ${SITE_URL}/ledger with a verify link on every row. - THE SPLIT, same transaction on Polygon, fixed in the contract: 50 percent direct sponsor, 20 percent level 2, 10 percent level 3, 10 percent + 10 percent to the two admin wallets. Level 1 pays from a referral's first qualifying purchase once the sponsor's payouts are on. Level 2 opens after two of the member's people buy a qualifying ($25 or larger) package, level 3 after five. An unfilled tier passes up the line to the next qualified member, then to the platform. Nothing is held, there are no withdrawals, no pending balances. Contract ${CONTRACT} on Polygon, verified on Polygonscan; plain-language review at ${SITE_URL}/contract; live ledger at ${SITE_URL}/ledger with a verify link on every row.
- CREDITS VS POL: every member, free ones included, earns CREDITS (zones, the daily ad set with a claim streak, watch-to-earn videos, verified visits, a daily sign-in bonus). Credits buy the member's own banner and text ads (a login-ad slot takes purchased credits only) and NEVER cash out or convert to crypto. POL only reaches a wallet through the contract split when a package sells in the member's line. Never promise or estimate income. - CREDITS VS POL: every member, free ones included, earns CREDITS (zones, the daily ad set with a claim streak, watch-to-earn videos, verified visits, a daily sign-in bonus). Credits buy the member's own banner and text ads (a login-ad slot takes purchased credits only) and NEVER cash out or convert to crypto. POL only reaches a wallet through the contract split when a package sells in the member's line. Never promise or estimate income.
@@ -113,29 +163,40 @@ RULES:
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page. - 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen in their line. - NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen in their line.
- No em dashes. If you do not know, say so and point to ${SITE_URL}/contract or the ledger. - No em dashes. If you do not know, say so and point to ${SITE_URL}/contract or the ledger.
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.`; - Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
} }
function askAI(message, historyText) { // OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
function endpoint() {
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
}
function askAI(message, historyText, kbBlock) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const body = JSON.stringify({ const body = JSON.stringify({
model: MODEL, model: MODEL,
reasoning: { enabled: false }, // deepseek-v4-flash thinks by default and can spend the whole max_tokens on it (IAP, 2026-10-16)
max_tokens: 300, max_tokens: 300,
messages: [ messages: [
{ role: 'system', content: systemPrompt() }, { role: 'system', content: systemPrompt(kbBlock) },
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []), ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
{ role: 'user', content: String(message).slice(0, 600) } { role: 'user', content: String(message).slice(0, 600) }
] ]
}); });
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST', const ep = endpoint();
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body) }, timeout: 30000 }, 'Content-Length': Buffer.byteLength(body) }, timeout: 30000 },
res => { res => {
let d = ''; let d = '';
res.on('data', c => d += c); res.on('data', c => d += c);
res.on('end', () => { res.on('end', () => {
try { resolve(JSON.parse(d).choices[0].message.content.trim()); } // OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object
catch (e) { reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); } const i = d.indexOf('{');
let txt = '';
try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); }
catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); }
if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content'));
resolve(txt);
}); });
}); });
req.on('error', reject); req.on('error', reject);
@@ -148,14 +209,25 @@ const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unabl
async function answer(message, historyText) { async function answer(message, historyText) {
const msg = String(message || '').trim(); const msg = String(message || '').trim();
if (!msg) return { error: 'Say something first.' }; if (!msg) return { error: 'Say something first.' };
for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); // fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
let hit = null, kbOk = true;
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
let kbBlock = '', kbIds = [];
try {
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
const hits = await kb.context(query, 5);
kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id);
} catch (e) { console.error('kb search', e.message); }
if (!enabled()) return { reply: 'Good question. The quick answers I have cover spin links, pages, zones, packages, the payout split, qualification and joining; for anything deeper, the plain-language contract review at ' + SITE_URL + '/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; if (!enabled()) return { reply: 'Good question. The quick answers I have cover spin links, pages, zones, packages, the payout split, qualification and joining; for anything deeper, the plain-language contract review at ' + SITE_URL + '/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true };
// handoff: the answer admits it cannot help, so the widget offers "Send this to support" // handoff: the answer admits it cannot help, so the widget offers "Send this to support"
try { const reply = await askAI(msg, historyText); return Object.assign({ reply }, UNSURE_RE.test(reply) ? { handoff: true } : {}); } try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
catch (e) { catch (e) {
console.error('chat AI failed', e.message); console.error('chat AI failed', e.message);
return { reply: 'I hit a snag answering that one. The contract review at ' + SITE_URL + '/contract and the live ledger at ' + SITE_URL + '/ledger cover most deep questions, or tap "Send this to support" and Marty will answer.', handoff: true }; return { reply: 'I hit a snag answering that one. The contract review at ' + SITE_URL + '/contract and the live ledger at ' + SITE_URL + '/ledger cover most deep questions, or tap "Send this to support" and Marty will answer.', handoff: true };
} }
} }
module.exports = { init, answer, enabled, CANNED }; module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt };
@@ -0,0 +1,7 @@
{
"_draft": "NOT PUBLISHED. Release note in the releases.json note shape (releases.saveNote: date, title, body, tags). To publish: Admin > Releases > New note, paste title + body, tags new. Saving a note there publishes it on /whats-new at once, and Releases > Email an update can mail members, so Marty decides when.",
"date": "2026-10-20",
"title": "Banner Spin: one banner slot, up to 25 banners",
"tags": "new",
"body": "Banner Spin is live on the Links screen. It gives you one image address and one click address that rotate up to 25 banners, each with its own target page or spin link. Paste it once into a banner slot on a traffic exchange, a safelist, a forum signature or your own site, and change the banners from your Control Room whenever you like.\n\n- Four embeds: the image + click pair, an HTML snippet, a script tag that matches every click exactly, and forum code\n- A click goes to the page of the banner that visitor saw; one we cannot match goes to your fallback\n- Weights, one banner per visitor per day, hours, pause and a fallback banner\n- Stats per banner and per placement: views, unique viewers, clicks, click rate, match rate and conversions, by day, country and device, on the Stats tab and on Reports\n- A WINNER badge once two banners have 1,000 views each, and a CACHED flag on sites that copy banners to their own server\n- Health checks every 30 minutes: a banner whose image or target breaks three times in a row is paused, and comes back after two clean checks. Your last live banner is never paused\n- Conversions from a traffic source fire that network's postback, same as spin links\n\nWho gets it: a free add-on with your own package of $25 or more. Starter holds 2 Banner Spins with 5 banners each, Builder (2 qualifying buyers) 5 with 15, Leader (5 qualifying buyers) 10 with 25.\n\nGood to know: paid ad networks copy your image when you upload a creative, and Gmail keeps its own copy of email images, so the rotation does not run there. For email, use a Banner Spin with a single banner.\n\nThe new Training lesson walks through it step by step."
}
+105 -6
View File
@@ -10,7 +10,12 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); 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 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 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; 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: [] }; } }, 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) {} } }; 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 // one request with a hard timeout; returns the Response or throws
async function req(url, method, signalMs) { async function req(url, method, signalMs) {
@@ -116,12 +121,106 @@ 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) {} } }); 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); 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);
// a size mismatch is a warning, not a failure (2026-10-20): the builder allows it with a warning, so live banners must not be auto-paused for it
if (d.w && d.h && W && (d.w !== W || d.h !== H)) return { state: 'ok', warn: '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; let running = false;
// the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by // the scheduled pass: active destinations + fallbacks every time; auto-paused destinations when 6 h have gone by
async function tick() { async function tick() {
if (running || !rotator) return { skipped: true }; running = true; 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 { 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 r of rotator.rawRotations()) {
for (const d of r.destinations) { for (const d of r.destinations) {
const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED)); const due = d.active || (d.autoPaused && (!d.health || now - (d.health.checkedAt || 0) >= RECHECK_PAUSED));
@@ -131,8 +230,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; }); 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); await runAll(jobs);
} finally { running = false; if (changed) rotator.save(); } } finally { running = false; if (changed) rotator.save(); if (bn && bannerspin) bannerspin.save(); }
return { checked: n }; return { checked: n, banners: bn };
} }
// "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback // "Check now" for one rotation (owner-scoped, once a minute): every destination, paused ones too, plus the fallback
const lastManual = new Map(); const lastManual = new Map();
@@ -146,4 +245,4 @@ async function checkRotation(owner, id) {
return { ok: true, rotation: rotator.pub(r) }; return { ok: true, rotation: rotator.pub(r) };
} }
function recent() { if (!L.db) L.load(); return L.db.events.slice(-50).reverse(); } 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 };
+57
View File
@@ -0,0 +1,57 @@
// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the home page's network notes, the
// wallets guide's Common questions, the earning guide, and support replies worth keeping. An entry here
// that nobody has edited in Admin > Knowledge base is refreshed when its text changes in this file; edit
// it in the admin pane and it becomes the admin's own.
// House rules: plain words, no em dashes, never a promise of income.
const { SITE_HOST, SITE_URL } = require('./host');
const FAQ = [
{ id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket',
questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'],
tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'],
answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. LinkSpin runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open ' + SITE_HOST + ' in SafePal\'s browser (or the browser with the extension), sign in with your email, open Credits in your Control Room and tap Link a wallet (one free signature). You only need a wallet to buy a package or receive payouts.' },
{ id: 'f-team-here', title: 'Already on InstantAdPay? Your team is already here', source: 'faq',
questions: ['I am already on InstantAdPay, do I start over?', 'Will my InstantAdPay sponsor be my sponsor here?', 'Can I sign in with my InstantAdPay email?'],
tags: ['instantadpay', 'sponsor', 'carry-over', 'team', 'network'],
answer: 'Sign in with the email you use on InstantAdPay and your sponsor is placed for you before you buy anything: the same people above you, the same people below you, the same wallet. LinkSpin is a second property to build on, with tools you will use every day.' },
{ id: 'f-new-here', title: 'New here: where to start', source: 'faq',
questions: ['I am new, where do I start?', 'What should I do first?', 'How do I get started?'],
tags: ['getting started', 'new member', 'first steps'],
answer: 'Make a spin link on the home page at ' + SITE_URL + ', promote it anywhere, and watch the clicks in your Control Room. Create your free account at ' + SITE_URL + '/join with just your email. Buy a package when you want your own ads in front of the network. Email first, wallet only when you are ready to be paid.' },
{ id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq',
questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'],
tags: ['pol', 'fees', 'gas', 'buy packages'],
answer: 'The Credits screen shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' },
{ id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq',
questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'],
tags: ['moonpay', 'card', 'declined', 'buy pol'],
answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check (minimum order usually around $30).' },
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
tags: ['wallet', 'position', 'qualified start', 'metamask'],
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' },
{ id: 'f-payouts-where', title: 'Where do my payouts go?', source: 'faq',
questions: ['Where do my payouts go?', 'Which wallet gets paid?', 'Does the site hold my earnings?'],
tags: ['payout', 'wallet', 'custody'],
answer: 'To the wallet address you switched payouts on with, in the same transaction as the purchase that earned them. Nothing is held on the site. The Wallet screen in your Control Room shows what was paid to that wallet.' },
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' },
{ id: 'f-claim-streak', title: 'The daily set and the claim streak', source: 'faq',
questions: ['How does the daily claim streak work?', 'How much does the daily claim pay?', 'When does the daily ad set reset?'],
tags: ['daily set', 'claim streak', 'earn credits', 'reset'],
answer: 'Earn credits > Watch ads gives five ads a day: each opens full screen, a 10-second countdown runs, you pass a quick click-the-icon check and earn 1 credit. Finish all five and Claim appears. The claim pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th day in a row; miss a day and it restarts. Days are counted in UTC, so the set resets at 7 PM Central (6 PM in winter time). Credits are ad delivery, never money.' },
{ id: 'f-visits-videos', title: 'Verified visits, videos and inbox ads', source: 'faq',
questions: ['How do verified visits pay?', 'How many videos can I watch a day?', 'How do inbox solo ads pay?'],
tags: ['verified visits', 'videos', 'inbox', 'earn credits'],
answer: 'After the daily set is claimed you can make up to 20 verified visits a day, 1 credit each: open a member\'s site in a new tab and stay for the dwell; each is a different site. Videos credit only when they play to the end, up to 6 a day, paying by length. Inbox solo ads: open the message, visit the advertiser\'s link, then claim 2 credits, once per message. Signing in also pays 5 credits a day, rising by one per day in a row up to 10.' },
{ id: 'f-spend-credits', title: 'What to do with earned credits', source: 'faq',
questions: ['What do I do with my credits?', 'How do I spend my credits?', 'My credits are just sitting there'],
tags: ['credits', 'campaign', 'spend'],
answer: 'Credits sitting in your balance do nothing. Open Ads in your Control Room, start a new banner or text campaign, give it a budget in credits and point it at your own invite link or wall. Banner and text ads also push out to the partner network. A campaign reserves its whole budget the moment it starts, and login ads are the one format that needs purchased credits.' },
{ id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq',
questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'],
tags: ['recovery phrase', 'private key', 'scam', 'security'],
answer: 'Never share your recovery phrase (the 12 or 24 words) or private key with anyone: whoever has them has your money. Nobody from LinkSpin will ever ask for them, and the site never sees them. If someone does ask, do not reply, and tell support through Help at ' + SITE_URL + '/help.' }
];
module.exports = { FAQ };
+245
View File
@@ -0,0 +1,245 @@
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
// The chatbot answers from maintained entries, and good support replies become entries.
//
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
// updated, created, edited, deleted, seedHash }
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
// path serves the new text.
// source canned | faq | ticket | admin
//
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
//
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
//
// Store: one JSON file on the volume, DATA_DIR/kb.json (written to a temp file and renamed). Ported from
// InstantAdPay's kb.js, which also has a MySQL store; keep the scoring and seed rules of the two in step.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { SITE_URL } = require('./host');
let DATA_DIR = null, SEEDS = [], ready = null;
let cache = null, cacheAt = 0, index = null;
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
function stem(w) {
if (SYN[w]) return SYN[w];
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
return w;
}
function words(text) {
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
}
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
function terms(text) {
const w = words(text), out = w.slice();
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
return out;
}
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
const K1 = 1.2, B = 0.75;
function fieldText(e, f) {
if (f === 'questions') return (e.questions || []).join(' . ');
if (f === 'tags') return (e.tags || []).join(' . ');
return e[f] || '';
}
function buildIndex(entries) {
const docs = entries.map(e => {
const d = { e, f: {} };
for (const f of Object.keys(FIELDS)) {
const t = terms(fieldText(e, f)), tf = new Map();
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
d.f[f] = { tf, len: t.length };
}
return d;
});
const df = new Map(), avg = {};
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
for (const d of docs) {
const seen = new Set();
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
}
return { docs, df, avg, n: docs.length };
}
function rank(idx, query, k) {
if (!idx || !idx.n) return [];
const qt = [...new Set(terms(query))];
if (!qt.length) return [];
const out = [];
for (const d of idx.docs) {
let s = 0;
for (const t of qt) {
const n = idx.df.get(t); if (!n) continue;
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
for (const f of Object.keys(FIELDS)) {
const tf = d.f[f].tf.get(t); if (!tf) continue;
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
}
}
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
}
out.sort((a, b) => b.score - a.score);
return out.slice(0, k || 5);
}
// keep hits that are close to the best one, and only when the best is a real match
const MIN_SCORE = 3;
function relevant(hits) {
if (!hits.length || hits[0].score < MIN_SCORE) return [];
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
return hits.filter(h => h.score >= floor);
}
// ---------------------------------------------------------------- store
const J = {
file: () => path.join(DATA_DIR, 'kb.json'),
async ensure() {},
async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
async put(e) {
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
if (i >= 0) all[i] = e; else all.push(e);
const tmp = J.file() + '.tmp';
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
fs.renameSync(tmp, J.file());
}
};
const store = () => J;
// ---------------------------------------------------------------- seeds
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
function seedEntry(s) {
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
order: s.order == null ? null : s.order, source: s.source || 'faq' };
}
async function syncSeeds() {
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
const seedIds = new Set(SEEDS.map(s => s.id));
let added = 0, refreshed = 0, retired = 0;
for (const s of SEEDS) {
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
}
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
}
function init(opts) {
DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null;
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
return ready;
}
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
const all = await store().all();
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
return cache;
}
const rx = new Map();
function compiled(src) {
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
return rx.get(src);
}
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
// ---------------------------------------------------------------- the chatbot side
async function fastPath(msg) {
const list = (await load()).filter(e => e.pattern).sort(byOrder);
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
return null;
}
async function search(query, k) { await load(); return rank(index, query, k || 5); }
async function context(query, k) { return relevant(await search(query, k || 5)); }
const HELP = 'Help (' + SITE_URL + '/help, or ' + SITE_URL + '/support when signed out)';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
}
// ---------------------------------------------------------------- the admin side
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
function validate(o, cur) {
o = o || {};
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
const answer = clean(o.answer).slice(0, 4000);
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
if (!title) return { error: 'Give the entry a title or at least one question.' };
if (!answer) return { error: 'The answer is empty.' };
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
}
async function list(q) {
const all = (await load(true)).slice();
if (!q) return all.sort((a, b) => b.updated - a.updated);
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
return ranked.concat(plain);
}
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
async function create(o) {
const v = validate(o); if (v.error) return v;
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function update(id, o) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
const v = validate(o, cur); if (v.error) return v;
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
await store().put(e); await load(true);
return { ok: true, entry: e };
}
async function remove(id) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
return { ok: true };
}
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
// KNOWLEDGE_DATE already speaks for the code.
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function stamp() {
const all = await load();
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
return { updated: max ? ctDay(max) : '', count: all.length };
}
async function test(question) {
const fast = await fastPath(String(question || ''));
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
}
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
+29 -1
View File
@@ -50,6 +50,7 @@
<button data-pane="zones" class="nb" type="button" title="Zones"><svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M8 15h8"/></svg><span class="lbl">Zones</span></button> <button data-pane="zones" class="nb" type="button" title="Zones"><svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M8 15h8"/></svg><span class="lbl">Zones</span></button>
<button data-pane="domains" class="nb" type="button" title="Link domains"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg><span class="lbl">Link domains</span></button> <button data-pane="domains" class="nb" type="button" title="Link domains"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg><span class="lbl">Link domains</span></button>
<button data-pane="blog" class="nb" type="button" title="Blog"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg><span class="lbl">Blog</span></button> <button data-pane="blog" class="nb" type="button" title="Blog"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg><span class="lbl">Blog</span></button>
<button data-pane="kb" class="nb" type="button" title="Knowledge base"><svg viewBox="0 0 24 24"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/><path d="M4 20.5A2.5 2.5 0 0 0 6.5 21H20v-3"/><path d="M9 8h7M9 11.5h5"/></svg><span class="lbl">Knowledge base</span></button>
<button data-pane="releases" class="nb" type="button" title="Releases"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg><span class="lbl">Releases</span></button> <button data-pane="releases" class="nb" type="button" title="Releases"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg><span class="lbl">Releases</span></button>
<button data-pane="pnl" class="nb" type="button" title="P&amp;L"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg><span class="lbl">P&amp;L</span></button> <button data-pane="pnl" class="nb" type="button" title="P&amp;L"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg><span class="lbl">P&amp;L</span></button>
<button data-pane="settings" class="nb" type="button" title="Settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg><span class="lbl">Settings</span></button> <button data-pane="settings" class="nb" type="button" title="Settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg><span class="lbl">Settings</span></button>
@@ -218,6 +219,12 @@
</div> </div>
<div class="pane" id="pane-content" hidden> <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="ct-totals" id="ctTotals"></div>
<div class="card"> <div class="card">
<div class="card-head"><h3>Everything members made</h3><span class="sub" id="ctSub">newest first</span></div> <div class="card-head"><h3>Everything members made</h3><span class="sub" id="ctSub">newest first</span></div>
@@ -349,6 +356,26 @@
</div> </div>
</div> </div>
</div> </div>
<div class="pane" id="pane-kb" hidden>
<div id="kbList">
<div class="card">
<div class="card-head"><h3>Knowledge base</h3><span class="sub" id="kbSub">what the chat assistant answers from</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
<input id="kbQ" class="small" placeholder="Search title, questions, answer, tags" style="flex:1;min-width:200px">
<select id="kbSrc" class="small"><option value="">All sources</option><option value="canned">From the code</option><option value="faq">FAQ</option><option value="ticket">From tickets</option><option value="admin">Added here</option></select>
<button type="button" class="btn small" id="kbNew">+ New entry</button>
</p>
<div class="tablewrap"><table class="adm-table" id="kbTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>Try a question</h3><span class="sub">which entry answers it, and what the AI is given</span></div>
<p style="display:flex;gap:8px;flex-wrap:wrap;margin:0"><input id="kbTry" class="small" placeholder="Ask it the way a member would" style="flex:1;min-width:200px"><button type="button" class="btn small sec" id="kbTryGo">Test</button></p>
<div id="kbTryOut" class="small"></div>
</div>
<p class="small muted">Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. Entries from the code follow chatbot.js and kb-seed.js until you edit them. LinkSpin tickets are answered on the InstantAdPay support desk: when a reply there is worth keeping for LinkSpin members, add it here with + New entry.</p>
</div>
<div id="kbEdit" class="card" hidden></div>
</div>
<div class="pane" id="pane-releases" hidden> <div class="pane" id="pane-releases" hidden>
<div class="grid c2"> <div class="grid c2">
<div class="card"> <div class="card">
@@ -472,6 +499,7 @@
</div> </div>
<script src="/assets/common.js?v=20261018p25"></script> <script src="/assets/common.js?v=20261018p25"></script>
<script src="/assets/admin.js?v=20261018e1"></script> <script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261020m1"></script>
</body> </body>
</html> </html>
+108
View File
@@ -0,0 +1,108 @@
// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
// entries the chat assistant answers from, and try a question against them. Same file as InstantAdPay's
// admin-kb.js; LinkSpin tickets are answered on the InstantAdPay desk, so fromTicket is unused here.
(function () {
const $ = IAP.$;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function api(path, body, method) {
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
const r = await (await fetch(path, opts)).json();
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
return r;
}
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
let entries = [], filter = { q: '', src: '' }, wired = false;
function wire() {
if (wired) return; wired = true;
let t = null;
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
$('kbNew').addEventListener('click', () => compose({}));
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
const go = async () => {
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
const r = await api('/api/admin/kb/test', { question: q });
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
};
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
}
async function load() {
wire();
$('kbEdit').hidden = true; $('kbList').hidden = false;
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
entries = r.entries || [];
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
draw();
}
function draw() {
const rows = entries.filter(e => !filter.src || e.source === filter.src);
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
}
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
function compose(e) {
wire();
e = e || {};
const isNew = !e.id;
$('kbList').hidden = true; $('kbEdit').hidden = false;
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
+ '<div style="display:grid;gap:10px">'
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
+ '</div>'
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
$('kbSave').addEventListener('click', async () => {
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
try {
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
await load();
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
});
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
});
$('kbTitle').focus();
}
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
function fromTicket(t, question, reply) {
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
}
window.IAPKB = { load: () => load(), compose, fromTicket };
})();
+19 -2
View File
@@ -44,8 +44,8 @@
}); });
// ── panes ── // ── panes ──
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', content: 'Member content', reports: 'Reports', zones: 'Zones', domains: 'Link domains', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' }; const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', content: 'Member content', reports: 'Reports', zones: 'Zones', domains: 'Link domains', traffic: 'Traffic', blog: 'Blog', kb: 'Knowledge base', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, content: loadContent, reports: loadReports, zones: loadZones, domains: loadDomains, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings }; const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, content: loadContent, reports: loadReports, zones: loadZones, domains: loadDomains, traffic: loadTraffic, blog: loadBlog, kb: () => window.IAPKB.load(), releases: loadReleases, pnl: loadPnl, settings: loadSettings };
function setPane(name) { function setPane(name) {
if (!TITLES[name]) name = 'overview'; if (!TITLES[name]) name = 'overview';
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; }); document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
@@ -611,7 +611,24 @@
if ($('ctFrom').value) sp.set('from', $('ctFrom').value); if ($('ctTo').value) sp.set('to', $('ctTo').value); 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'); if ($('ctFlagged').checked) sp.set('flagged', '1'); if (fresh === true) sp.set('fresh', '1');
CT.data = await api('/api/admin/content?' + sp.toString()); drawContent(); 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')); 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); }); $('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(); })); ['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: '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(''); 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; }; 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) { function renderBanners(s) {
const total = s.banners.filter(b => b.active && !b.adminOff).reduce((n, b) => n + b.weight, 0) || 1; 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">' 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 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 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>' + '<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="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>' + '<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('') + (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>'; : '<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) { 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); } 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); 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>'; // seven columns: name, views, second number (uniques for a banner, every image load for a placement), clicks, CTR, matched, last
$('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>'; const cell = (label, v) => '<span class="r num"><span class="ml">' + label + ' </span>' + v + '</span>';
$('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>'; 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)); 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').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>'; $('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).'; 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).';
} }
+1 -1
View File
@@ -418,7 +418,7 @@
if (it.videoUrl && !isVid) links.push('<a class="btn small sec" href="' + esc(it.videoUrl) + '" target="_blank" rel="noopener">Watch</a>'); if (it.videoUrl && !isVid) links.push('<a class="btn small sec" href="' + esc(it.videoUrl) + '" target="_blank" rel="noopener">Watch</a>');
if (it.docUrl) links.push('<a class="btn small sec" href="' + esc(it.docUrl) + '" target="_blank" rel="noopener">Open material</a>'); if (it.docUrl) links.push('<a class="btn small sec" href="' + esc(it.docUrl) + '" target="_blank" rel="noopener">Open material</a>');
return head + '<div class="card"><h3>' + esc(it.title || 'Lesson') + '</h3>' return head + '<div class="card"><h3>' + esc(it.title || 'Lesson') + '</h3>'
+ (it.desc ? '<p class="muted small">' + esc(it.desc) + '</p>' : '') + (it.desc ? '<p class="muted small" style="white-space:pre-line">' + esc(it.desc) + '</p>' : '') // pre-line: a written lesson keeps its paragraphs (Banner Spin, 2026-10-20)
+ (media ? '<p style="margin:10px 0">' + media + '</p>' : '') + (media ? '<p style="margin:10px 0">' + media + '</p>' : '')
+ (links.length ? '<p>' + links.join(' ') + '</p>' : '') + '</div>'; + (links.length ? '<p>' + links.join(' ') + '</p>' : '') + '</div>';
}).join(''); }).join('');
+3
View File
@@ -13,6 +13,7 @@ window.IAPPromo = (function () {
// ── social posts ── // ── social posts ──
const POSTS = [ const POSTS = [
{ net: 'X', label: 'X · Banner Spin', text: 'One banner slot on a traffic exchange, up to 25 banners rotating in it. LinkSpin Banner Spin: one image address, one click address, every click lands on the page of the banner that was shown, and the report tells you which banner wins. Free with your first $25 package: {{LINK:links}}' },
{ net: 'X', label: 'X · one link', text: 'I stopped juggling six affiliate links. One LinkSpin link now rotates every page I promote, with weights, hours and a fallback, and a report by source, country and device. Free, no account needed to try the spin: {{LINK}}' }, { net: 'X', label: 'X · one link', text: 'I stopped juggling six affiliate links. One LinkSpin link now rotates every page I promote, with weights, hours and a fallback, and a report by source, country and device. Free, no account needed to try the spin: {{LINK}}' },
{ net: 'X', label: 'X · instant payout', text: 'No withdraw button. A verified contract on Polygon splits every ad package the second it sells: 50% to the sponsor, 20% to level 2, 10% to level 3, straight to wallets. Watch the ledger move: {{LINK}}' }, { net: 'X', label: 'X · instant payout', text: 'No withdraw button. A verified contract on Polygon splits every ad package the second it sells: 50% to the sponsor, 20% to level 2, 10% to level 3, straight to wallets. Watch the ledger move: {{LINK}}' },
{ net: 'X', label: 'X · advertiser', text: 'Marketers: you were buying traffic anyway. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Packages from $10. Join free: {{LINK:zones}}' }, { net: 'X', label: 'X · advertiser', text: 'Marketers: you were buying traffic anyway. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Packages from $10. Join free: {{LINK:zones}}' },
@@ -43,6 +44,8 @@ window.IAPPromo = (function () {
// ── objection bank (truth + say this) ── // ── objection bank (truth + say this) ──
const OBJECTIONS = [ const OBJECTIONS = [
// Banner Spin (2026-10-20): the add-on that opens with the member's own $25 package
{ q: 'What is Banner Spin?', truth: 'One image address and one click address that rotate up to 25 banners, each with its own target page or spin link. The member pastes it once into a banner slot (traffic exchange, safelist, forum signature, their own site) and changes the banners from the Control Room. A click goes to the banner that visitor saw, unmatched clicks go to a fallback, and reports show views, clicks, click rate and conversions per banner and per placement, with a WINNER badge once two banners have 1,000 views each. It is a free add-on with the member\'s own package of $25 or more: Starter 2 Banner Spins x 5 banners, Builder (2 qualifying buyers) 5 x 15, Leader (5 qualifying buyers) 10 x 25. It does not rotate inside paid ad networks or Gmail, which keep their own copy of the image.', say: 'You know how every exchange gives you one banner slot? Banner Spin turns that slot into a rotation of up to 25 banners, each going to its own page, and tells you which one gets the clicks. Set it once, swap banners any time from your dashboard. It comes free with your first $25 package: {{LINK}}' },
{ q: 'What is a spin link?', truth: 'One short link on a LinkSpin link domain that rotates visitors through a list of destination pages by weight. Each destination can be paused, limited to hours of the day, capped per day, or pointed at a fallback. Clicks are reported by source, country and device, and tracker macros are filled on the way through. The rotator is free and needs no package.', say: 'It is one link that stands in for all of yours. You give it the pages you promote and how often each should show, and it rotates visitors through them. Pause a page, cap it, give it hours. Free, and you can try a spin before you even sign up: {{LINK}}' }, { q: 'What is a spin link?', truth: 'One short link on a LinkSpin link domain that rotates visitors through a list of destination pages by weight. Each destination can be paused, limited to hours of the day, capped per day, or pointed at a fallback. Clicks are reported by source, country and device, and tracker macros are filled on the way through. The rotator is free and needs no package.', say: 'It is one link that stands in for all of yours. You give it the pages you promote and how often each should show, and it rotates visitors through them. Pause a page, cap it, give it hours. Free, and you can try a spin before you even sign up: {{LINK}}' },
{ q: 'Which crypto do I get paid in?', truth: 'One coin, one network: POL, the native coin of Polygon. Packages are dollar-priced and settled in POL at the live Chainlink rate; every payout is sent as POL to the recipient\'s own Polygon wallet in the same transaction. No tokens, no other chains, no stablecoins.', say: 'You get paid in POL, which is Polygon\'s own coin, straight into your wallet the moment a package in your line sells. Any Polygon wallet works, SafePal, MetaMask, Phantom, and if you have never held crypto there is a card on-ramp inside the control room. {{LINK}}' }, { q: 'Which crypto do I get paid in?', truth: 'One coin, one network: POL, the native coin of Polygon. Packages are dollar-priced and settled in POL at the live Chainlink rate; every payout is sent as POL to the recipient\'s own Polygon wallet in the same transaction. No tokens, no other chains, no stablecoins.', say: 'You get paid in POL, which is Polygon\'s own coin, straight into your wallet the moment a package in your line sells. Any Polygon wallet works, SafePal, MetaMask, Phantom, and if you have never held crypto there is a card on-ramp inside the control room. {{LINK}}' },
{ q: 'Is this a pyramid scheme?', truth: 'There is a real product with no referral needed: the rotator, the page builder and the zone script are free tools, and the paid product is ad delivery at one cent per credit across seven live formats that members can watch serving. Sponsor payments are referral commissions written as constants in a verified contract, paid only when a real package sells. Nobody has to recruit, and joining costs nothing.', say: 'Fair question. Here is the test I use: is there something people would use with no referral involved? Here there is, and most of it is free: a link rotator, a page builder, an ad slot for your site. The paid product is advertising you can watch run. The sponsor split is a referral commission on those sales, fixed in a public contract. Join free and never refer anyone if you like. {{LINK:stack}}' }, { q: 'Is this a pyramid scheme?', truth: 'There is a real product with no referral needed: the rotator, the page builder and the zone script are free tools, and the paid product is ad delivery at one cent per credit across seven live formats that members can watch serving. Sponsor payments are referral commissions written as constants in a verified contract, paid only when a real package sells. Nobody has to recruit, and joining costs nothing.', say: 'Fair question. Here is the test I use: is there something people would use with no referral involved? Here there is, and most of it is free: a link rotator, a page builder, an ad slot for your site. The paid product is advertising you can watch run. The sponsor split is a referral commission on those sales, fixed in a public contract. Join free and never refer anyone if you like. {{LINK:stack}}' },
+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: '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: '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: '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))); 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').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(''); $('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 || []; 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>'; $('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>'; $('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: [] }; const zn = s.zones || { byDay: [], byZone: [] };
// bar = all views, lighter inner share = the ones that were NOT viewable // 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'); 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} .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} .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} .bsr .ml{display:none}
.st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 90px 80px 70px 80px 70px} .st3 .hd,.st3 .rw{grid-template-columns:minmax(0,2fr) 80px 70px 70px 64px 74px 56px}
@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 .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}} @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> </style>
</head> </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 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>
<div id="bs-stats" hidden> <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"><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">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>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 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>
</div> </div>
@@ -239,6 +242,6 @@
</div> </div>
<script src="/assets/cr-shell.js?v=20261018c"></script> <script src="/assets/cr-shell.js?v=20261018c"></script>
<script src="/assets/links.js?v=20261018bs"></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> </body>
</html> </html>
+2 -2
View File
@@ -1011,8 +1011,8 @@
<script src="/assets/cr-shell.js?v=20261018c"></script> <script src="/assets/cr-shell.js?v=20261018c"></script>
<script src="/assets/tools.js?v=20261011a"></script> <script src="/assets/tools.js?v=20261011a"></script>
<script src="/assets/wallet.js?v=20261018a"></script> <script src="/assets/wallet.js?v=20261018a"></script>
<script src="/assets/promo.js?v=20261009b"></script> <script src="/assets/promo.js?v=20261020bs3"></script>
<script src="/assets/my.js?v=20261018pe1"></script> <script src="/assets/my.js?v=20261020bs3"></script>
<script src="/assets/chat.js?v=20261016a"></script> <script src="/assets/chat.js?v=20261016a"></script>
</body> </body>
</html> </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)} .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} .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} .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} .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> </style>
</head> </head>
<body> <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>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 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> </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) --> <!-- 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="sec">Zones</div>
<div class="two sect"> <div class="two sect">
@@ -71,6 +90,6 @@
</div> </div>
</div> </div>
<script src="/assets/cr-shell.js?v=20261018c"></script> <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> </body>
</html> </html>
+145 -3
View File
@@ -2,6 +2,9 @@
// no DB, no mail key, devCode sign-in, no chain-writing keys), builds a Banner Spin with 3 banners through the Links // no DB, no mail key, devCode sign-in, no chain-writing keys), builds a Banner Spin with 3 banners through the Links
// screen UI, then plays simulated visitors against /i/, /c/ and /s/ on a link domain and checks matching, fallback, // screen UI, then plays simulated visitors against /i/, /c/ and /s/ on a link domain and checks matching, fallback,
// counters, headers, tier limits, URL tokens, conversions, the admin kill switch and the admin Member content pane. // counters, headers, tier limits, URL tokens, conversions, the admin kill switch and the admin Member content pane.
// Phase 3 + 4 (2026-10-20): image health auto-pause / resume (a corrupted upload, a dead target, the last live banner),
// the winner badge, bots and servers kept apart, the "caches banners" flag, the traffic-source postback, the Reports
// screen, the admin Banner Spin switch button, the chatbot answer, the Training lesson, Promo tools and the release draft.
// node qa/bannerspin.mjs (from the site dir) // node qa/bannerspin.mjs (from the site dir)
// Env: PORT (default 8961), PW (playwright package dir), SHOTS (screenshot dir, default D:/tmp/banner-spin) // Env: PORT (default 8961), PW (playwright package dir), SHOTS (screenshot dir, default D:/tmp/banner-spin)
import { pathToFileURL } from 'node:url'; import { pathToFileURL } from 'node:url';
@@ -98,6 +101,56 @@ try {
const lockedUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cL, body: IMG.a, headers: { 'Content-Type': 'image/png' } }); const lockedUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cL, body: IMG.a, headers: { 'Content-Type': 'image/png' } });
check(lockedUp.status === 403, 'locked member cannot upload', String(lockedUp.status)); check(lockedUp.status === 403, 'locked member cannot upload', String(lockedUp.status));
// ════ phase 3 (2026-10-20): image health checks + the winner badge, on the builder's own Banner Spin ════
// Runs first, before the scheduled health pass (2 minutes after boot), so only the admin "run checks" passes below count.
const AUTH = { Authorization: 'Bearer ' + ADMIN_PW };
const rotB = await req('POST', '/api/my/rotations', { cookie: cB, body: { name: 'Builder invite' } });
await req('POST', '/api/my/rotations/' + rotB.json.rotation.id + '/dest', { cookie: cB, body: { url: 'https://spin-dest.example/b', weight: 10 } });
const hsp = await req('POST', '/api/my/bannerspins', { cookie: cB, body: { name: 'Health test', size: '468x60', fallback: 'https://fallback.example/b' } });
const HID = hsp.json.spin.id, HCODE = hsp.json.spin.code;
const hImg = [png(468, 60, [250, 120, 0]), png(468, 60, [0, 200, 200]), png(468, 60, [120, 0, 200])]; const hByHash = {}; hImg.forEach((b, i) => { hByHash[sha(b)] = i + 1; });
const hUp = []; for (const b of hImg) hUp.push((await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cB, body: b, headers: { 'Content-Type': 'image/png' } })).json);
for (const [i, u] of hUp.entries()) await req('POST', '/api/my/bannerspins/' + HID + '/banner', { cookie: cB, body: i < 2 ? { image: u.url, link: rotB.json.rotation.id, label: 'H' + (i + 1), weight: 10 } : { image: u.url, target: 'https://nowhere.invalid/offer', label: 'H3 dead target', weight: 10 } });
const hFile = i => path.join(DATA, 'uploads', hUp[i].url.split('/').pop());
const hRun = async () => (await req('POST', '/api/admin/bannerspins/health', { headers: AUTH, body: { id: HID } })).json;
const hGet = async () => (await req('GET', '/api/my/bannerspins', { cookie: cB })).json.spins.find(x => x.id === HID);
const bOf = (sp, id) => sp.banners.find(b => b.id === id);
const hDesc = sp => sp.banners.map(b => b.id + ':' + (b.health ? b.health.state + '/' + b.health.fails : '-') + (b.active ? ' live' : ' off') + (b.autoPaused ? ' auto' : '')).join(', ');
const hr1 = await hRun(); let H = await hGet();
check(hr1 && hr1.checked === 3 && bOf(H, 1).health.state === 'ok' && bOf(H, 2).health.state === 'ok' && bOf(H, 3).health.state === 'dead' && bOf(H, 3).active, 'health: one pass checks image + target of every live banner (spin-link target ok, dead target failing, nothing paused yet)', (hr1 && hr1.checked) + ' checked; ' + hDesc(H));
const good1 = fs.readFileSync(hFile(0)), good2 = fs.readFileSync(hFile(1));
fs.writeFileSync(hFile(0), Buffer.from('this is not an image at all')); // simulate a broken image
await hRun(); await hRun(); H = await hGet();
check(!bOf(H, 3).active && bOf(H, 3).autoPaused && bOf(H, 1).active && bOf(H, 1).health.state === 'image' && bOf(H, 1).health.fails === 2, 'health: 3 failing checks in a row pause a banner (dead target), 2 do not (broken image so far)', hDesc(H));
await hRun(); H = await hGet();
check(!bOf(H, 1).active && bOf(H, 1).autoPaused && /not a readable image/.test(bOf(H, 1).health.note), 'health: a broken image is auto-paused on its 3rd failing check', hDesc(H) + ' · ' + bOf(H, 1).health.note);
let hSeenOff = 0; for (let i = 0; i < 30; i++) { const r = await req('GET', '/i/' + HCODE + '.gif', { host: LINK, ip: '10.20.0.' + i, referer: 'https://h.example/' }); const id = hByHash[sha(r.buf)]; if (id !== 2) hSeenOff++; }
check(hSeenOff === 0, 'auto-paused banners never serve (30 loads, all the one live banner)', hSeenOff + ' of 30 were not banner 2');
fs.writeFileSync(hFile(1), Buffer.from('broken too'));
await hRun(); await hRun(); await hRun(); H = await hGet();
check(bOf(H, 2).active && !bOf(H, 2).autoPaused && bOf(H, 2).health.fails >= 3 && /Kept live/.test(bOf(H, 2).health.note), 'health: the last live banner is never auto-paused', hDesc(H) + ' · ' + bOf(H, 2).health.note);
fs.writeFileSync(hFile(0), good1); fs.writeFileSync(hFile(1), good2); // the images are fixed
await hRun(); H = await hGet(); const oneClean = !bOf(H, 1).active;
await hRun(); H = await hGet();
check(oneClean && bOf(H, 1).active && !bOf(H, 1).autoPaused && bOf(H, 2).active && bOf(H, 2).health.state === 'ok' && !bOf(H, 3).active, 'health: 2 clean passes resume the auto-paused banner (1 is not enough); the dead target stays paused', hDesc(H));
const hLog = await req('GET', '/api/admin/bannerspins', { headers: AUTH });
check(hLog.status === 200 && hLog.json.spins.some(x => x.id === HID), 'admin Banner Spin list still answers after the checks');
// winner badge: no badge until two live banners have 1,000 views each and one leads on CTR
let wst = (await req('GET', '/api/my/bannerspins/' + HID + '/stats', { cookie: cB })).json;
check(!wst.winner && wst.banners.every(b => !b.winner), 'no winner badge before 1,000 views each', JSON.stringify(wst.banners.map(b => [b.id, b.imps, b.clicks])));
for (let i = 0; i < 40; i++) await req('GET', '/c/' + HCODE + '?x=' + (i < 30 ? 1 : 2), { host: LINK, ip: '10.21.0.' + i, ua: 'Mozilla/5.0 Clicker' + i, referer: 'https://h.example/' });
// 1,500 views each, added straight to the counters file the way a second app copy's flush would (read, add, write)
await sleep(6000);
const cFile = path.join(DATA, 'bannerspin-counts.json'); const cj = JSON.parse(fs.readFileSync(cFile, 'utf8'));
const ctToday = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date());
const hd = cj.d[String(HID)] = cj.d[String(HID)] || {}; const hdd = hd[ctToday] = hd[ctToday] || { b: {}, h: {}, u: {} };
hdd.b['1'] = (hdd.b['1'] || 0) + 1500; hdd.b['2'] = (hdd.b['2'] || 0) + 1500; fs.writeFileSync(cFile, JSON.stringify(cj));
await req('GET', '/i/' + HCODE + '.gif', { host: LINK, ip: '10.22.0.1', referer: 'https://h.example/' }); // marks the counters dirty, so the next flush reads the file back
await sleep(6500);
wst = (await req('GET', '/api/my/bannerspins/' + HID + '/stats', { cookie: cB })).json;
check(wst.winner === 1 && wst.banners.find(b => b.id === 1).winner && !wst.banners.find(b => b.id === 2).winner, 'winner badge: banner 1 leads on CTR with 1,000+ views on both', JSON.stringify(wst.banners.map(b => [b.id, b.imps, b.clicks, b.ctr, b.winner])));
// a spin link of the starter's own, used as one banner's target // a spin link of the starter's own, used as one banner's target
const rot = await req('POST', '/api/my/rotations', { cookie: cS, body: { name: 'Main invite' } }); const rot = await req('POST', '/api/my/rotations', { cookie: cS, body: { name: 'Main invite' } });
await req('POST', '/api/my/rotations/' + rot.json.rotation.id + '/dest', { cookie: cS, body: { url: 'https://spin-dest.example/landing', weight: 10 } }); await req('POST', '/api/my/rotations/' + rot.json.rotation.id + '/dest', { cookie: cS, body: { url: 'https://spin-dest.example/landing', weight: 10 } });
@@ -243,7 +296,8 @@ try {
check(saw1 === 0, 'one banner taken offline by admin never serves', saw1 + ' of 40'); check(saw1 === 0, 'one banner taken offline by admin never serves', saw1 + ' of 40');
await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: false } }); await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: false } });
const adm = await req('GET', '/api/admin/content?type=bannerspin&fresh=1', { headers: auth }); const adm = await req('GET', '/api/admin/content?type=bannerspin&fresh=1', { headers: auth });
check(adm.json && adm.json.items && adm.json.items.length === 1 && adm.json.items[0].detail.banners.length === 3 && adm.json.items[0].actions.length === 4, 'admin Member content lists the Banner Spin with its banners + actions', adm.json && JSON.stringify(adm.json.totals.bannerspin)); const admS = adm.json && adm.json.items && adm.json.items.find(x => x.id === String(S.id)); // the builder's health-test Banner Spin is listed too since phase 3
check(admS && adm.json.items.length === 2 && admS.detail.banners.length === 3 && admS.actions.length === 4, 'admin Member content lists the Banner Spin with its banners + actions', adm.json && JSON.stringify(adm.json.totals.bannerspin));
// ── one-per-visitor mode: the same banner all day ── // ── one-per-visitor mode: the same banner all day ──
await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'visitor' } }); await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'visitor' } });
@@ -267,6 +321,89 @@ try {
const bigUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.big, headers: { 'Content-Type': 'image/png' } }).catch(e => ({ status: 'reset' })); const bigUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.big, headers: { 'Content-Type': 'image/png' } }).catch(e => ({ status: 'reset' }));
check(bigUp.status === 400 || bigUp.status === 'reset', 'server refuses an image over 150 KB', String(bigUp.status) + ' (' + IMG.big.length + ' bytes)'); check(bigUp.status === 400 || bigUp.status === 'reset', 'server refuses an image over 150 KB', String(bigUp.status) + ' (' + IMG.big.length + ' bytes)');
// ════ phase 3: traffic-source postback end to end on a Banner Spin click ════
const srcR = await req('POST', '/api/my/sources', { cookie: cS, body: { name: 'QA Network', template: 'custom', params: [{ key: 'clickid', token: '{clickid}' }], postbackUrl: 'https://example.com/pb?cid={clickid}&ev={event}&pay={payout}&ls={lsid}', events: ['join', 'lead', 'purchase', 'external'] } });
const SRC = srcR.json && srcR.json.source;
const attach = SRC ? await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { sourceId: SRC.id } }) : null;
check(!!SRC && attach && attach.status === 200 && attach.json.spin.sourceId === SRC.id, 'a traffic source attaches to the Banner Spin', srcR.buf.toString().slice(0, 120));
const pc = await req('GET', clickPath + '?x=1&clickid=NET-777', { host: LINK, ip: '10.12.0.1', ua: 'Mozilla/5.0 Buyer', referer: 'https://forum-a.example/' });
const pls = /sub=(k[0-9a-f]{11})/.exec(pc.headers.location || '');
const convBefore = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.conversions;
const pin = pls ? await req('GET', '/pb/in?key=' + pb.key + '&lsid=' + pls[1] + '&event=sale&value=2.50') : null; // waits for the outbound postback (real network, example.com)
let slog = null; for (let i = 0; i < 20 && SRC; i++) { const g = await req('GET', '/api/my/sources/' + SRC.id, { cookie: cS }); slog = ((g.json && g.json.log) || [])[0] || null; if (slog) break; await sleep(500); }
check(pin && pin.status === 200 && slog && /cid=NET-777/.test(slog.url) && /ev=external/.test(slog.url) && /pay=2\.5/.test(slog.url) && slog.url.includes('ls=' + pls[1]), 'Banner Spin conversion fires the traffic source postback with the network click id, event, payout and lsid', slog ? slog.url + ' -> ' + (slog.ok ? 'delivered HTTP ' + slog.status : 'not delivered: ' + (slog.status || '') + ' ' + slog.note) : pin && pin.buf.toString().slice(0, 120));
const convAfter = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.conversions;
check(convAfter === convBefore + 1, 'that conversion is credited to the Banner Spin', convBefore + ' -> ' + convAfter);
// ════ phase 3: bots and servers kept apart, the "caches banners" flag ════
await sleep(6000); const stA = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json;
for (let i = 0; i < 8; i++) await req('GET', imgPath, { host: LINK, ip: '10.13.0.1', ua: 'Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko Firefox/11.0 (via ggpht.com GoogleImageProxy)' }); // a mail image proxy, no referrer
for (let i = 0; i < 12; i++) await req('GET', clickPath, { host: LINK, ip: '10.14.0.' + i, ua: 'Mozilla/5.0 Exchange' + i, referer: 'https://cachex.example/surf' }); // an exchange showing its own copy: clicks, no views
await sleep(6500); const stB = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json;
check(stB.totals.imps === stA.totals.imps && stB.totals.serverLoads >= stA.totals.serverLoads + 8 && stB.totals.botLoads >= 10, 'image-proxy and bot loads are shown separately, never as views', 'views ' + stA.totals.imps + ' -> ' + stB.totals.imps + ', server loads ' + stB.totals.serverLoads + ', bot loads ' + stB.totals.botLoads);
const pCache = stB.placements.find(p => p.host === 'cachex.example'), pNone = stB.placements.find(p => p.host === '(none)'), pForum = stB.placements.find(p => p.host === 'forum-a.example');
const pSafe = stB.placements.find(p => p.host === 'safelist-c.example'); // more clicks than views in this test (clicks are not deduped) but every one matched: no flag
check(pCache && /frozen/.test(pCache.caches) && pNone && /server/.test(pNone.caches) && pForum && !pForum.caches && pSafe && !pSafe.caches, '"caches banners" flag on the copying exchange and the image proxy, not on a normal placement', JSON.stringify([pCache && pCache.caches, pNone && pNone.caches, pForum && pForum.caches]).slice(0, 300));
check(Array.isArray(stB.country) && stB.device.some(d => d.k === 'mobile') && stB.device.some(d => d.k === 'desktop') && stB.days.length >= 1 && stB.days[stB.days.length - 1].day === ctToday, 'stats break clicks down by country and device, days are Central time', JSON.stringify(stB.device) + ' last day ' + (stB.days.slice(-1)[0] || {}).day);
// ════ phase 3: the Reports screen (totals beside spin links, per banner, per placement) ════
const repS = (await req('GET', '/api/my/reports?days=30', { cookie: cS })).json;
const rb = repS && repS.bannerSpins;
check(rb && rb.count === 2 && rb.totals.imps === stB.totals.imps && rb.totals.clicks === stB.totals.clicks && rb.banners.some(b => b.spinId === S.id) && rb.placements.some(p => p.host === 'cachex.example' && p.caches) && repS.totals && repS.top, 'Reports API: Banner Spin totals match the Stats tab and sit beside the spin-link report', rb && JSON.stringify(rb.totals));
const repB = (await req('GET', '/api/my/reports?days=7', { cookie: cB })).json;
check(repB.bannerSpins && repB.bannerSpins.banners.some(b => b.spinId === HID && b.id === 1 && b.winner), 'Reports API: the winner badge shows on Reports too', repB.bannerSpins && JSON.stringify(repB.bannerSpins.banners.map(b => [b.id, b.imps, b.ctr, b.winner])));
await page.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsRowsB .rw', { timeout: 15000 }); await page.waitForTimeout(600);
check(await page.locator('#bsRowsP [data-caches="cachex.example"]').count() === 1 && /Banner views/.test(await page.textContent('#tiles')), 'Reports screen: Banner Spin section with the CACHED placement and the totals tiles');
await page.locator('#bsSect').scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(SHOTS, 'reports-desktop.png'), fullPage: true });
const ctxB = await browser.newContext({ viewport: { width: 1360, height: 950 } });
await ctxB.addCookies(cB.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
const pB = await ctxB.newPage(); pB.on('pageerror', e => pageErrors.push('builder: ' + e.message));
await pB.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await pB.waitForSelector('#bsRowsB [data-winner]', { timeout: 15000 });
await pB.locator('#bsSect').scrollIntoViewIfNeeded(); await pB.screenshot({ path: path.join(SHOTS, 'reports-winner.png'), fullPage: true });
check(true, 'Reports screen shows the WINNER badge');
// the builder: health status on every banner row, the winner on the Stats tab
await pB.goto(BASE + '/links#b' + HID, { waitUntil: 'domcontentloaded' }); await pB.waitForSelector('#bsRows [data-bhealth]', { timeout: 15000 });
const rowsTxt = await pB.textContent('#bsRows');
check(await pB.locator('#bsRows [data-bhealth="ok"]').count() === 2 && await pB.locator('#bsRows [data-bhealth="paused"]').count() === 1 && /AUTO-PAUSED/.test(rowsTxt) && /Target page is down/.test(rowsTxt), 'builder shows each banner\'s health (2 OK, 1 auto-paused with the reason)', rowsTxt.replace(/\s+/g, ' ').slice(0, 300));
await pB.screenshot({ path: path.join(SHOTS, 'builder-health.png'), fullPage: true });
await pB.click('#bsTabs button[data-tab="stats"]'); await pB.waitForSelector('#bsStB [data-winner="1"]', { timeout: 10000 }); await pB.screenshot({ path: path.join(SHOTS, 'builder-stats-winner.png'), fullPage: true });
check(true, 'builder Stats tab shows the WINNER badge');
// ════ phase 4: the admin switch is a real button (Admin > Member content) ════
const ctxA = await browser.newContext({ viewport: { width: 1360, height: 950 } }); const pA = await ctxA.newPage(); pA.on('pageerror', e => pageErrors.push('admin: ' + e.message));
await pA.goto(BASE + '/admin#content', { waitUntil: 'domcontentloaded' });
await pA.fill('#adEmail', 'admin@bs.test'); await pA.click('#adSend'); await pA.waitForSelector('#adVerify:not([hidden])', { timeout: 10000 }); await pA.waitForFunction(() => document.getElementById('adCode').value.length > 0, null, { timeout: 10000 });
await pA.click('#adVerify'); await pA.waitForSelector('#pane-content:not([hidden])', { timeout: 15000 }).catch(async () => { await pA.click('.bo-menu [data-pane="content"]'); await pA.waitForSelector('#pane-content:not([hidden])', { timeout: 10000 }); });
await pA.waitForFunction(() => /Switch Banner Spin off/.test(document.getElementById('bsSwitchBtn').textContent) && !document.getElementById('bsSwitchBtn').disabled, null, { timeout: 15000 });
check(/live/.test(await pA.textContent('#bsSwitchState')), 'admin shows the Banner Spin switch, live', await pA.textContent('#bsSwitchState'));
await pA.click('#bsSwitchBtn'); await pA.waitForSelector('#dlgOk', { timeout: 5000 }); await pA.screenshot({ path: path.join(SHOTS, 'admin-switch-confirm.png') }); await pA.click('#dlgOk');
await pA.waitForFunction(() => /switched off/.test(document.getElementById('bsSwitchState').textContent), null, { timeout: 10000 });
await pA.screenshot({ path: path.join(SHOTS, 'admin-switch-off.png') });
const gOff = (await req('GET', '/api/admin/bannerspins', { headers: AUTH })).json.settings.off;
const offImg = await req('GET', imgPath, { host: LINK, ip: '10.15.0.1', referer: 'https://forum-a.example/' }); const offClk = await req('GET', clickPath, { host: LINK, ip: '10.15.0.1', referer: 'https://forum-a.example/' });
const memberSees = (await req('GET', '/api/my/bannerspins', { cookie: cS })).json.off;
check(gOff === true && blankOf(offImg) && expectTarget[0].test(offClk.headers.location || '') && memberSees === true, 'admin button switches Banner Spin off: blank image, fallback click, members see the notice', 'off=' + gOff + ' member off=' + memberSees + ' click ' + offClk.headers.location);
await pA.click('#bsSwitchBtn'); await pA.waitForFunction(() => /live/.test(document.getElementById('bsSwitchState').textContent), null, { timeout: 10000 });
const onImg = await req('GET', imgPath, { host: LINK, ip: '10.15.0.2', referer: 'https://forum-a.example/' });
const gOn = (await req('GET', '/api/admin/bannerspins', { headers: AUTH })).json.settings.off;
check(gOn === false && onImg.status === 200 && !blankOf(onImg), 'admin button switches it back on and banners serve again', 'off=' + gOn + ', image ' + onImg.status + ' ' + onImg.buf.length + ' bytes');
await pA.click('#bsHealthBtn'); await pA.waitForTimeout(1500); // the "run banner checks" button answers (it checks every Banner Spin)
await ctxA.close();
// ════ phase 4: chatbot, training, promo tools, release draft ════
const chat = await req('POST', '/api/chat', { body: { message: 'What is Banner Spin and how do I embed it?' } });
const ans = (chat.json && chat.json.reply) || '';
check(chat.json && chat.json.canned && /Banner Spin/.test(ans) && /\$25/.test(ans) && /Gmail/.test(ans) && /paid ad networks/.test(ans) && /25 banners/.test(ans) && !/—/.test(ans), 'chatbot: canned Banner Spin answer (tiers, embeds, Gmail + paid-network limits, no em dash)', ans.slice(0, 160));
const chat2 = await req('POST', '/api/chat', { body: { message: 'how do I edit my banner ad' } });
check(chat2.json && /Ads in your Control Room/.test(chat2.json.reply || ''), 'chatbot: the ad-editing answer still wins for "edit my banner ad"', (chat2.json.reply || '').slice(0, 80));
const tr = (await req('GET', '/api/training', { cookie: cS })).json;
const trB = (tr.items || []).find(x => x.id === 'banner-spin');
check(trB && /Gmail/.test(trB.desc) && /1,000 views/.test(trB.desc) && !/—/.test(trB.desc), 'Training lists the Banner Spin lesson', trB && trB.title);
const promoJs = (await req('GET', '/assets/promo.js')).buf.toString();
check(/What is Banner Spin\?/.test(promoJs) && /X · Banner Spin/.test(promoJs), 'Promo tools carry a Banner Spin entry (objection bank + social post)');
const rel = (await req('GET', '/api/releases')).json; const draft = JSON.parse(fs.readFileSync(path.join(site, 'docs', 'release-drafts', '2026-10-20-banner-spin.json'), 'utf8'));
check(draft.title && draft.body && !/—/.test(draft.body) && !(rel.notes || []).some(n => /Banner Spin/.test(n.title)), 'release note is a draft file only, not published', draft.title);
// ── phone width screenshots ── // ── phone width screenshots ──
const ph = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }); const ph = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
await ph.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); await ph.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
@@ -277,8 +414,13 @@ try {
check(overflow <= 2, 'no horizontal page scroll at phone width', overflow + ' px'); check(overflow <= 2, 'no horizontal page scroll at phone width', overflow + ' px');
await pp.click('#bsTabs button[data-tab="code"]'); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-code.png'), fullPage: true }); await pp.click('#bsTabs button[data-tab="code"]'); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-code.png'), fullPage: true });
await pp.click('#bsTabs button[data-tab="stats"]'); await pp.waitForTimeout(800); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-stats.png'), fullPage: true }); await pp.click('#bsTabs button[data-tab="stats"]'); await pp.waitForTimeout(800); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-stats.png'), fullPage: true });
await page.reload({ waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 }); await page.goto(BASE + '/links#b' + S.id, { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 }); // the Reports step moved this page off /links
await page.click('#bsTabs button[data-tab="stats"]'); await page.waitForTimeout(1000); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-stats.png'), fullPage: true }); await page.click('#bsTabs button[data-tab="stats"]'); await page.waitForSelector('#bsStP [data-caches]', { timeout: 10000 }); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-stats.png'), fullPage: true });
check(await page.locator('#bsStP [data-caches="cachex.example"]').count() === 1 && /mobile/.test(await page.textContent('#bsStD')) && /server/.test(await page.textContent('#bsStBots')), 'builder Stats tab: CACHED placement, device breakdown, bots and servers line');
await pp.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await pp.waitForSelector('#bsRowsB .rw', { timeout: 15000 }); await pp.waitForTimeout(600);
await pp.screenshot({ path: path.join(SHOTS, 'reports-phone.png'), fullPage: true });
const rOverflow = await pp.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
check(rOverflow <= 2, 'Reports: no horizontal page scroll at phone width', rOverflow + ' px');
await page.click('#vsw button[data-v="links"]'); await page.waitForTimeout(800); await page.click('#vsw button[data-v="links"]'); await page.waitForTimeout(800);
check(!(await page.isHidden('#ws')) && await page.isHidden('#bsWs'), 'switching back to Spin links works'); check(!(await page.isHidden('#ws')) && await page.isHidden('#bsWs'), 'switching back to Spin links works');
check(pageErrors.length === 0, 'no page errors in the builder', pageErrors.slice(0, 3).join(' | ')); check(pageErrors.length === 0, 'no page errors in the builder', pageErrors.slice(0, 3).join(' | '));
+131
View File
@@ -0,0 +1,131 @@
// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20).
// node qa/kb-chat.mjs (or: bash qa/run.sh kb) LinkSpin copy of InstantAdPay's qa/kb-chat.mjs
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB) and a mock OpenRouter that
// records every request and answers from the "Knowledge base" block it was given. Nothing touches production:
// OPENROUTER_URL points at the mock and the key is a throwaway string.
// Covers: the Coinbase question answered from the KB through the AI path, the CANNED fast path served from the
// KB (no AI call), an off-topic question told to say "I'm not sure, ask support", admin create / edit / test /
// delete, an admin edit to a canned entry changing the instant answer, and /api/chat/kb-stamp. Exit 1 on failure.
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.KB_PORT || 8799), MOCK = PORT + 100;
const B = 'http://127.0.0.1:' + PORT;
const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-kb-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
// -- the mock OpenRouter: answers with the first KB answer it was handed, or the not-sure line
const calls = [];
const mock = http.createServer((req, res) => {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
let body = {}; try { body = JSON.parse(raw); } catch (e) {}
calls.push({ url: req.url, auth: req.headers.authorization, body });
const sys = ((body.messages || [])[0] || {}).content || '';
const m = /\nAnswer: ([^\n]+)/.exec(sys.slice(sys.indexOf('KNOWLEDGE BASE')));
const content = m ? m[1] : "I'm not sure, ask support: open Help in your Control Room.";
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end('\n\n' + JSON.stringify({ choices: [{ message: { content } }] })); // keepalive padding first, like the real thing
});
});
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
let srv = null, srvLog = '';
async function boot() {
srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN,
OPENROUTER_API_KEY: 'qa-throwaway', OPENROUTER_URL: 'http://127.0.0.1:' + MOCK + '/api/v1/chat/completions', DATABASE_URL: '' }) });
srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
}
async function halt() { if (!srv) return; const s = srv; srv = null; s.kill(); await new Promise(r => { s.once('exit', r); setTimeout(r, 3000); }); await sleep(300); }
const cleanup = async () => { try { await halt(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
await boot();
const api = async (p, data, method, hdr) => { const r = await fetch(B + p, data !== undefined || method ? { method: method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: data === undefined ? undefined : JSON.stringify(data) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
const chat = message => api('/api/chat', { message }, 'POST'); // six questions in all, under the 10-a-minute chat limit
// 1. seeds landed in DATA_DIR/kb.json
await sleep(300);
const list0 = await api('/api/admin/kb', undefined, undefined, adminH);
const ids = (list0.j && list0.j.entries || []).map(e => e.id);
ok(ids.includes('f-coinbase') && ids.includes('c-withdraw') && ids.length >= 40, 'KB seeded from CANNED + FAQ + the Coinbase ticket', ids.length + ' entries');
ok(fs.existsSync(path.join(DATA, 'kb.json')), 'JSON store at DATA_DIR/kb.json');
// 2. the Coinbase question goes to the AI with the Coinbase entry in its knowledge base
let n = calls.length;
const cb = await chat('Can I use my regular Coinbase account?');
const sys = calls[n] && calls[n].body.messages[0].content || '';
ok(cb.status === 200 && calls.length === n + 1, 'Coinbase question goes to the AI path (one call)', 'status ' + cb.status);
ok(sys.includes('KNOWLEDGE BASE') && sys.includes('Coinbase is an exchange') && sys.indexOf('[1] Can I use my regular Coinbase account?') > 0, 'system prompt carries the Coinbase entry first');
ok(sys.includes('NEVER promise or estimate income') && sys.includes('No em dashes'), 'compliance rules still in the prompt');
ok(/open \S+ in SafePal's browser/.test(sys) && !/instantadpay\.com in SafePal/.test(sys), 'Coinbase entry is the LinkSpin wording');
ok(calls[n] && calls[n].body.reasoning && calls[n].body.reasoning.enabled === false, 'reasoning stays off');
ok(cb.j && /Coinbase is an exchange/.test(cb.j.reply) && (cb.j.kb || [])[0] === 'f-coinbase', 'reply drawn from the KB entry', JSON.stringify(cb.j).slice(0, 140));
// 3. the CANNED fast path, now served from the KB: no AI call
n = calls.length;
const wd = await chat('how do I withdraw my money');
ok(wd.j && wd.j.canned && wd.j.kb === 'c-withdraw' && /no withdrawals here/.test(wd.j.reply) && calls.length === n, 'canned answer served from the KB, no AI call', JSON.stringify(wd.j).slice(0, 100));
const sup = await chat('I want to talk to a real person');
ok(sup.j && sup.j.handoff && sup.j.kb === 'c-support', 'support hand-off flag kept on the instant answer');
// 4. nothing fits: the prompt says so and the reply hands off
n = calls.length;
const off = await chat('What is the capital of Mongolia?');
const sys2 = calls[n] && calls[n].body.messages[0].content || '';
ok(/no entry matches this question/.test(sys2) && /I'm not sure, ask support/.test(sys2), 'off-topic: prompt tells the AI to say it is not sure');
ok(off.j && off.j.handoff, 'off-topic reply offers "Send this to support"');
// 5. admin: create, find, test, edit, delete
const cr = await api('/api/admin/kb', { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?', 'Do you take PayPal'], answer: 'No. Packages are paid in POL on Polygon only — PayPal is not accepted.', tags: 'paypal, payment' }, 'POST', adminH);
ok(cr.j && cr.j.ok && cr.j.entry.answer.indexOf('—') < 0, 'admin creates an entry (em dash cleaned)', cr.j && cr.j.entry && cr.j.entry.answer);
const kid = cr.j && cr.j.entry && cr.j.entry.id;
const noAuth = await api('/api/admin/kb', { title: 'x', answer: 'y' }, 'POST');
ok(noAuth.status === 401, 'KB admin routes need the admin');
const t = await api('/api/admin/kb/test', { question: 'do you accept paypal' }, 'POST', adminH);
ok(t.j && t.j.ranked[0] && t.j.ranked[0].id === kid && t.j.ranked[0].used, 'Try a question ranks the new entry first');
n = calls.length;
await chat('can I pay using paypal?');
ok(calls[n] && calls[n].body.messages[0].content.includes('PayPal is not accepted'), 'new entry reaches the AI prompt right away');
const ed = await api('/api/admin/kb/' + kid, { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?'], answer: 'No, PayPal is not accepted. Packages are paid in POL on Polygon.', tags: ['paypal'] }, 'PUT', adminH);
ok(ed.j && ed.j.ok && ed.j.entry.answer.startsWith('No, PayPal'), 'admin edits the entry');
const srch = await api('/api/admin/kb?q=paypal', undefined, undefined, adminH);
ok(srch.j && srch.j.entries[0] && srch.j.entries[0].id === kid, 'admin search finds it');
const bad = await api('/api/admin/kb', { title: 'x', answer: 'y', pattern: '(' }, 'POST', adminH);
ok(bad.status === 400, 'a broken instant-answer pattern is refused');
const del = await api('/api/admin/kb/' + kid, undefined, 'DELETE', adminH);
const gone = await api('/api/admin/kb/' + kid, undefined, undefined, adminH);
ok(del.j && del.j.ok && gone.status === 404, 'admin deletes it');
// 6. editing a canned entry changes the instant answer (one source)
const cw = (await api('/api/admin/kb/c-withdraw', undefined, undefined, adminH)).j.entry;
await api('/api/admin/kb/c-withdraw', Object.assign({}, cw, { answer: cw.answer + ' (edited in QA)' }), 'PUT', adminH);
const wd2 = await chat('how do I withdraw');
ok(wd2.j && /\(edited in QA\)$/.test(wd2.j.reply), 'admin edit to a canned entry is what the fast path serves');
// 7. the sync guard's stamp: today (Central), because a person just edited entries
const st = await api('/api/chat/kb-stamp');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
ok(st.j && st.j.updated === today && st.j.count >= 40, '/api/chat/kb-stamp reports the newest human edit', JSON.stringify(st.j));
// 8. a restart (the seed sync runs again) keeps admin work and does not bring a deleted seed back
await api('/api/admin/kb/f-refunds', undefined, 'DELETE', adminH);
await halt(); await boot();
const after = await api('/api/admin/kb', undefined, undefined, adminH);
const aIds = (after.j && after.j.entries || []).map(e => e.id);
const cw2 = (after.j && after.j.entries || []).find(e => e.id === 'c-withdraw');
ok(!aIds.includes('f-refunds') && aIds.includes('f-coinbase'), 'restart: a deleted seed stays deleted');
ok(cw2 && /\(edited in QA\)$/.test(cw2.answer) && cw2.edited, 'restart: an admin edit to a seed is not overwritten by the code');
} catch (e) { ok(false, 'run', e.message); }
await cleanup();
console.log(fails ? fails + ' failure(s)' : 'all KB chat checks passed');
process.exit(fails ? 1 : 0);
+48
View File
@@ -0,0 +1,48 @@
// Knowledge-base retrieval unit test (kb.js): the right entry must rank first for each sample question,
// scored over the real seeds (chatbot.js CANNED + kb-seed.js). No server, no network.
// node qa/kb-retrieval.cjs
const path = require('path');
const kb = require(path.join(__dirname, '..', 'kb.js'));
const chatbot = require(path.join(__dirname, '..', 'chatbot.js'));
const { buildIndex, rank, relevant, validate } = kb._pure;
const entries = chatbot.seeds();
const idx = buildIndex(entries);
const CASES = [
['Can I hook up my Coinbase account to pay for a package?', 'f-coinbase'],
['can i just use coinbase', 'f-coinbase'],
['I already have an InstantAdPay account, will my upline carry over here?', 'f-team-here'],
['How many extra POL should I keep for gas fees?', 'f-how-much-pol'],
['MoonPay declined my bank card', 'f-moonpay-declined'],
['When does the daily set reset each day?', 'f-claim-streak'],
['How many videos can I watch per day?', 'f-visits-videos'],
['How do I rotate several offers behind one short link?', 'c-spin-links'],
['How do I put an ad slot on my own website?', 'c-zones'],
['Can I track conversions from PropellerAds with a postback?', 'c-sources'],
['Someone on Telegram asked for my recovery phrase', 'f-recovery-phrase'],
['Which network do I choose when withdrawing POL from Binance?', 'f-exchange-withdraw']
];
let bad = 0;
for (const [q, want] of CASES) {
const hits = rank(idx, q, 5), top = hits[0];
const ok = top && top.entry.id === want && relevant(hits).length > 0;
if (!ok) bad++;
console.log((ok ? 'ok ' : 'FAIL ') + q + ' -> ' + hits.slice(0, 3).map(h => h.entry.id + ' ' + h.score).join(', ') + (ok ? '' : ' (wanted ' + want + ')'));
}
// off-topic questions should bring nothing back, so the prompt says "I'm not sure, ask support"
for (const q of ['What is the weather in Paris tomorrow?', 'Recommend a good pizza recipe']) {
const r = relevant(rank(idx, q, 5));
if (r.length) bad++;
console.log((r.length ? 'FAIL ' : 'ok ') + 'off-topic: ' + q + ' -> ' + (r.map(h => h.entry.id + ' ' + h.score).join(', ') || 'nothing'));
}
// admin input hygiene: em dashes are turned into commas, a bad pattern is refused
const v = validate({ title: 'T', answer: 'One — two', questions: 'a\nb', tags: 'X, y' });
if (v.answer !== 'One, two' || v.questions.length !== 2 || v.tags[0] !== 'x') { bad++; console.log('FAIL validate', v); } else console.log('ok validate cleans em dashes, splits questions and tags');
if (!validate({ title: 'T', answer: 'a', pattern: '(' }).error) { bad++; console.log('FAIL validate accepted a broken pattern'); } else console.log('ok validate refuses a broken pattern');
// every CANNED regex still answers through the KB fast path in the same order
const ordered = entries.filter(e => e.pattern).sort((a, b) => a.order - b.order);
const first = msg => ordered.find(e => new RegExp(e.pattern, 'i').test(msg));
const canned = chatbot.CANNED.find(c => c.re.test('how do I withdraw'));
if (!first('how do I withdraw') || first('how do I withdraw').answer !== canned.a) { bad++; console.log('FAIL fast-path order'); } else console.log('ok fast path keeps CANNED order');
console.log(bad ? bad + ' failure(s)' : 'all retrieval checks passed');
process.exit(bad ? 1 : 0);
+4
View File
@@ -4,6 +4,7 @@
# bash qa/run.sh member # local copy: member + admin walk # bash qa/run.sh member # local copy: member + admin walk
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min) # bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
# bash qa/run.sh all # public + member + earn # bash qa/run.sh all # public + member + earn
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u set -u
@@ -29,6 +30,9 @@ if [ "$MODE" = "public" ]; then
node qa/walk.mjs public || status=1 node qa/walk.mjs public || status=1
elif [ "$MODE" = "member" ]; then elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
elif [ "$MODE" = "kb" ]; then
node qa/kb-retrieval.cjs || status=1
node qa/kb-chat.mjs || status=1
elif [ "$MODE" = "earn" ]; then elif [ "$MODE" = "earn" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
else else
+1 -1
View File
@@ -121,7 +121,7 @@ if (MODE === 'member' || MODE === 'all') {
// admin // admin
await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' }); await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' });
await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200); await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200);
for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'settings']) { for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'kb', 'releases', 'pnl', 'settings']) {
const label = L + 'admin#' + pn; const label = L + 'admin#' + pn;
await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200); await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200);
const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn); const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn);
+35 -2
View File
@@ -23,6 +23,7 @@ const drip = require('./drip');
const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set)
let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ }
const chatbot = require('./chatbot'); const chatbot = require('./chatbot');
const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20)
const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats
const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward
const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails
@@ -581,7 +582,7 @@ async function boot() {
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); 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 }); 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) // 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); 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(() => 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 setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h
@@ -1398,6 +1399,29 @@ const server = http.createServer(async (req, res) => {
const r = await chatbot.answer(b.message, b.history); const r = await chatbot.answer(b.message, b.history);
return json(res, r.error ? 400 : 200, r); return json(res, r.error ? 400 : 200, r);
} }
if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // the newest knowledge-base edit by a person (Central day) and the entry count
return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' });
}
// -- the assistant's knowledge base, admin side (2026-10-20, kb.js): list, search, add, edit, delete, try a question
if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' });
const r = await kb.create(await readBody(req));
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/kb/test' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, await kb.test(b.question));
}
const kbm = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p);
if (kbm) {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
if (req.method === 'GET') { const e = await kb.get(kbm[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); }
if (req.method === 'PUT') { const r = await kb.update(kbm[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); }
if (req.method === 'DELETE') { const r = await kb.remove(kbm[1]); return json(res, r.error ? 404 : 200, r); }
return json(res, 405, { error: 'method' });
}
// -- help desk (2026-10-16, helpdesk.js): the tickets live on InstantAdPay's one shared desk; these routes check the // -- help desk (2026-10-16, helpdesk.js): the tickets live on InstantAdPay's one shared desk; these routes check the
// person (session or the support guard) and proxy. Public side first: the /support form, the private ticket link, // person (session or the support guard) and proxy. Public side first: the /support form, the private ticket link,
@@ -2299,6 +2323,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); } 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' }); 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); m = /^\/api\/admin\/bannerspins\/(\d+)$/.exec(p);
if (m && req.method === 'POST') { if (m && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
@@ -2421,7 +2450,9 @@ const server = http.createServer(async (req, res) => {
const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30)); 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) // 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)]); 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. // -- 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' }); 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' });
@@ -2772,6 +2803,8 @@ const server = http.createServer(async (req, res) => {
let items = []; let items = [];
try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {} 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) // 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))); 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', 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.', desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.',