eedc15bc13
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>
319 lines
29 KiB
JavaScript
319 lines
29 KiB
JavaScript
// Conversion pixel (Marty approved 2026-10-23, "Go with the conversion pixel"). LinkSpin is the single source of truth
|
|
// for goals and goal conversions, for its own members AND for InstantAdPay members (their LinkSpin shell account, same
|
|
// email, holds the goals; InstantAdPay reads and edits them over the signed partner call).
|
|
//
|
|
// - Goals: a member names a goal ("subscriber", "sale", optional default value). Each goal has a PUBLIC pixel id
|
|
// (px + 10 hex). It is not a secret: it can only ever count conversions for clicks its owner owns.
|
|
// - Ad clicks: every LinkSpin ad click (/api/ads/click, zone clicks) gets a click id 'a' + 11 hex; every InstantAdPay
|
|
// ad click is pushed here with its own id 'i' + 11 hex (/api/partner/clicks). Spin-link clicks keep the rotator's
|
|
// 10-hex lsid; a spin-link click that arrived through an ad carries that ad click as `ac` (rotator.js).
|
|
// - Landing tag (/t.js) stores the click id on the member's own site; the goal pixel (/cv.gif, /cv.js) reports it.
|
|
// Matching order: the click id in the URL > the landing tag's stored id > LinkSpin's cookie > the 24 h IP+UA soft key.
|
|
// The method that matched is kept on the conversion so Reports can say how solid each count is.
|
|
// - Rules: each goal counts once per click (per ROOT click: an ad click and the spin-link click it led to are one
|
|
// click), only within 30 days of a real click, only for clicks the pixel's owner owns (the ad's owner or the spin
|
|
// link's owner), per-pixel and per-IP rate limits. A test conversion is recorded apart and never counted. The goal
|
|
// owner's own click (any type: ad, spin link, Banner Spin) is kept as a test, never counted (2026-10-26).
|
|
// - Banner Spin clicks ('k' + 11 hex) that go straight to a page carry lsclk too since 2026-10-26 (bannerspin.js).
|
|
// Storage: DATA_DIR/convtrack.json (JSON in both modes, like rotator.json / postbacks.json), debounced writes.
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
|
|
const DAY = 86400000, WINDOW_MS = 30 * DAY, SOFT_MS = 24 * 3600000, MAX_GOALS = 20;
|
|
const MAX_CLICKS = 300000, MAX_CONV = 100000;
|
|
let FILE = null, S = null, dirty = false, rotator = null, bannerspin = null, campaignOf = async () => null;
|
|
|
|
function load() {
|
|
if (S) return S;
|
|
try { S = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { S = null; }
|
|
if (!S || typeof S !== 'object') S = {};
|
|
S.v = 1; S.goals = S.goals || {}; S.clicks = S.clicks || {}; S.soft = S.soft || {}; S.conv = Array.isArray(S.conv) ? S.conv : []; S.camps = S.camps || {}; S.tests = S.tests || {};
|
|
S.own = S.own || {}; S.selfIds = S.selfIds || {}; // own-click tests (2026-10-26): soft key -> { owner email: last seen }, click id -> marked at
|
|
return S;
|
|
}
|
|
function save() { dirty = true; }
|
|
function flush() { if (!dirty || !S || !FILE) return; dirty = false; try { fs.writeFileSync(FILE + '.tmp', JSON.stringify(S)); fs.renameSync(FILE + '.tmp', FILE); } catch (e) { console.error('convtrack save', e.message); } }
|
|
function init(opts) {
|
|
FILE = path.join(opts.dataDir, 'convtrack.json'); rotator = opts.rotator || null; bannerspin = opts.bannerspin || null; if (opts.campaignOf) campaignOf = opts.campaignOf;
|
|
S = null; load();
|
|
if (!opts.noTimers) { setInterval(flush, 3000).unref(); setInterval(prune, 3600000).unref(); }
|
|
}
|
|
|
|
const norm = e => String(e || '').trim().toLowerCase();
|
|
const isPx = v => /^px[a-f0-9]{10}$/.test(String(v || ''));
|
|
const isClickId = v => /^[a-z0-9]{6,24}$/i.test(String(v || ''));
|
|
const isAdId = v => /^[ai][a-f0-9]{11}$/.test(String(v || ''));
|
|
const cleanName = v => { const s = String(v == null ? '' : v).trim().toLowerCase().replace(/\s+/g, '_'); return /^[a-z0-9_-]{1,32}$/.test(s) ? s : ''; };
|
|
const cleanValue = v => { if (v === '' || v == null) return 0; const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n * 100) / 100, 100000) : 0; };
|
|
const newPx = () => { for (;;) { const id = 'px' + crypto.randomBytes(5).toString('hex'); if (!load().goals[id]) return id; } };
|
|
const newAdClickId = () => 'a' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
|
function ipOf(req) { return String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim(); }
|
|
// the soft key: InstantAdPay computes exactly the same thing for its ad clicks (contract 2026-10-23)
|
|
function softKey(req) { return 's:' + crypto.createHash('sha256').update(ipOf(req) + '|' + String(req.headers['user-agent'] || '')).digest('hex').slice(0, 20); }
|
|
|
|
// ── own clicks are tests, on every click type (Marty approved 2026-10-26) ───────────────────────────────────────
|
|
// A member clicking their OWN ad, spin link or Banner Spin and converting is a test, never a count. Known by: the click
|
|
// was made while signed in as the owner (ads), or the clicking / converting browser's soft key is one the owner has been
|
|
// seen signed in from (LinkSpin sessions, noted by auth.js; InstantAdPay sessions, pushed with its clicks). Linked
|
|
// positions sit on the owner's own email, so they are the owner here too. Soft keys kept 31 days (the click window).
|
|
const OWN_MS = WINDOW_MS + DAY, ownNoted = new Map();
|
|
const isSk = sk => /^s:[a-f0-9]{20}$/.test(String(sk || ''));
|
|
function noteOwner(email, sk, ts) {
|
|
const e = norm(email); if (!e || e.length > 190 || !isSk(sk)) return false;
|
|
const at = Math.min(Number(ts) || Date.now(), Date.now()); const k = e + '|' + sk;
|
|
if ((ownNoted.get(k) || 0) > at - 600000) return false; ownNoted.set(k, at); if (ownNoted.size > 20000) ownNoted.clear();
|
|
const st = load(); const m = st.own[sk] = st.own[sk] || {};
|
|
if (!(m[e] >= at)) m[e] = at;
|
|
const keys = Object.keys(m); if (keys.length > 8) { keys.sort((a, b) => m[a] - m[b]); for (const x of keys.slice(0, keys.length - 8)) delete m[x]; }
|
|
save(); return true;
|
|
}
|
|
function noteSession(email, req) { try { return noteOwner(email, softKey(req)); } catch (e) { return false; } }
|
|
// InstantAdPay's pushed rows: [{ owner, sk, ts }] (its members' own sessions)
|
|
function importOwners(rows) { let n = 0; for (const r of (Array.isArray(rows) ? rows.slice(0, 2000) : [])) if (r && noteOwner(r.owner, r.sk, r.ts)) n++; return n; }
|
|
function isOwnerSk(owner, sk) { const m = isSk(sk) && load().own[sk]; const t = m && m[norm(owner)]; return !!(t && Date.now() - t <= OWN_MS); }
|
|
// spin-link and Banner Spin clicks: marked when the owner made them (signed in on this host, or from an owner soft key)
|
|
function markSelfClick(id, owner, req, sessionEmail) {
|
|
if (!isClickId(id) || !owner) return false;
|
|
const mine = (sessionEmail && norm(sessionEmail) === norm(owner)) || isOwnerSk(owner, softKey(req));
|
|
if (mine) { load().selfIds[id] = Date.now(); save(); }
|
|
return !!mine;
|
|
}
|
|
|
|
// ── goals ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
function pubGoal(g) { return { px: g.px, name: g.name, value: g.value || 0, created: g.created, lastTest: (load().tests[g.px] || 0) || null }; }
|
|
function goalsOf(owner) { const o = norm(owner); return Object.values(load().goals).filter(g => g.owner === o).sort((a, b) => a.created - b.created); }
|
|
function goal(px) { return load().goals[String(px || '')] || null; }
|
|
function createGoal(owner, body) {
|
|
const o = norm(owner); if (!o) return { error: 'Sign in first.' };
|
|
const name = cleanName(body && body.name); if (!name) return { error: 'Name the goal with letters, numbers, - or _ (for example subscriber or sale), up to 32.' };
|
|
const mine = goalsOf(o);
|
|
if (mine.length >= MAX_GOALS) return { error: 'Up to ' + MAX_GOALS + ' goals per account. Remove one first.' };
|
|
if (mine.some(g => g.name === name)) return { error: 'You already have a goal called ' + name + '.' };
|
|
const g = { px: newPx(), owner: o, name, value: cleanValue(body && body.value), created: Date.now() };
|
|
load().goals[g.px] = g; save(); flush(); return { ok: true, goal: pubGoal(g) };
|
|
}
|
|
function updateGoal(owner, px, body) {
|
|
const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' };
|
|
if (body.remove) { delete load().goals[g.px]; delete load().tests[g.px]; save(); flush(); return { ok: true, removed: true }; } // its past conversions stay in the log (the reports show them under the name)
|
|
if (body.name != null) { const n = cleanName(body.name); if (!n) return { error: 'Name the goal with letters, numbers, - or _ , up to 32.' }; if (goalsOf(g.owner).some(x => x.px !== g.px && x.name === n)) return { error: 'You already have a goal called ' + n + '.' }; g.name = n; }
|
|
if (body.value != null) g.value = cleanValue(body.value);
|
|
save(); flush(); return { ok: true, goal: pubGoal(g) };
|
|
}
|
|
|
|
// ── clicks ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
function noteSoft(sk, id, owner, ts) {
|
|
if (!sk || !/^s:[a-f0-9]{20}$/.test(sk) || !id) return;
|
|
const st = load(); const now = ts || Date.now();
|
|
const list = (st.soft[sk] || []).filter(x => now - x[1] <= SOFT_MS && x[0] !== id);
|
|
list.push([id, now, norm(owner)]); st.soft[sk] = list.slice(-6); save();
|
|
}
|
|
// a LinkSpin ad click (banner, text, zone). Returns the click id to append to the target.
|
|
function recordAdClick(camp, req, extra) {
|
|
if (!camp || !camp.id) return null;
|
|
const st = load(); const id = newAdClickId(); const ua = String(req.headers['user-agent'] || '');
|
|
const sk = softKey(req);
|
|
let pl = String((extra && extra.placement) || ''); if (!pl) { try { const r = new URL(String(req.headers.referer || '')); pl = (r.hostname.replace(/^www\./, '') + r.pathname).slice(0, 80); } catch (e) {} }
|
|
st.clicks[id] = { id, k: 'ad', camp: Number(camp.id), cname: String(camp.name || camp.title || '').slice(0, 80), type: camp.type || '', owner: norm(camp.owner), ts: Date.now(), sk,
|
|
c: (extra && extra.country) || '', dv: /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop', pl, self: (extra && extra.self) || isOwnerSk(camp.owner, sk) ? 1 : undefined, target: String(camp.targetUrl || '').slice(0, 300) };
|
|
noteSoft(sk, id, camp.owner); trimClicks(); save();
|
|
return id;
|
|
}
|
|
// InstantAdPay pushes its ad clicks (signed partner call); an upsert by id, so a row sent twice is harmless
|
|
function importClicks(rows) {
|
|
const st = load(); let n = 0;
|
|
for (const r of (Array.isArray(rows) ? rows.slice(0, 500) : [])) {
|
|
const id = String(r && r.id || ''); if (!/^i[a-f0-9]{11}$/.test(id)) continue;
|
|
const owner = norm(r.owner); if (!owner || owner.length > 190) continue;
|
|
const ts = Number(r.ts) || Date.now(); if (ts > Date.now() + 600000 || Date.now() - ts > WINDOW_MS) continue;
|
|
const sk = /^s:[a-f0-9]{20}$/.test(String(r.sk || '')) ? String(r.sk) : '';
|
|
const had = !!st.clicks[id];
|
|
st.clicks[id] = { id, k: 'iap', camp: Number(r.camp) || 0, cname: String(r.cname || '').slice(0, 80), type: String(r.type || '').slice(0, 12), owner, ts, sk,
|
|
c: String(r.c || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2), dv: r.dv === 'mobile' ? 'mobile' : 'desktop', pl: String(r.pl || '').slice(0, 80), self: r.self || isOwnerSk(owner, sk) ? 1 : undefined, target: String(r.target || '').slice(0, 300) };
|
|
if (r.camp) { const key = 'iap:' + Number(r.camp); const cur = st.camps[key] || {}; if (!cur.ts || ts >= cur.ts) st.camps[key] = { owner, name: String(r.cname || '').slice(0, 80), spent: Math.max(0, Number(r.spent) || 0), ts }; }
|
|
if (!had && sk) noteSoft(sk, id, owner, ts);
|
|
n++;
|
|
}
|
|
if (n) { trimClicks(); save(); }
|
|
return n;
|
|
}
|
|
function trimClicks() {
|
|
const st = load(); const keys = Object.keys(st.clicks); if (keys.length <= MAX_CLICKS) return;
|
|
keys.sort((a, b) => st.clicks[a].ts - st.clicks[b].ts); for (const k of keys.slice(0, keys.length - Math.floor(MAX_CLICKS * 0.8))) delete st.clicks[k];
|
|
}
|
|
function prune() {
|
|
const st = load(); const now = Date.now();
|
|
for (const k in st.clicks) if (now - st.clicks[k].ts > WINDOW_MS + DAY) delete st.clicks[k];
|
|
for (const k in st.soft) { const l = st.soft[k].filter(x => now - x[1] <= SOFT_MS); if (l.length) st.soft[k] = l; else delete st.soft[k]; }
|
|
for (const k in st.camps) if (now - st.camps[k].ts > 400 * DAY) delete st.camps[k];
|
|
for (const k in st.selfIds) if (now - st.selfIds[k] > OWN_MS) delete st.selfIds[k];
|
|
for (const k in st.own) { const m = st.own[k]; for (const e in m) if (now - m[e] > OWN_MS) delete m[e]; if (!Object.keys(m).length) delete st.own[k]; }
|
|
if (st.conv.length > MAX_CONV) st.conv = st.conv.slice(-Math.floor(MAX_CONV * 0.8));
|
|
save(); flush();
|
|
}
|
|
|
|
// What a click id is, who owns it, where it came from. Spin-link clicks live in rotator.json.
|
|
function lookup(id) {
|
|
id = String(id || ''); if (!isClickId(id)) return null;
|
|
const st = load();
|
|
const ad = st.clicks[id];
|
|
if (ad) return { id, root: id, ts: ad.ts, owners: [ad.owner], ad };
|
|
if (rotator && rotator.hitById && id[0] !== 'k') { // spin-link ids are 10 hex, never 'k' (that is Banner Spin's)
|
|
const h = rotator.hitById(id); if (!h || !h.hit || h.hit.bot) return null;
|
|
const via = h.hit.ac && st.clicks[h.hit.ac] ? st.clicks[h.hit.ac] : null;
|
|
return { id, root: via ? via.id : id, ts: via ? Math.min(via.ts, h.hit.ts) : h.hit.ts, owners: [h.owner].concat(via ? [via.owner] : []), ad: via, spin: h };
|
|
}
|
|
// a Banner Spin click ('k' + 11 hex) that went straight to a page (2026-10-26: those now carry lsclk too)
|
|
if (bannerspin && bannerspin.clickById && id[0] === 'k') {
|
|
const b = bannerspin.clickById(id); if (!b || !b.click || b.click.bot) return null;
|
|
return { id, root: id, ts: b.click.ts, owners: [b.owner], bspin: b };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// ── the goal pixel ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
const RL = { px: new Map(), ip: new Map() };
|
|
function rateOk(map, key, max, ms) { const now = Date.now(); const a = (map.get(key) || []).filter(t => now - t < ms); if (a.length >= max) { map.set(key, a); return false; } a.push(now); map.set(key, a); if (map.size > 50000) map.clear(); return true; }
|
|
setInterval(() => { const now = Date.now(); for (const m of [RL.px, RL.ip]) for (const [k, a] of m) if (!a.some(t => now - t < 3600000)) m.delete(k); }, 600000).unref();
|
|
const LIMITS = { pxPerMin: 60, pxPerHour: 1000, ipPerMin: 20 };
|
|
|
|
// q: { px, goal, value, c (click id from the page), m ('url'|'stored', who found it), test }
|
|
// cookies: { 'ls.clk', 'ls.click' }. Returns { result, method?, conv? } where result is counted | dup | nomatch | unknown | limited | test | refused
|
|
function record(q, req, cookies) {
|
|
const g = goal(q.px); if (!g) return { result: 'unknown' };
|
|
const sk = softKey(req); const ip = sk; // the soft key doubles as the per-visitor rate key (no raw IP held)
|
|
if (!rateOk(RL.ip, ip, LIMITS.ipPerMin, 60000)) return { result: 'limited' };
|
|
if (!rateOk(RL.px, g.px + ':m', LIMITS.pxPerMin, 60000) || !rateOk(RL.px, g.px + ':h', LIMITS.pxPerHour, 3600000)) return { result: 'limited' };
|
|
if (q.test) { load().tests[g.px] = Date.now(); save(); return { result: 'test', at: load().tests[g.px] }; }
|
|
const now = Date.now(); let refused = 0;
|
|
const tryId = (id, method) => {
|
|
const L = lookup(id); if (!L) return null;
|
|
if (!L.owners.includes(g.owner)) { refused++; return null; } // someone else's click: never counted for this pixel
|
|
if (now - L.ts > WINDOW_MS) return null;
|
|
return Object.assign(L, { method });
|
|
};
|
|
let hit = null;
|
|
if (isClickId(q.c)) hit = tryId(q.c, q.m === 'stored' ? 'stored' : 'url');
|
|
if (!hit) for (const ck of ['ls.clk', 'ls.click']) { const v = cookies && cookies[ck]; if (!hit && isClickId(v)) hit = tryId(v, 'cookie'); }
|
|
if (!hit) { const list = (load().soft[sk] || []).filter(x => x[2] === g.owner && now - x[1] <= SOFT_MS).sort((a, b) => b[1] - a[1]); for (const x of list) { hit = tryId(x[0], 'soft'); if (hit) break; } }
|
|
if (!hit) return { result: refused ? 'refused' : 'nomatch' };
|
|
const st = load();
|
|
if (st.conv.some(c => c.px === g.px && (c.root === hit.root || c.click === hit.id || c.root === hit.id))) return { result: 'dup', method: hit.method };
|
|
const ad = hit.ad, sp = hit.spin, bs = hit.bspin;
|
|
const value = q.value != null && q.value !== '' ? cleanValue(q.value) : (g.value || 0);
|
|
// the goal owner's own click, on ANY click type (ad, spin link, Banner Spin): kept as a test, never in the counts.
|
|
// Own = the ad click was flagged self for this owner, the spin / Banner Spin click was marked at click time, or the
|
|
// clicking or converting browser is one the owner has been seen signed in from (2026-10-26).
|
|
const self = (ad && ad.self && ad.owner === g.owner) || st.selfIds[hit.id] || st.selfIds[hit.root] || isOwnerSk(g.owner, sk) || (ad && ad.sk && isOwnerSk(g.owner, ad.sk)) ? 1 : undefined;
|
|
const conv = { id: crypto.randomBytes(6).toString('hex'), ts: now, px: g.px, goal: g.name, owner: g.owner, click: hit.id, root: hit.root, method: hit.method, value,
|
|
k: ad ? ad.k : (bs ? 'bspin' : 'spin'), camp: ad ? ad.camp : undefined, cname: ad ? ad.cname : undefined, ctype: ad ? ad.type : undefined,
|
|
rot: sp ? sp.rotation.id : undefined, rcode: sp ? sp.rotation.code : undefined, rname: sp ? sp.rotation.name : undefined,
|
|
bs: bs ? bs.spin.id : undefined, bcode: bs ? bs.spin.code : undefined, bname: bs ? bs.spin.name : undefined, bban: bs && bs.banner ? bs.banner.id : undefined,
|
|
dest: sp ? sp.destUrl : (bs ? bs.destUrl : (ad ? ad.target : undefined)), sr: sp ? (sp.hit.sr || undefined) : (bs ? (bs.click.sr || undefined) : undefined), src: sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : undefined)),
|
|
c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.dv : ad && ad.dv)) || '', self };
|
|
for (const k of Object.keys(conv)) if (conv[k] === undefined) delete conv[k];
|
|
st.conv.push(conv); save();
|
|
return { result: 'counted', method: hit.method, conv, hit };
|
|
}
|
|
// the postback context for a counted conversion (postbacks.fire)
|
|
function postbackCtx(r) {
|
|
const c = r.conv, sp = r.hit && r.hit.spin, bs = r.hit && r.hit.bspin;
|
|
return { q: sp ? (sp.hit.q || {}) : (bs ? (bs.click.q || {}) : {}), source: c.src || '', country: c.c || '', device: c.dv || '', lsid: c.click, code: c.rcode || c.bcode || '', sourceId: c.sr || '', payout: c.value || 0, currency: 'USD', label: c.goal };
|
|
}
|
|
// the landing tag's beacon: it saw a click id on the member's page. Returns the id when it is a real click of the pixel's owner.
|
|
function landing(px, id, req) {
|
|
const g = goal(px); if (!g || !isClickId(id)) return null;
|
|
if (!rateOk(RL.ip, softKey(req) + ':t', 60, 60000)) return null;
|
|
const L = lookup(id); if (!L || !L.owners.includes(g.owner) || Date.now() - L.ts > WINDOW_MS) return null;
|
|
noteSoft(softKey(req), id, g.owner); return id;
|
|
}
|
|
|
|
// ── reports ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
// per goal: totals, match methods, and breakdowns by ad campaign (LinkSpin + InstantAdPay), spin link, destination
|
|
// and traffic source. Cost per goal on ad campaigns = the campaign's credits spent / its conversions of that goal.
|
|
async function report(owner, days, opts) {
|
|
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
|
|
const goals = goalsOf(o); const st = load();
|
|
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
|
|
const selfTests = st.conv.filter(c => c.owner === o && c.ts >= since && c.self).length;
|
|
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 };
|
|
const byGoal = {};
|
|
const at = (gname) => (byGoal[gname] = byGoal[gname] || { goal: gname, n: 0, value: 0, methods: { url: 0, stored: 0, cookie: 0, soft: 0 }, campaigns: {}, links: {}, banners: {}, dests: {}, sources: {} });
|
|
for (const c of conv) {
|
|
const G = at(c.goal); G.n++; G.value += c.value || 0; G.methods[c.method] = (G.methods[c.method] || 0) + 1; methods[c.method] = (methods[c.method] || 0) + 1;
|
|
if (c.camp) { const key = (c.k === 'iap' ? 'iap:' : 'ls:') + c.camp; const x = G.campaigns[key] = G.campaigns[key] || { key, site: c.k === 'iap' ? 'InstantAdPay' : 'LinkSpin', id: c.camp, name: c.cname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
|
|
if (c.rot) { const x = G.links[c.rot] = G.links[c.rot] || { id: c.rot, code: c.rcode, name: c.rname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
|
|
if (c.bs) { const x = G.banners[c.bs] = G.banners[c.bs] || { id: c.bs, code: c.bcode, name: c.bname || '', n: 0, value: 0 }; x.n++; x.value += c.value || 0; }
|
|
if (c.dest) { let d = c.dest; try { const u = new URL(c.dest); d = u.hostname.replace(/^www\./, '') + u.pathname.replace(/\/$/, ''); } catch (e) {} const x = G.dests[d] = G.dests[d] || { k: d, n: 0 }; x.n++; }
|
|
{ const key = c.sr ? 'src:' + c.sr : (c.src || '(direct)'); const x = G.sources[key] = G.sources[key] || { k: key, sourceId: c.sr || '', n: 0 }; x.n++; }
|
|
}
|
|
// clicks per ad campaign in the same window, and the cost basis
|
|
const clicksBy = {}; for (const k in st.clicks) { const a = st.clicks[k]; if (a.owner !== o || a.ts < since || a.self) continue; const key = (a.k === 'iap' ? 'iap:' : 'ls:') + a.camp; clicksBy[key] = (clicksBy[key] || 0) + 1; }
|
|
const meta = (opts && opts.sourceMeta) || {};
|
|
const out = [];
|
|
for (const gname of new Set(goals.map(g => g.name).concat(Object.keys(byGoal)))) {
|
|
const G = byGoal[gname] || at(gname);
|
|
const campaigns = [];
|
|
for (const x of Object.values(G.campaigns)) {
|
|
let spent = null, asOf = null;
|
|
if (x.site === 'LinkSpin') { try { const cp = await campaignOf(x.id); if (cp && norm(cp.owner) === o) { spent = Number(cp.spent || 0) + Number(cp.accrued || 0); if (!x.name) x.name = cp.name || ''; } } catch (e) {} }
|
|
else { const cm = st.camps['iap:' + x.id]; if (cm && cm.owner === o) { spent = cm.spent; asOf = cm.ts; if (!x.name) x.name = cm.name; } }
|
|
campaigns.push(Object.assign(x, { clicks: clicksBy[x.key] || 0, spent, spentAsOf: asOf, costPer: spent != null && x.n ? Math.round(spent / x.n * 100) / 100 : null, rate: clicksBy[x.key] ? Math.round(x.n / clicksBy[x.key] * 1000) / 10 : null }));
|
|
}
|
|
campaigns.sort((a, b) => b.n - a.n);
|
|
const sources = Object.values(G.sources).map(x => Object.assign(x, { name: x.sourceId ? ((meta[x.sourceId] || {}).name || 'Deleted source') : x.k })).sort((a, b) => b.n - a.n).slice(0, 15);
|
|
const g = goals.find(y => y.name === gname);
|
|
out.push({ goal: gname, px: g ? g.px : null, removed: !g, n: G.n, value: Math.round(G.value * 100) / 100, methods: G.methods, campaigns,
|
|
links: Object.values(G.links).sort((a, b) => b.n - a.n).slice(0, 15), banners: Object.values(G.banners).sort((a, b) => b.n - a.n).slice(0, 15), dests: Object.values(G.dests).sort((a, b) => b.n - a.n).slice(0, 15), sources });
|
|
}
|
|
return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })),
|
|
byGoal: out, methods, total: conv.length, selfTests };
|
|
}
|
|
// goal conversions as rows, own-click tests left out. goalRows() = every row that came through a spin link, in the rotator's own
|
|
// shape, so per-link counts include goals (2026-11-07); memoized on the length of the log, the pixel only ever appends to it.
|
|
let GR = { n: -1, rows: [] };
|
|
function goalRows() { const c = load().conv; if (GR.n !== c.length) GR = { n: c.length, rows: c.filter(x => x.rot && !x.self).map(x => ({ r: x.rot, lsid: x.click, ev: 'goal: ' + x.goal, ts: x.ts, value: x.value || 0, sr: x.sr })) }; return GR.rows; }
|
|
function goalRowsOf(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self); }
|
|
// the click-side test of "is this the owner's own": the click was theirs, or the converting browser is one they sign in from
|
|
function selfFor(L, owner, sk) {
|
|
const st = load(), ad = L.ad, o = norm(owner);
|
|
return !!(st.selfIds[L.id] || st.selfIds[L.root] || (ad && ad.owner === o && (ad.self || (ad.sk && isOwnerSk(o, ad.sk)))) || (sk && isOwnerSk(o, sk)));
|
|
}
|
|
// InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner
|
|
// goal conversions (not the owner's own tests) since a moment, for the Engine Room's goals dial (2026-10-24)
|
|
function countSince(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self).length; }
|
|
function partnerSummary(owner, days) {
|
|
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(90, Number(days) || 30))) * DAY; const st = load();
|
|
const conv = st.conv.filter(c => c.owner === o && c.ts >= since && !c.self);
|
|
const byCampaign = {};
|
|
for (const k in st.clicks) { const a = st.clicks[k]; if (a.k !== 'iap' || a.owner !== o || a.ts < since || a.self) continue; const b = byCampaign[a.camp] = byCampaign[a.camp] || { clicks: 0, conv: {}, value: {} }; b.clicks++; }
|
|
for (const c of conv) if (c.k === 'iap' && c.camp) { const b = byCampaign[c.camp] = byCampaign[c.camp] || { clicks: 0, conv: {}, value: {} }; b.conv[c.px] = (b.conv[c.px] || 0) + 1; b.value[c.px] = Math.round(((b.value[c.px] || 0) + (c.value || 0)) * 100) / 100; }
|
|
const methods = { url: 0, stored: 0, cookie: 0, soft: 0 }; for (const c of conv) methods[c.method] = (methods[c.method] || 0) + 1;
|
|
const goals = goalsOf(o).map(g => { const mine = conv.filter(c => c.px === g.px); return Object.assign(pubGoal(g), { conv: mine.length, convDays: Number(days) || 30, lastAt: mine.length ? mine[mine.length - 1].ts : null }); });
|
|
const selfTests = st.conv.filter(c => c.owner === o && c.ts >= since && c.self).length; // own clicks, kept as tests (InstantAdPay shows "N from your own clicks")
|
|
return { ok: true, goals, byCampaign, methods, selfTests };
|
|
}
|
|
function csv(owner, days) {
|
|
const o = norm(owner); const since = Date.now() - (Math.max(1, Math.min(400, Number(days) || 30))) * DAY;
|
|
const esc = v => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) || /^[=+\-@]/.test(s) ? '"' + (/^[=+\-@]/.test(s) ? "'" : '') + s.replace(/"/g, '""') + '"' : s; };
|
|
const ctFmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
|
|
const lines = ['time_central,goal,value,match_method,site,campaign_id,campaign,spin_link,destination,source,country,device,click_id'];
|
|
for (const c of load().conv) if (c.owner === o && c.ts >= since && !c.self) lines.push([ctFmt.format(new Date(c.ts)).replace(',', ''), c.goal, c.value || 0, c.method, c.k === 'iap' ? 'InstantAdPay' : (c.k === 'ad' ? 'LinkSpin ad' : (c.k === 'bspin' ? 'Banner Spin' : 'Spin link')), c.camp || '', c.cname || '', c.rcode || (c.bcode ? 'c/' + c.bcode : ''), c.dest || '', c.src || '', c.c || '', c.dv || '', c.click].map(esc).join(','));
|
|
return lines.join('\n') + '\n';
|
|
}
|
|
// "Send a test conversion" from a screen (InstantAdPay's partner call, or the Control Room when it cannot load the image)
|
|
function testGoal(owner, px) { const g = goal(px); if (!g || g.owner !== norm(owner)) return { error: 'No such goal.' }; load().tests[g.px] = Date.now(); save(); flush(); return { ok: true, at: load().tests[g.px] }; }
|
|
function adminCounts() { const st = load(); return { goals: Object.keys(st.goals).length, clicks: Object.keys(st.clicks).length, conversions: st.conv.length }; }
|
|
// append lsclk=<id> the way InstantAdPay's lsconv.withClickId does: string insert (every existing param keeps its exact
|
|
// encoding), before any #hash, an lsclk already there never replaced, a URL that does not parse goes out unchanged
|
|
function withClickId(target, id) {
|
|
const t = String(target || '');
|
|
let u; try { u = new URL(t); } catch (e) { return t; }
|
|
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk') || !isClickId(id)) return t;
|
|
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
|
|
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
|
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
|
}
|
|
module.exports = { goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS };
|