Files
linkspin/rotator.js
T
martbost eedc15bc13 Conversion linkage, LinkSpin side (Marty 2026-11-07, "Yes ship these"): InstantAdPay's sign-ups, wallet links and package purchases on a click count for the click's owner, in one Conversions list. Reporting only: no sponsor, payout, credit or chain path changes.
The landing tag (t.js) adds the kept click id to links to linkspin.app, instantadpay.com and the share domains, also inside a member's own redirect link (Orlando's buttons are go.opgnetwerk.com/go?u=<encoded join link>). Spin and Banner Spin links are left alone and only LinkSpin's own id shapes travel. A spin link or Banner Spin pointed straight at those sites carries lsclk with no goal set up.

netconv.js: new partner op 'events' on /api/partner/conv. Append-only ledger DATA_DIR/netconv.jsonl so two app copies cannot overwrite each other, marks.claim plus the ledger keys for once-only, join and wallet once per root click, every purchase by its own key, 30 days from click to event, the first account on a click owns it, the click owner's own account and own clicks kept as tests, each row keeps what the click was so later events survive the hit ageing out of the rotator. Spin events mirror into rotator.conv (replayed on a timer) so per-link counts, sources and placements see them; postbacks fire as for LinkSpin's own conversions.

Reports > Conversions lists goals, joins, wallets, purchases, leads and partner postbacks with values, each once; per-link Conv. counts include goals. /join keeps lsclk as well as lsid. Guide, /conversions, privacy and chatbot (CANNED + FACTS) updated; reports.js and join.js tags bumped.

The false Pages webhook claim is gone from chatbot.js, join.js and the home page: leads go to the member's list and CSV, or into a pasted autoresponder form.

QA: bash qa/run.sh netconv (57 checks, also runs in member).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:46:43 -06:00

337 lines
32 KiB
JavaScript

// The rotator (LinkSpin's core tool, 2026-09-15): a member owns rotations; each rotation has a short
// code and a list of destinations with weights. /r/<code> picks one by weight, records the hit
// (day, country, source, device, a daily-salted visitor hash so uniques are honest, bot filter)
// and redirects in one hop. Destinations can be paused; a fallback catches the empty case.
// Health checks (a dead or parked destination is paused automatically) live in health.js (2026-10-10).
// Dayparting (2026-10-10): rotation.hours / destination.hours = null (always on) or 7 strings of 24 chars
// '1'/'0', index 0 = Sunday like JS getDay(); rotation.tz = IANA zone name or 'visitor' (the visitor's
// country picks a representative zone). Zones are stored by NAME, never as an offset.
// JSON store on the volume for the test area; the MySQL twin follows the engine's dual-mode pattern.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12)
let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk=
let IS_NETWORK = () => false, GOAL_ROWS = () => []; // 2026-11-07: a page on a network host always gets the click id (InstantAdPay reports joins, wallets, purchases against it); goal conversions as rotator-shaped rows for per-link counts
const DAY = 86400000;
const J = {
db: null,
FILE: () => path.join(DATA_DIR, 'rotator.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; },
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
};
function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; if (opts.isNetworkHost) IS_NETWORK = opts.isNetworkHost; if (opts.goalRows) GOAL_ROWS = opts.goalRows; J.load(); }
const convOf = (rid) => J.db.conv.filter(c => c.r === rid).concat(GOAL_ROWS().filter(c => c.r === rid)); // a link's conversions: site and network events, and goals
const norm = e => String(e || '').trim().toLowerCase();
const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; };
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
const cleanUrl = u => { let s = String(u || '').trim(); if (s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && /^[^\s\/]+\.[^\s]+/.test(s)) s = 'https://' + s; return /^https?:\/\/[^\s]+$/i.test(s) && s.length <= 500 ? s : null; };
// ── dayparting ──────────────────────────────────────────────────────────────────────────────────────────────
// representative zone per country for tz = 'visitor' (top ~60 by traffic); unknown or no country -> Central
const COUNTRY_TZ = { US: 'America/Chicago', CA: 'America/Toronto', MX: 'America/Mexico_City', BR: 'America/Sao_Paulo', AR: 'America/Argentina/Buenos_Aires', CL: 'America/Santiago', CO: 'America/Bogota', PE: 'America/Lima', VE: 'America/Caracas',
GB: 'Europe/London', IE: 'Europe/Dublin', PT: 'Europe/Lisbon', ES: 'Europe/Madrid', FR: 'Europe/Paris', DE: 'Europe/Berlin', NL: 'Europe/Amsterdam', BE: 'Europe/Brussels', CH: 'Europe/Zurich', AT: 'Europe/Vienna', IT: 'Europe/Rome', PL: 'Europe/Warsaw', CZ: 'Europe/Prague', HU: 'Europe/Budapest', SE: 'Europe/Stockholm', NO: 'Europe/Oslo', DK: 'Europe/Copenhagen', FI: 'Europe/Helsinki', GR: 'Europe/Athens', RO: 'Europe/Bucharest', BG: 'Europe/Sofia', UA: 'Europe/Kyiv', RU: 'Europe/Moscow', TR: 'Europe/Istanbul', RS: 'Europe/Belgrade', HR: 'Europe/Zagreb', SK: 'Europe/Bratislava', LT: 'Europe/Vilnius', LV: 'Europe/Riga', EE: 'Europe/Tallinn',
ZA: 'Africa/Johannesburg', NG: 'Africa/Lagos', KE: 'Africa/Nairobi', EG: 'Africa/Cairo', MA: 'Africa/Casablanca', GH: 'Africa/Accra',
IN: 'Asia/Kolkata', PK: 'Asia/Karachi', BD: 'Asia/Dhaka', LK: 'Asia/Colombo', NP: 'Asia/Kathmandu', PH: 'Asia/Manila', ID: 'Asia/Jakarta', MY: 'Asia/Kuala_Lumpur', SG: 'Asia/Singapore', TH: 'Asia/Bangkok', VN: 'Asia/Ho_Chi_Minh', HK: 'Asia/Hong_Kong', TW: 'Asia/Taipei', CN: 'Asia/Shanghai', JP: 'Asia/Tokyo', KR: 'Asia/Seoul', AE: 'Asia/Dubai', SA: 'Asia/Riyadh', IL: 'Asia/Jerusalem', IR: 'Asia/Tehran', KZ: 'Asia/Almaty',
AU: 'Australia/Sydney', NZ: 'Pacific/Auckland' };
const DEFAULT_TZ = 'America/Chicago';
const WD = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
const row = (from, to) => { let s = ''; for (let h = 0; h < 24; h++) s += h >= from && h < to ? '1' : '0'; return s; };
const ALL = row(0, 24), NONE = row(0, 0);
const PRESETS = { always: null, business: [NONE, row(8, 18), row(8, 18), row(8, 18), row(8, 18), row(8, 18), NONE], evenings: new Array(7).fill(row(17, 23)), weekends: [ALL, NONE, NONE, NONE, NONE, NONE, ALL] };
// validate a grid from the API: null/'' = always; a preset name; 7 strings of 24 x '1'/'0'; or 7 arrays of 24 booleans
function cleanHours(h) {
if (h == null || h === '' || h === 'always') return { hours: null };
if (typeof h === 'string' && PRESETS[h] !== undefined) return { hours: PRESETS[h] ? PRESETS[h].slice() : null };
if (!Array.isArray(h) || h.length !== 7) return { error: 'Hours must be a 7 by 24 grid.' };
const out = [];
for (const d of h) {
let s = Array.isArray(d) ? d.map(x => x && x !== '0' ? '1' : '0').join('') : String(d || '');
if (!/^[01]{24}$/.test(s)) return { error: 'Hours must be a 7 by 24 grid.' };
out.push(s);
}
if (out.every(s => s === ALL)) return { hours: null };
if (out.every(s => s === NONE)) return { error: 'Pick at least one hour, or choose Always on.' };
return { hours: out };
}
// validate a zone name: 'visitor' or anything Intl knows; stored canonical, never an offset
function cleanTz(tz) {
const s = String(tz || '').trim(); if (!s || s === 'visitor') return { tz: 'visitor' };
if (s.length > 64 || !/^[A-Za-z0-9_+\-\/]+$/.test(s)) return { error: 'That time zone name is not one we know.' };
try { return { tz: new Intl.DateTimeFormat('en', { timeZone: s }).resolvedOptions().timeZone }; } catch (e) { return { error: 'That time zone name is not one we know. Use a name like America/New_York.' }; }
}
const zoneFor = (r, country) => (r.tz && r.tz !== 'visitor') ? r.tz : (COUNTRY_TZ[String(country || '').toUpperCase()] || DEFAULT_TZ);
// the weekday + hour right now (or at ts) in a zone -> { wd, h }
// one formatter per time zone: building an Intl.DateTimeFormat is expensive, and bestHours calls cellAt once per hit
// (2026-10-14: a 10k-hit link took ~4 s to open its stats and blocked every other request meanwhile)
const TZ_FMT = new Map();
function tzFormatter(tz) {
let f = TZ_FMT.get(tz);
if (!f) { f = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', hour12: false, hourCycle: 'h23', weekday: 'short' }); TZ_FMT.set(tz, f); }
return f;
}
function cellAt(tz, ts) {
try {
const parts = tzFormatter(tz).formatToParts(new Date(ts || Date.now()));
let wd = 1, h = 0; for (const p of parts) { if (p.type === 'weekday') wd = WD[p.value] ?? 1; if (p.type === 'hour') h = Number(p.value) % 24; }
return { wd, h };
} catch (e) { return cellAt(DEFAULT_TZ, ts); }
}
const isOn = (hours, cell) => !hours || hours[cell.wd][cell.h] === '1';
function pub(r) {
const hits = J.db.hits.filter(h => h.r === r.id);
const since7 = Date.now() - 7 * DAY;
const perDest = {};
for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); }
const conv = convOf(r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const since30 = Date.now() - 30 * DAY;
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy,
hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '',
destinations: r.destinations.map(d => Object.assign({ hours: null, health: null, autoPaused: 0 }, d, { hits: (perDest[d.id] || { hits: 0 }).hits, hits7: (perDest[d.id] || { hits7: 0 }).hits7, uniques: (perDest[d.id] || { uniques: new Set() }).uniques.size })),
hits: hits.length, hits7: hits.filter(h => h.ts >= since7).length, uniques: new Set(hits.map(h => h.v)).size, bots: hits.filter(h => h.bot).length };
}
// "my best hours": the rotation's own non-bot hits over 30 days, bucketed by weekday + hour in the rotation's zone
// (per visitor country when tz = visitor). Top 25% of cells by uniques. Unlocks at 200 hits.
const BEST_MIN = 200;
function bestHours(r) {
const since = Date.now() - 30 * DAY;
const hits = J.db.hits.filter(h => h.r === r.id && !h.bot && h.ts >= since);
const cells = []; for (let i = 0; i < 7; i++) cells.push(new Array(24).fill(0).map(() => new Set()));
for (const h of hits) { const c = cellAt(zoneFor(r, h.c), h.ts); cells[c.wd][c.h].add(h.v); }
const counts = cells.map(d => d.map(s => s.size));
const flat = []; counts.forEach((d, wd) => d.forEach((n, h) => { if (n > 0) flat.push({ wd, h, n }); }));
flat.sort((a, b) => b.n - a.n);
const keep = flat.slice(0, Math.max(1, Math.ceil(flat.length * 0.25)));
const grid = new Array(7).fill(NONE).map(s => s.split(''));
for (const c of keep) grid[c.wd][c.h] = '1';
const ready = hits.length >= BEST_MIN && keep.length > 0;
return { hits: hits.length, need: BEST_MIN, ready, hours: ready ? grid.map(d => d.join('')) : null, cells: counts };
}
async function list(owner) { return J.db.rotations.filter(r => r.owner === norm(owner)).map(pub); }
async function get(owner, id) { const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); return r ? pub(r) : null; }
async function create(owner, body) {
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the rotation a name.' };
if (J.db.rotations.filter(r => r.owner === norm(owner)).length >= 100) return { error: 'That is a lot of rotations. Archive some first.' };
let code = newCode(); while (J.db.rotations.some(r => r.code === code)) code = newCode();
const r = { id: (J.db.rotations.reduce((m, x) => Math.max(m, x.id), 0) + 1), owner: norm(owner), name, code, fallback: cleanUrl(body.fallback) || '', destinations: [], created: Date.now(), paused: false, nextDest: 1 };
J.db.rotations.push(r); J.save(); return { ok: true, rotation: pub(r) };
}
async function update(owner, id, body) {
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
if (body.name != null) { const n = String(body.name).trim().slice(0, 80); if (n) r.name = n; }
if (body.fallback != null) r.fallback = cleanUrl(body.fallback) || '';
if (body.paused != null) r.paused = !!body.paused;
if (body.hours !== undefined) { const h = cleanHours(body.hours); if (h.error) return h; if (h.hours) r.hours = h.hours; else delete r.hours; }
if (body.tz !== undefined) { const t = cleanTz(body.tz); if (t.error) return t; if (t.tz === 'visitor') delete r.tz; else r.tz = t.tz; }
// traffic source attachment: '' detaches; otherwise it must be one of the owner's own sources
if (body.sourceId !== undefined) { const sid = String(body.sourceId || '').trim(); if (!sid) delete r.sourceId; else { if (!/^[a-f0-9]{10}$/.test(sid) || !SOURCES || !SOURCES.find(owner, sid)) return { error: 'No such source.' }; r.sourceId = sid; } }
J.save(); return { ok: true, rotation: pub(r) };
}
async function remove(owner, id) { const n = J.db.rotations.length; J.db.rotations = J.db.rotations.filter(r => !(r.id === Number(id) && r.owner === norm(owner))); J.save(); return n !== J.db.rotations.length ? { ok: true } : { error: 'No such rotation.' }; }
async function addDest(owner, id, body) {
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
const url = cleanUrl(body.url); if (!url) return { error: 'Destination must be a full https:// address.' };
if (r.destinations.length >= 25) return { error: 'Up to 25 destinations per rotation.' };
const w = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
const d = { id: r.nextDest++, url, label: String(body.label || '').trim().slice(0, 60), weight: w, active: true, added: Date.now() };
r.destinations.push(d); J.save(); return { ok: true, rotation: pub(r) };
}
async function updateDest(owner, id, did, body) {
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return { error: 'No such rotation.' };
const d = r.destinations.find(d => d.id === Number(did)); if (!d) return { error: 'No such destination.' };
if (body.url != null) { const u = cleanUrl(body.url); if (!u) return { error: 'Destination must be a full https:// address.' }; d.url = u; }
if (body.label != null) d.label = String(body.label).trim().slice(0, 60);
if (body.weight != null) d.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
if (body.active != null) { d.active = !!body.active; delete d.autoPaused; if (d.health) { d.health.fails = 0; d.health.passes = 0; } } // the owner's own choice: never auto-resumed, counters start over
if (body.hours !== undefined) { const h = cleanHours(body.hours); if (h.error) return h; if (h.hours) d.hours = h.hours; else delete d.hours; }
if (body.remove) r.destinations = r.destinations.filter(x => x.id !== d.id);
J.save(); return { ok: true, rotation: pub(r) };
}
// pick by weight among active destinations that are inside their own hours right now
function pick(r, cell) {
const live = r.destinations.filter(d => d.active && (!cell || isOn(d.hours, cell)));
if (!live.length) return null;
const total = live.reduce((n, d) => n + d.weight, 0); let x = crypto.randomInt(total);
for (const d of live) { x -= d.weight; if (x < 0) return d; }
return live[live.length - 1];
}
// the redirect: returns { url, dest } or null (unknown code). Records the hit.
async function resolve(code, req) {
const r = J.db.rotations.find(r => r.code === norm(code)); if (!r) return null;
const ua = String(req.headers['user-agent'] || ''); const bot = BOT.test(ua) || !ua;
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const day = new Date().toISOString().slice(0, 10);
const v = crypto.createHash('sha256').update(day + '|' + ip + '|' + ua).digest('hex').slice(0, 16); // daily-salted visitor hash, no IP stored
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ip) || '') : ''; } catch (e) {}
// dayparting: the rotation's own hours gate everything (off hours -> fallback); each destination's hours gate the pick
const cell = cellAt(zoneFor(r, country));
const off = !r.paused && !isOn(r.hours, cell);
const d = (r.paused || off) ? null : pick(r, cell);
const url = d ? d.url : (r.fallback || null);
const ref = String(req.headers.referer || ''); let src = 'direct'; try { if (ref) src = new URL(ref).hostname.replace(/^www\./, ''); } catch (e) {}
// an ad click that led here (conversion pixel, 2026-10-23): InstantAdPay and LinkSpin ad clicks append ?lsclk=<i|a + 11 hex>.
// The spin-link click inherits the ad as its source; the goal pixel credits the ad campaign AND this link.
let ac = ''; try { const v = String(new URL(req.url, 'http://x').searchParams.get('lsclk') || ''); if (/^[ai][a-f0-9]{11}$/.test(v)) ac = v; } catch (e) {}
if (ac) src = ac[0] === 'i' ? 'InstantAdPay ad' : 'LinkSpin ad';
const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
// click ids and sub ids that rode in on the link (tracker / traffic-network params), kept per click
const q = {}; try { const sp = new URL(req.url, 'http://x').searchParams; let n = 0; for (const [k, val] of sp) { 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++; } } } catch (e) {}
const id = crypto.randomBytes(6).toString('hex').slice(0, 10);
// sr = the traffic source attached to the link at click time, so the network that sent this click is the one told about its conversion
J.db.hits.push({ id, r: r.id, d: d ? d.id : 0, ts: Date.now(), v, c: country, s: src, dv: device, bot: bot ? 1 : 0, oh: off ? 1 : undefined, q: Object.keys(q).length ? q : undefined, sr: r.sourceId || undefined, ac: ac || undefined });
if (HIT_IX) HIT_IX.set(id, J.db.hits.length - 1);
if (J.db.hits.length > 200000) { J.db.hits = J.db.hits.slice(-150000); HIT_IX = null; }
J.save();
let out = url;
if (out) {
const vals = { clickid: q.clickid || q.cid || q.click_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: src, country, device, lsid: id, code: r.code };
for (const [k, val] of Object.entries(q)) if (vals[k] == null) vals[k] = val;
out = out.replace(/\{([a-z0-9_]{1,24})\}/gi, (m, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
// our own pages get the click id automatically, so a join can be matched back to this click without any macro
try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {}
// conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets
// ?lsclk=<this click id> for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone.
if (!bot) { try { const t = new URL(out); if ((ac || WANTS_CLICK_ID(r.owner) || IS_NETWORK(t.hostname)) && !t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} }
}
return { url: out, dest: d, rotation: r, lsid: id };
}
// conversions: record an event against the click that brought the person (dedupe per click + event)
// Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it
let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; }
// facts.key (netconv.js, 2026-11-07): every purchase InstantAdPay reports counts by its own key, not once per click; facts.bound =
// the click as first recorded, so an event still lands on its link after the hit aged out of the array
async function convert(lsid, ev, facts) {
const f = facts || {}; const key = f.key ? String(f.key) : ''; const id = String(lsid);
let h = J.db.hits.find(x => x.id === id);
if (!h && f.bound && f.bound.r) h = { id, r: f.bound.r, d: f.bound.d, sr: f.bound.sr };
if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
const dup = J.db.conv.some(c => key && ev === 'purchase' ? c.key === key : (c.lsid === h.id && c.ev === ev && (ev !== 'purchase' || !c.key)));
if (!dup) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Number(f.ts) || Date.now(), value: Number(f.payout || 0) || 0, label: f.label ? String(f.label).slice(0, 40) : undefined, sr: h.sr || undefined, key: key || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' };
}
// a member's conversions as rows (Reports' one Conversions panel, netconv.unified): goals are added there, never here
function convRows(owner, since) { const ids = new Set(J.db.rotations.filter(r => r.owner === norm(owner)).map(r => r.id)); return J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); }
// clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports
async function sourceCounts(owner, days) {
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
const since = Date.now() - (Number(days) || 30) * DAY; const out = {};
const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 });
for (const r of mine) if (r.sourceId) at(r.sourceId).links++;
for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); }
for (const c of J.db.conv.concat(GOAL_ROWS())) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++;
for (const k in out) out[k].unique = out[k].unique.size;
return out;
}
// a source was deleted: its links go back to having none
async function detachSource(owner, sid) { let n = 0; for (const r of J.db.rotations) if (r.owner === norm(owner) && r.sourceId === String(sid)) { delete r.sourceId; n++; } if (n) J.save(); return n; }
// shared formatter: toLocaleDateString(..., {timeZone}) builds a new Intl formatter per call (slow per hit; 2026-10-14)
const CT_DAY_FMT = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' });
const ctDay = ts => CT_DAY_FMT.format(new Date(ts));
// one view across everything a member owns, for Reports
async function summary(owner, days) {
const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id));
const since = Date.now() - (Number(days) || 30) * DAY;
const all = J.db.hits.filter(h => ids.has(h.r) && h.ts >= since); const hits = all.filter(h => !h.bot);
const by = key => { const m = {}; for (const h of hits) { const k = h[key] || '(none)'; m[k] = (m[k] || 0) + 1; } return Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })); };
const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); }
const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b }));
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const conv = J.db.conv.concat(GOAL_ROWS()).filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1;
const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10);
// traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried
const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {};
const srcMap = {}; for (const h of hits) if (h.sr) { const o = srcMap[h.sr] = srcMap[h.sr] || { hits: 0, u: new Set(), conv: 0 }; o.hits++; o.u.add(h.v); }
for (const c of conv) if (c.sr) { const o = srcMap[c.sr] = srcMap[c.sr] || { hits: 0, u: new Set(), conv: 0 }; o.conv++; }
const sources = Object.entries(srcMap).map(([id, o]) => ({ id, name: (meta[id] || {}).name || 'Deleted source', site: (meta[id] || {}).site || '', hits: o.hits, unique: o.u.size, conv: o.conv })).sort((a, b) => b.hits - a.hits);
const convByHit = {}; for (const c of conv) convByHit[c.lsid] = (convByHit[c.lsid] || 0) + 1;
const plMap = {}; for (const h of hits) { if (!h.sr || !h.q) continue; const pk = (meta[h.sr] || {}).placementKey; if (!pk || h.q[pk] == null || h.q[pk] === '') continue; const key = h.sr + '\u0000' + h.q[pk]; const o = plMap[key] = plMap[key] || { source: (meta[h.sr] || {}).name || 'Deleted source', sourceId: h.sr, key: pk, k: h.q[pk], n: 0, conv: 0 }; o.n++; o.conv += convByHit[h.id] || 0; }
const placements = Object.values(plMap).sort((a, b) => b.n - a.n).slice(0, 12);
return { links: mine.length, totals: { served: hits.length, unique: new Set(hits.map(h => h.v)).size, bots: all.length - hits.length, joins: convBy.join || 0, wallets: convBy.wallet || 0, purchases: convBy.purchase || 0, external: convBy.external || 0 },
days: dlist, source: by('s'), country: by('c'), device: by('dv'), hours, top, conversions: Object.entries(convBy).map(([k, n]) => ({ k, n })).sort((a, b) => b.n - a.n), sources, placements };
}
async function stats(owner, id) {
const r = J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)); if (!r) return null;
const hits = J.db.hits.filter(h => h.r === r.id && !h.bot);
const by = key => { const m = {}; for (const h of hits) { const k = h[key] || '(none)'; m[k] = (m[k] || 0) + 1; } return Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })); };
const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; }
const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++;
const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; }
const conv = convOf(r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length,
subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
// conversion pixel (2026-10-23): a click by id, with its link and destination. An index over the hits array, rebuilt lazily
// after new hits (the pixel asks rarely; a rebuild over 200k hits is a few ms).
let HIT_IX = null;
function hitById(id, again) {
if (!HIT_IX) { HIT_IX = new Map(); for (let i = 0; i < J.db.hits.length; i++) HIT_IX.set(J.db.hits[i].id, i); }
let i = HIT_IX.get(String(id)); let h = i == null ? null : J.db.hits[i];
if (i != null && (!h || h.id !== String(id))) { HIT_IX = null; return again ? null : hitById(id, true); } // the array moved under the index (trim, demo sweep): rebuild once
if (!h) return null;
const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null;
const d = (r.destinations || []).find(x => x.id === h.d);
return { hit: h, owner: r.owner, rotation: { id: r.id, code: r.code, name: r.name }, destUrl: d ? d.url : (r.fallback || '') };
}
function totals() { return { rotations: J.db.rotations.length, hits: J.db.hits.length }; }
// ── demo spins (home page, 2026-10-07) ─────────────────────────────────────────────────────────────────────
// A visitor with no account pastes up to three pages and gets a working link at once. The rotation is owned by
// 'demo:<token>' (token in the ls.demo cookie) and expires after 24 h unless the visitor signs in, at which point
// claim() hands it to their email and the expiry is lifted. Demo owners never count against a member's quota.
const DEMO_TTL = 24 * DAY;
async function createDemo(token, urls) {
const t = String(token || '').replace(/[^a-f0-9]/g, '').slice(0, 32); if (t.length < 16) return { error: 'Bad demo token.' };
const owner = 'demo:' + t;
if (J.db.rotations.some(r => r.owner === owner)) return { error: 'This browser already made a demo spin. Sign in to make more.' };
const clean = (urls || []).map(cleanUrl).filter(Boolean).slice(0, 3);
if (clean.length < 1) return { error: 'Paste at least one page address that starts with https://' };
const r = await create(owner, { name: 'My first spin' }); if (r.error) return r;
const rec = J.db.rotations.find(x => x.id === r.rotation.id); rec.demo = true; rec.expires = Date.now() + DEMO_TTL;
for (const u of clean) await addDest(owner, rec.id, { url: u, weight: 1, label: '' });
J.save(); return { ok: true, rotation: pub(rec) };
}
async function claim(demoOwner, newOwner) {
const o = norm(newOwner); if (!o || !demoOwner) return { ok: false };
const mine = J.db.rotations.filter(r => r.owner === demoOwner);
for (const r of mine) { r.owner = o; delete r.demo; delete r.expires; r.name = r.name === 'My first spin' ? 'My first spin' : r.name; }
if (mine.length) J.save(); return { ok: true, claimed: mine.length };
}
function sweepDemos() {
const now = Date.now(); const gone = new Set();
J.db.rotations = J.db.rotations.filter(r => { if (r.demo && r.expires && r.expires < now) { gone.add(r.id); return false; } return true; });
if (gone.size) { J.db.hits = J.db.hits.filter(h => !gone.has(h.r)); J.db.conv = J.db.conv.filter(c => !gone.has(c.r)); J.save(); }
return gone.size;
}
// site-wide figures for the daily snapshot (snapshot.js): the last `since` window, every owner, bots left out
function window24(since) {
const hits = J.db.hits.filter(h => h.ts >= since); const real = hits.filter(h => !h.bot);
return { links: J.db.rotations.length, created: J.db.rotations.filter(r => (r.created || 0) >= since).length,
served: real.length, unique: new Set(real.map(h => h.v)).size, bots: hits.length - real.length,
countries: new Set(real.map(h => h.c).filter(Boolean)).size };
}
function servedToday() {
// Central-time day, like Reports
const now = new Date(); const ct = new Date(now.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
const startCt = new Date(ct.getFullYear(), ct.getMonth(), ct.getDate()).getTime(); const start = now.getTime() - (ct.getTime() - startCt);
return J.db.hits.filter(h => h.ts >= start && !h.bot).length;
}
// raw access for health.js (same store, same save)
const rawRotations = () => J.db.rotations;
const save = () => J.save();
const findMine = (owner, id) => J.db.rotations.find(r => r.id === Number(id) && r.owner === norm(owner)) || null;
// admin Member content (2026-10-18): every rotation of every owner, click counts in ONE pass over the hits (pub() per rotation is O(rotations x hits))
function adminAll() {
const since7 = Date.now() - 7 * DAY; const by = {}, cv = {};
for (const h of J.db.hits) { const o = by[h.r] = by[h.r] || { hits: 0, hits7: 0, bots: 0 }; if (h.bot) { o.bots++; continue; } o.hits++; if (h.ts >= since7) o.hits7++; }
for (const c of J.db.conv) cv[c.r] = (cv[c.r] || 0) + 1;
return J.db.rotations.map(r => { const o = by[r.id] || { hits: 0, hits7: 0, bots: 0 };
return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, paused: !!r.paused, demo: !!r.demo, expires: r.expires || 0, fallback: r.fallback || '', sourceId: r.sourceId || '', dayparted: !!r.hours,
destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })),
hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; });
}
module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24,
pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource };