Banner Spin phase 3: reports, health checks, postbacks verified, admin switch button
- bannerspin.js: every image load also counted raw per placement (bots/prefetch and servers/mail image proxies kept apart from views); one aggregation for the Stats tab and a new summary() for Reports: per banner (views, uniques, clicks, CTR, match rate, conversions), per placement with a "caches banners" flag, by Central day, country and device, bots shown separately; WINNER badge once two live banners have 1,000 views each and one leads on CTR. Click params now keep the banner macro (same list as spin links). Owner pause/resume clears an auto-pause; a new image or target resets health. - health.js: the 30-minute pass also checks each live banner: image must load as an image (magic bytes) at the Banner Spin size, target must pass the spin-link checks (a spin-link target only has to exist). 3 failures pause, 2 clean passes resume, the last live banner is never auto-paused; owner gets an inbox notice. checkBannerSpins() for admin. - server.js (own blocks): health.init gets bannerspin; /api/my/reports adds bannerSpins; POST /api/admin/bannerspins/health runs the checks now. - Builder: health line + AUTO-PAUSED tag on every banner row; Stats tab adds uniques, WINNER, CACHED placements, loads, country/device, bots line. - Reports screen: Banner Spin section + Banner views/clicks tiles beside spin links. - Admin > Member content: real Banner Spin on/off button (with confirm) and "Run banner checks". - Traffic-source postbacks on Banner Spin clicks verified end to end (network click id, event, payout, lsid reach the source postback). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+122
-32
@@ -28,7 +28,12 @@
|
||||
// below a tier keeps everything serving; it only stops new ones.
|
||||
//
|
||||
// Moderation. Admin can take one banner or a whole Banner Spin offline (a neutral blank image + the fallback link), or
|
||||
// switch the whole feature off. Store: DATA_DIR/bannerspin.json (atomic writes).
|
||||
// switch the whole feature off (a button in Admin > Member content since phase 3). Store: DATA_DIR/bannerspin.json (atomic writes).
|
||||
//
|
||||
// Phase 3 (2026-10-20, "Reports and health"): every image load is also counted raw per placement (bots, prefetches and
|
||||
// servers / mail image proxies kept apart from views), which feeds the "caches banners" flag; stats() and summary() share
|
||||
// one aggregation (per banner, per placement, by Central day, country and device, a winner once two banners have 1,000
|
||||
// views each); health.js checks each live banner's image and target every 30 minutes (b.health, b.autoPaused).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -83,6 +88,11 @@ const vkey = (req, ts) => crypto.createHash('sha256').update(new Date(ts || Date
|
||||
function vkeys(req) { const now = Date.now(); const k = [vkey(req, now)]; if (now % DAY < NOTE_TTL) k.push(vkey(req, now - DAY)); return k; }
|
||||
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT.test(ua); };
|
||||
const isPrefetch = req => /prefetch|prerender|preview/i.test([req.headers.purpose, req.headers['sec-purpose'], req.headers['x-purpose'], req.headers['x-moz']].filter(Boolean).join(' '));
|
||||
// a server fetching the image, not a browser (phase 3, 2026-10-20): mail image proxies and plain HTTP libraries. Kept out of
|
||||
// impressions like bots, but counted per placement, because a site that copies banners to its own server shows up this way.
|
||||
const PROXY = /GoogleImageProxy|ggpht\.com|YahooMailProxy|ImageProxy|^(php|java|go-http-client|okhttp|axios|node-fetch|undici|libwww-perl|apache-httpclient|guzzlehttp|ruby)\b/i;
|
||||
// '' = a browser view (counted), 'pre' = prefetch, 'bot' = bot or no UA, 'srv' = a server or image proxy
|
||||
const loaderKind = req => isPrefetch(req) ? 'pre' : isBot(req) ? 'bot' : PROXY.test(String(req.headers['user-agent'] || '')) ? 'srv' : '';
|
||||
// the placement: the page the banner sits on (the browser's referrer, else its origin), www stripped
|
||||
function hostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, '').slice(0, 80); } catch (e) { return ''; } }
|
||||
|
||||
@@ -98,18 +108,33 @@ function findNote(keys, s, h) {
|
||||
function sweep() { const now = Date.now(); for (const [k, a] of NOTES) { const keep = a.filter(n => now - n.ts <= NOTE_TTL); if (keep.length) NOTES.set(k, keep); else NOTES.delete(k); } for (const [k, t] of SEEN) if (now - t > DEDUPE_MS) SEEN.delete(k); }
|
||||
|
||||
// ── counters ──
|
||||
// a day record: b = counted views per banner, h = per placement host per banner, u = uniques sample per banner,
|
||||
// bt = bot + prefetch loads, sv = server / image-proxy loads, z = per placement host { r: every load, s: loads with no browser, k: top loaders sample }
|
||||
const dayRec = sid => { const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; return s[day] = s[day] || { b: {}, h: {}, u: {}, z: {} }; };
|
||||
function bump(sid, bid, host, v) {
|
||||
const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
|
||||
const d = dayRec(sid);
|
||||
d.b[bid] = (d.b[bid] || 0) + 1; const hk = host || '(none)'; const hh = d.h[hk] = d.h[hk] || {}; hh[bid] = (hh[bid] || 0) + 1;
|
||||
const u = d.u[bid] = d.u[bid] || []; const p = v.slice(0, 8); if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p);
|
||||
DIRTY = true;
|
||||
}
|
||||
// every image load (counted or not), for bots shown separately and the "caches banners" flag
|
||||
const LOADERS_CAP = 10;
|
||||
function rawLoad(sid, host, v, kind) {
|
||||
const d = dayRec(sid); const hk = host || '(none)'; const z = d.z[hk] = d.z[hk] || { r: 0, s: 0, k: {} };
|
||||
z.r++; if (kind === 'bot' || kind === 'srv') z.s++;
|
||||
const p = v.slice(0, 8); if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + 1;
|
||||
if (kind === 'bot' || kind === 'pre') d.bt = (d.bt || 0) + 1; else if (kind === 'srv') d.sv = (d.sv || 0) + 1;
|
||||
DIRTY = true;
|
||||
}
|
||||
function mergeInto(base, add) {
|
||||
for (const [sid, days] of Object.entries(add.d)) { const s = base.d[sid] = base.d[sid] || {};
|
||||
for (const [day, x] of Object.entries(days)) { const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
|
||||
for (const [b, n] of Object.entries(x.b)) d.b[b] = (d.b[b] || 0) + n;
|
||||
for (const [h, m] of Object.entries(x.h)) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
|
||||
for (const [b, arr] of Object.entries(x.u)) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); } } }
|
||||
for (const [b, n] of Object.entries(x.b || {})) d.b[b] = (d.b[b] || 0) + n;
|
||||
for (const [h, m] of Object.entries(x.h || {})) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
|
||||
for (const [b, arr] of Object.entries(x.u || {})) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); }
|
||||
if (x.bt) d.bt = (d.bt || 0) + x.bt; if (x.sv) d.sv = (d.sv || 0) + x.sv;
|
||||
if (x.z) { d.z = d.z || {}; for (const [h, zz] of Object.entries(x.z)) { let z = d.z[h]; if (!z) { const key = Object.keys(d.z).length >= HOSTS_CAP ? '(other)' : h; z = d.z[key] = d.z[key] || { r: 0, s: 0, k: {} }; }
|
||||
z.r += zz.r || 0; z.s += zz.s || 0; for (const [p, n] of Object.entries(zz.k || {})) if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + n; } } } }
|
||||
return base;
|
||||
}
|
||||
function flush() {
|
||||
@@ -162,7 +187,8 @@ function pub(s, extra) {
|
||||
return Object.assign({ id: s.id, code: s.code, name: s.name, size: s.size, mode: s.mode || 'weight', owner: s.owner, created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '',
|
||||
fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', hours: s.hours || null, tz: s.tz || 'visitor', sourceId: s.sourceId || '',
|
||||
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, w: b.w || 0, h: b.h || 0, bytes: b.bytes || 0, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff, hours: b.hours || null, added: b.added,
|
||||
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h) })),
|
||||
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h),
|
||||
autoPaused: b.autoPaused || 0, health: b.health ? { state: b.health.state, note: b.health.note || '', checkedAt: b.health.checkedAt || 0, fails: b.health.fails || 0, image: b.health.image || null, target: b.health.target || null } : null })),
|
||||
imps: sum(imps), imps30: sum(imps30), fallbackImps: imps[0] || 0, clicks: sum(cl), matched: Object.values(cl).reduce((a, o) => a + o.m, 0), conversions: conv }, extra || {});
|
||||
}
|
||||
async function list(owner) { return mine(owner).map(s => pub(s)); }
|
||||
@@ -203,10 +229,10 @@ async function updateBanner(owner, id, bid, body) {
|
||||
const b = s.banners.find(x => x.id === Number(bid)); if (!b) return { error: 'No such banner.' };
|
||||
if (body.remove) { s.banners = s.banners.filter(x => x !== b); J.save(); return { ok: true, spin: pub(s) }; }
|
||||
if (body.weight != null) b.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
|
||||
if (body.active != null) b.active = !!body.active;
|
||||
if (body.active != null) { b.active = !!body.active; delete b.autoPaused; } // the owner's own pause / resume wins over the health checker
|
||||
if (body.label != null) b.label = String(body.label).trim().slice(0, 60);
|
||||
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); }
|
||||
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; }
|
||||
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); delete b.health; }
|
||||
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; delete b.health; }
|
||||
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) b.hours = h.hours; else delete b.hours; }
|
||||
J.save(); return { ok: true, spin: pub(s) };
|
||||
}
|
||||
@@ -243,7 +269,8 @@ function choose(s, req, opts) {
|
||||
const off = s.paused || !rotator.isOn(s.hours, cell);
|
||||
const b = off ? null : pick(s, cell, v);
|
||||
const out = b ? { banner: b } : (s.fallbackImage ? { fallback: true } : { blank: true, fallback: true });
|
||||
if (!isBot(req) && !isPrefetch(req)) {
|
||||
const kind = loaderKind(req); rawLoad(String(s.id), hostOf(req), v, kind);
|
||||
if (!kind) {
|
||||
const bid = b ? b.id : 0; const host = hostOf(req);
|
||||
note(v, s.id, host, bid);
|
||||
const k = v + '|' + s.id + '|' + bid; const last = SEEN.get(k);
|
||||
@@ -287,7 +314,7 @@ async function click(code, req, reqHost) {
|
||||
if (!url) { const first = s.banners.find(q => q.active && !q.adminOff && q.target); url = first ? first.target : null; } // no fallback set: the first live banner beats a dead end
|
||||
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {}
|
||||
const ua = String(req.headers['user-agent'] || ''); const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
|
||||
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
|
||||
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|banner|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
|
||||
const id = 'k' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
||||
J.db.clicks.push({ id, s: s.id, b: b ? b.id : 0, ts: Date.now(), v: keys[0], h: h || undefined, m, bot, c: country || undefined, dv: device, q: Object.keys(q).length ? q : undefined, sr: s.sourceId || undefined });
|
||||
if (J.db.clicks.length > 200000) J.db.clicks = J.db.clicks.slice(-150000);
|
||||
@@ -308,28 +335,87 @@ async function convert(lsid, ev, facts) {
|
||||
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
|
||||
}
|
||||
|
||||
// ── stats: per banner and per placement (impressions, clicks, CTR, match rate), last 30 Central days by day ──
|
||||
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
|
||||
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
|
||||
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
|
||||
// sinceTs = 0 means all time (the builder); Reports passes its range. Day keys are Central time.
|
||||
const WIN_MIN = 1000; // a winner needs this many views on every banner it is compared with
|
||||
const ctrOf = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null;
|
||||
const mrOf = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
|
||||
function agg(spins, sinceTs) {
|
||||
const sinceDay = sinceTs ? ctDay(sinceTs) : '';
|
||||
const ids = new Set(spins.map(s => s.id));
|
||||
const blank = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0, bots: 0, botClicks: 0, srv: 0, raw: 0, top: {} });
|
||||
const at = (o, k) => (o[k] = o[k] || blank());
|
||||
const per = {}, hosts = {}, days = {}, T = blank();
|
||||
for (const s of spins) for (const [day, d] of Object.entries(countsOf(s.id))) {
|
||||
if (sinceDay && day < sinceDay) continue;
|
||||
const dd = at(days, day);
|
||||
for (const [b, n] of Object.entries(d.b || {})) { at(per, s.id + ':' + b).imps += n; dd.imps += n; T.imps += n; }
|
||||
for (const [b, arr] of Object.entries(d.u || {})) { at(per, s.id + ':' + b).uniq += arr.length; dd.uniq += arr.length; T.uniq += arr.length; }
|
||||
for (const [h, m] of Object.entries(d.h || {})) for (const n of Object.values(m)) at(hosts, h).imps += n;
|
||||
dd.bots += d.bt || 0; T.bots += d.bt || 0; dd.srv += d.sv || 0; T.srv += d.sv || 0;
|
||||
for (const [h, z] of Object.entries(d.z || {})) { const o = at(hosts, h); o.raw += z.r || 0; o.srv += z.s || 0; for (const [k, n] of Object.entries(z.k || {})) o.top[k] = (o.top[k] || 0) + n; }
|
||||
}
|
||||
const country = {}, device = {};
|
||||
for (const c of J.db.clicks) {
|
||||
if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue;
|
||||
const dd = at(days, ctDay(c.ts));
|
||||
if (c.bot) { T.botClicks++; dd.botClicks++; continue; }
|
||||
const ok = c.m === 'exact' || c.m === 'note';
|
||||
for (const o of [at(per, c.s + ':' + c.b), at(hosts, c.h || '(none)'), dd, T]) { o.clicks++; if (ok) o.matched++; else if (c.m === 'none') o.unmatched++; }
|
||||
const k = c.c || '(none)'; country[k] = (country[k] || 0) + 1; const dv = c.dv || '(none)'; device[dv] = (device[dv] || 0) + 1;
|
||||
}
|
||||
const convBy = {};
|
||||
for (const c of J.db.conv) { if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue; at(per, c.s + ':' + c.b).conv++; T.conv++; at(days, ctDay(c.ts)).conv++; const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
|
||||
return { per, hosts, days, T, country, device, convBy };
|
||||
}
|
||||
// the "caches banners" flag: a placement whose image loads come from a server instead of browsers, or whose clicks
|
||||
// cannot be tied to a view (a copied image never asks us, so the click arrives with no note). '' when it looks normal.
|
||||
function cacheFlag(o) {
|
||||
if (o.srv >= 5 && o.srv >= o.raw * 0.5) return 'Most image loads here come from a server, not a browser (' + o.srv + ' of ' + o.raw + '). This site most likely copies banners to its own server, so the rotation is frozen there.';
|
||||
const top = Math.max(0, ...Object.values(o.top || {}));
|
||||
if (o.raw >= 50 && top >= o.raw * 0.8 && o.clicks <= o.raw * 0.01) return 'One loader made ' + Math.round(top / o.raw * 100) + '% of the ' + o.raw + ' image loads here and almost nobody clicks. This site most likely caches banners, so the rotation is frozen there.';
|
||||
// more clicks than views alone is not enough (one visitor's reloads count once a minute, clicks are not deduped): a copy also leaves the clicks unmatched
|
||||
if (o.clicks >= 10 && o.clicks > o.imps && o.matched / o.clicks < 0.5) return 'More clicks (' + o.clicks + ') than views we served (' + o.imps + '). This site shows a copy of the banner, so the rotation is frozen there and clicks go to the fallback.';
|
||||
if (o.clicks >= 10 && o.matched / o.clicks < 0.3) return 'Only ' + Math.round(o.matched / o.clicks * 100) + '% of clicks here match a view. This site most likely caches banners, so the rotation is frozen there.';
|
||||
return '';
|
||||
}
|
||||
// winner: among the live banners of one Banner Spin with at least WIN_MIN views each, the one with the best CTR (strictly ahead)
|
||||
function winnerOf(rows) {
|
||||
const q = rows.filter(r => r.imps >= WIN_MIN && r.ctr != null).sort((a, b) => b.ctr - a.ctr);
|
||||
return q.length >= 2 && q[0].ctr > q[1].ctr ? q[0].id : 0;
|
||||
}
|
||||
const listOf = m => Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n }));
|
||||
const dayRows = (days, sinceDay) => Object.entries(days).filter(([d]) => !sinceDay || d >= sinceDay).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks, bots: o.bots, botClicks: o.botClicks, servers: o.srv, conv: o.conv }));
|
||||
const placementRows = hosts => Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), loads: o.raw, serverLoads: o.srv, caches: cacheFlag(o) }))
|
||||
.filter(p => p.imps || p.clicks || p.loads).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30);
|
||||
|
||||
async function stats(owner, id) {
|
||||
const s = findMine(owner, id); if (!s) return null;
|
||||
const cnt = countsOf(s.id); const clicks = J.db.clicks.filter(c => c.s === s.id && !c.bot);
|
||||
const per = {}; const at = (o, k) => (o[k] = o[k] || { imps: 0, clicks: 0, matched: 0, uniq: 0 });
|
||||
const hosts = {}; const days = {};
|
||||
for (const [day, d] of Object.entries(cnt)) {
|
||||
for (const [b, n] of Object.entries(d.b)) { at(per, b).imps += n; at(days, day).imps += n; }
|
||||
for (const [b, arr] of Object.entries(d.u)) at(per, b).uniq += arr.length;
|
||||
for (const [hh, m] of Object.entries(d.h)) for (const n of Object.values(m)) at(hosts, hh).imps += n;
|
||||
const A = agg([s], 0); const z = blank0();
|
||||
const banners = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
|
||||
const win = winnerOf(banners.filter(b => b.active)); for (const b of banners) b.winner = b.id === win;
|
||||
const fb = A.per[s.id + ':0'] || z;
|
||||
return { spin: pub(s), totals: { imps: A.T.imps, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, uniquesSampled: A.T.uniq, conversions: A.T.conv, bots: A.T.botClicks, botLoads: A.T.bots, serverLoads: A.T.srv },
|
||||
banners, winner: win, winMin: WIN_MIN, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctrOf(fb) },
|
||||
placements: placementRows(A.hosts), days: dayRows(A.days, ctDay(Date.now() - 30 * DAY)), country: listOf(A.country), device: listOf(A.device),
|
||||
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
|
||||
}
|
||||
const blank0 = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0 });
|
||||
// Reports screen: every Banner Spin the member owns over the last `days`, totals + per banner + per placement + day / country / device
|
||||
async function summary(owner, days) {
|
||||
const list = mine(owner); const n = Math.max(1, Math.min(365, Number(days) || 30)); const since = Date.now() - n * DAY;
|
||||
const A = agg(list, since); const z = blank0(); const banners = [];
|
||||
for (const s of list) {
|
||||
const rows = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { spinId: s.id, spin: s.name, code: s.code, size: s.size, id: b.id, label: b.label || 'Banner ' + b.id, image: b.image, active: !!b.active, autoPaused: !!b.autoPaused, imps: o.imps, uniques: o.uniq, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
|
||||
const win = winnerOf(rows.filter(r => r.active)); for (const r of rows) { r.winner = r.id === win; banners.push(r); }
|
||||
}
|
||||
for (const c of clicks) { const ok = c.m === 'exact' || c.m === 'note'; const o = at(per, c.b); o.clicks++; if (ok) o.matched++; const ho = at(hosts, c.h || '(none)'); ho.clicks++; if (ok) ho.matched++; const dd = at(days, ctDay(c.ts)); dd.clicks++; if (ok) dd.matched++; }
|
||||
const ctr = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null; const mr = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
|
||||
const conv = J.db.conv.filter(c => c.s === s.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } const convB = {}; for (const c of conv) convB[c.b] = (convB[c.b] || 0) + 1;
|
||||
const banners = s.banners.map(b => { const o = per[b.id] || { imps: 0, clicks: 0, matched: 0, uniq: 0 }; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctr(o), matchRate: mr(o), conversions: convB[b.id] || 0 }; });
|
||||
const fb = per[0] || { imps: 0, clicks: 0, matched: 0, uniq: 0 };
|
||||
const tot = { imps: 0, clicks: clicks.length, matched: 0, uniq: 0 }; for (const o of Object.values(per)) { tot.imps += o.imps; tot.matched += o.matched; tot.uniq += o.uniq; }
|
||||
const since = ctDay(Date.now() - 30 * DAY);
|
||||
return { spin: pub(s), totals: { imps: tot.imps, clicks: tot.clicks, ctr: ctr(tot), matchRate: mr(tot), matched: tot.matched, unmatched: clicks.filter(c => c.m === 'none').length, uniquesSampled: tot.uniq, conversions: conv.length, bots: J.db.clicks.filter(c => c.s === s.id && c.bot).length },
|
||||
banners, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctr(fb) },
|
||||
placements: Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctr(o), matchRate: mr(o) })).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30),
|
||||
days: Object.entries(days).filter(([d]) => d >= since).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
|
||||
banners.sort((a, b) => b.imps - a.imps || b.clicks - a.clicks);
|
||||
const spins = list.map(s => { let imps = 0, clicks = 0, conv = 0; for (const b of s.banners.concat([{ id: 0 }])) { const o = A.per[s.id + ':' + b.id]; if (o) { imps += o.imps; clicks += o.clicks; conv += o.conv; } } return { id: s.id, name: s.name, code: s.code, size: s.size, imps, clicks, ctr: imps ? Math.round(clicks / imps * 10000) / 100 : null, conversions: conv }; }).sort((a, b) => b.imps - a.imps);
|
||||
return { count: list.length, totals: { imps: A.T.imps, uniques: A.T.uniq, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, conversions: A.T.conv, bots: A.T.bots, botClicks: A.T.botClicks, serverLoads: A.T.srv },
|
||||
days: dayRows(A.days, ctDay(since)), country: listOf(A.country), device: listOf(A.device), banners: banners.slice(0, 50), placements: placementRows(A.hosts), spins, winMin: WIN_MIN,
|
||||
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, c]) => ({ k, n: c })) };
|
||||
}
|
||||
|
||||
// ── admin ──
|
||||
@@ -372,5 +458,9 @@ function readImage(name) {
|
||||
if (buf.length <= MAX_BYTES) { IMG.set(name, rec); IMG_BYTES += buf.length; while (IMG_BYTES > 32 * 1024 * 1024) { const [k, v] = IMG.entries().next().value; IMG.delete(k); IMG_BYTES -= v.buf.length; } }
|
||||
return rec;
|
||||
}
|
||||
const _test = { notes: () => NOTES, flush, vkey };
|
||||
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, _test };
|
||||
// raw access for health.js (phase 3): the same store and save, and where a banner image lives ({ file } on disk or { url })
|
||||
const rawSpins = () => J.db.spins;
|
||||
const save = () => J.save();
|
||||
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
|
||||
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
|
||||
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
|
||||
|
||||
Reference in New Issue
Block a user