Daily LinkSpin snapshot card (Marty 2026-11-02): spin links served, Banner Spin views, zone views, page views and leads, then sign-ups, purchases and POL paid, posted once a day to the LinkSpin Support topic (new target 'support', settings telegramSupportChatId/TopicId); window24() helpers on rotator, bannerspin, zones and pages; POST /api/admin/snapshot/send takes {target} for a one-off

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-02 08:17:38 -06:00
parent fb0afbcb3c
commit d22b8adada
7 changed files with 77 additions and 38 deletions
+10 -1
View File
@@ -454,6 +454,15 @@ function settings() { return { off: !!J.db.settings.off, grants: J.db.grants };
// image files Banner Spins use, for the admin upload list (file name -> owner + where)
function imageRefs() { const out = {}; for (const s of J.db.spins) for (const im of s.banners.map(b => b.image).concat(s.fallbackImage || [])) { const m = LOCAL_IMG.exec(im || ''); if (m) out[m[1]] = { email: s.owner, where: 'Banner Spin ' + s.code }; } for (const [n, r] of Object.entries(J.db.images)) if (!out[n]) out[n] = { email: r.owner, where: '' }; return out; }
function totals() { return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), clicks: J.db.clicks.length }; }
// site-wide figures for the daily snapshot: impressions counted today (Central day, merged counts + pending deltas),
// clicks and new Banner Spins inside the `since` window
function window24(since) {
const day = ctDay(); let imps = 0;
const add = store => { try { for (const sid of Object.keys((store && store.d) || {})) { const r = (store.d[sid] || {})[day]; if (r && r.b) for (const k of Object.keys(r.b)) imps += Number(r.b[k]) || 0; } } catch (e) {} };
add(C.db); add(PENDING);
const clicks = J.db.clicks.filter(c => c.ts >= since && !c.bot);
return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), created: J.db.spins.filter(s => (s.created || 0) >= since).length, impsToday: imps, clicks: clicks.length };
}
// a transparent PNG at the exact banner size, for the blank image (admin off, nothing to show); cached per size
const BLANK = new Map();
@@ -480,4 +489,4 @@ 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, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, window24, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };
+7 -1
View File
@@ -172,6 +172,12 @@ async function write(owner, id, body) {
return { ok: true, page: pub(p), by };
}
function totals() { return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, leads: J.db.leads.length }; }
// site-wide figures for the daily snapshot: page views, leads and new pages inside the `since` window
function window24(since) {
const views = J.db.views.filter(v => v.ts >= since && (v.k || 'view') === 'view');
return { pages: J.db.pages.length, published: J.db.pages.filter(p => p.status === 'published').length, created: J.db.pages.filter(p => (p.created || 0) >= since).length,
views: views.length, unique: new Set(views.map(v => v.v)).size, leads: J.db.leads.filter(l => l.ts >= since).length };
}
// -- Reports (2026-10-10): the member's page views, uniques, clicks-through and leads for the last N days, by Central day and by page
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function summary(owner, days) {
@@ -263,4 +269,4 @@ function adminAll() {
formProvider: p.type === 'squeeze' && c.formEmbed ? formrestyle.provider(c.formEmbed) : null, views: o.views, uniques: o.u.size, clicks: o.clicks, leads: ld[p.id] || 0 }; });
}
function adminImages() { return J.db.images.map(i => Object.assign(pubImage(i), { owner: i.owner })); }
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider, adminAll, adminImages };
module.exports = { init, TYPES, list, get, bySlug, create, update, html, view, lead, leads, csv, scan, write, totals, window24, summary, readUpload, uploadImage, images, removeImage, imageFile, IMG_MAX, IMG_BYTES, providers: () => formrestyle.PROVIDERS, provider: formrestyle.provider, adminAll, adminImages };
+1 -1
View File
@@ -1092,7 +1092,7 @@
}));
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, echo = shared payments topic; comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' };
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, support = LinkSpin Support topic, echo = shared payments topic; comma list)', telegramSupportChatId: 'Telegram LinkSpin Support topic: chat id', telegramSupportTopicId: 'Telegram LinkSpin Support topic: topic id', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' };
function drawSite() {
const wrap = $('siteForm');
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '<div class="kv-row"><span class="k" title="' + esc(k) + '">' + esc(SITE_META[k] || humanize(k)) + '</span>'
+8 -1
View File
@@ -295,6 +295,13 @@ function sweepDemos() {
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' }));
@@ -315,5 +322,5 @@ function adminAll() {
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, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday,
module.exports = { init, 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 };
+3 -2
View File
@@ -724,7 +724,7 @@ async function boot() {
domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)),
notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } });
zonereport.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, rotator, bannerspin, zones, pages, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore,
// network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never
@@ -3975,7 +3975,8 @@ const server = http.createServer(async (req, res) => {
}
if (p === '/api/admin/snapshot/send' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r);
let target = ''; try { target = String(((await readBody(req)) || {}).target || '').trim(); } catch (e) {}
const r = target ? await snapshot.postTo(target) : await snapshot.post(); return json(res, r.error ? 400 : 200, r);
}
// -- level-4 override (2026-10-23): ?week=YYYY-MM-DD (any day of the week) or ?from=&to= (ms); rows=1 adds every purchase.
// Carries the week's payout status and the payer state; pay-now and resolve work only while the live payer is ready.
+42 -31
View File
@@ -1,9 +1,9 @@
// Growth snapshot (Marty, 2026-09-15): once a day, a short "how the site is doing" post in the Telegram
// payments feed (and the shared payments topic), so members watching the payout lines also see the
// whole picture: sign-ups, purchases, POL paid out, campaigns posted, ads viewed. Every number comes
// from the same tables and chain index the dashboards read. Settings: snapshotEnabled (1/0),
// snapshotHourUtc (default 14 = 9 AM Central), snapshotTargets (feed,echo). State: snapshot-state.json.
const { SITE_URL } = require('./host');
// Daily snapshot (Marty, 2026-11-02): once a day, a short "how LinkSpin is doing" card in the LinkSpin Support topic
// (and any other target listed), the LinkSpin counterpart of InstantAdPay's growth snapshot. The card speaks LinkSpin:
// spin links served, Banner Spin impressions, zone views, page views and leads, then sign-ups, purchases and POL paid.
// Every number comes from the same stores the Reports screen reads. Settings: snapshotEnabled (1/0), snapshotHourUtc
// (default 14 = 9 AM Central), snapshotTargets (feed, support, echo). State: snapshot-state.json (lastDay), so a
// restart never double-posts.
const fs = require('fs');
const path = require('path');
@@ -15,26 +15,17 @@ function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); }
function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} }
const n = v => Number(v || 0).toLocaleString('en-US');
const pol = w => { try { return (Number(BigInt(w) / (10n ** 16n)) / 100).toLocaleString('en-US', { maximumFractionDigits: 0 }); } catch (e) { return '0'; } };
const safe = (fn, dflt) => { try { const v = fn(); return v == null ? dflt : v; } catch (e) { return dflt; } };
async function gather(now = Date.now()) {
const since = now - DAY, prior = now - 2 * DAY;
const s = { signups: 0, signupsPrior: 0, members: 0, wallets: 0, payoutsOn: 0, seen24h: 0,
campaigns: 0, advertisers: 0, active: 0, activeAdvertisers: 0, imps: 0, viewers: 0, views: 0,
buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0 };
buys: 0, buysPrior: 0, usd: 0, activations: 0, paidWei: 0n, lifeBuys: 0, lifePaidWei: 0n, lifePayouts: 0,
links: null, spins: null, zones: null, pages: null };
if (X.db && X.db.enabled()) {
const q = (a, b) => X.db.q(a, b || []);
const a = (await q('SELECT COUNT(*) total, SUM(created>=?) s24, SUM(created>=? AND created<?) sPrior, SUM(address IS NOT NULL) wallet, SUM(member_id>0) payouts, SUM(last_seen>=?) seen FROM accounts', [since, prior, since, since]))[0] || {};
s.members = Number(a.total || 0); s.signups = Number(a.s24 || 0); s.signupsPrior = Number(a.sPrior || 0); s.wallets = Number(a.wallet || 0); s.payoutsOn = Number(a.payouts || 0); s.seen24h = Number(a.seen || 0);
const c = (await q('SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND created>=?', [since]))[0] || {};
s.campaigns = Number(c.n || 0); s.advertisers = Number(c.owners || 0);
const ac = (await q("SELECT COUNT(*) n, COUNT(DISTINCT owner_email) owners FROM campaigns WHERE house=0 AND status='active'"))[0] || {};
s.active = Number(ac.n || 0); s.activeAdvertisers = Number(ac.owners || 0);
// impressions in the last 24 hours: camp_hours is keyed by UTC day + hour
const d0 = new Date(since).toISOString().slice(0, 10), h0 = new Date(since).getUTCHours(), d1 = new Date(now).toISOString().slice(0, 10);
const im = (await q('SELECT SUM(n) imps FROM camp_hours WHERE (day=? AND hour>=?) OR (day>? AND day<=?)', [d0, h0, d0, d1]))[0] || {};
s.imps = Number(im.imps || 0);
const v = (await q('SELECT COUNT(*) viewers, SUM(views) views FROM daily_views WHERE day=? AND views>0', [d1]))[0] || {};
s.viewers = Number(v.viewers || 0); s.views = Number(v.views || 0);
}
try {
for (const ev of X.chain.recentEvents(1e9)) {
@@ -42,42 +33,62 @@ async function gather(now = Date.now()) {
else if (ev.type === 'MemberActivated' && ev.ts >= since) s.activations++;
else if (ev.type === 'TierPaid' || ev.type === 'AwardPaid') { s.lifePayouts++; s.lifePaidWei += BigInt(ev.amountWei); if (ev.ts >= since) s.paidWei += BigInt(ev.amountWei); }
}
// the index keeps a bounded event list; lifetime totals come from its running tally when present
const t = X.chain.totals ? X.chain.totals() : null;
if (t) { if (t.purchases) s.lifeBuys = Number(t.purchases); if (t.payoutWei) s.lifePaidWei = BigInt(t.payoutWei); if (t.payouts) s.lifePayouts = Number(t.payouts); }
} catch (e) {}
// the LinkSpin tools, each module answers for every owner at once
s.links = safe(() => X.rotator && X.rotator.window24(since), null);
s.spins = safe(() => X.bannerspin && X.bannerspin.window24(since), null);
s.zones = safe(() => X.zones && X.zones.window24(since), null);
s.pages = safe(() => X.pages && X.pages.window24(since), null);
return s;
}
function compose(s, cta) {
const trend = (cur, prev, what) => cur > prev ? ' (up from ' + n(prev) + ' ' + what + ')' : cur < prev ? ' (' + n(prev) + ' ' + what + ')' : '';
const plural = (k, one, many) => n(k) + ' ' + (k === 1 ? one : many);
const L = [];
L.push('\u{1F4C8} <b>LinkSpin</b> · 24-hour snapshot');
L.push('\u{1F465} Sign-ups: <b>' + n(s.signups) + '</b>' + trend(s.signups, s.signupsPrior, 'the day before') + ' · ' + n(s.activations) + ' switched on payouts');
L.push('\u{1F300} <b>LinkSpin</b> · 24-hour snapshot');
if (s.links) L.push('\u{1F517} Spin links: <b>' + n(s.links.served) + '</b> visitors sent through ' + plural(s.links.links, 'link', 'links') + ' · ' + n(s.links.unique) + ' unique · ' + n(s.links.countries) + ' countries' + (s.links.created ? ' · ' + plural(s.links.created, 'new link', 'new links') : ''));
if (s.spins) L.push('\u{1F5BC} Banner Spin: <b>' + n(s.spins.impsToday) + '</b> banner views today · ' + n(s.spins.clicks) + ' clicks · ' + n(s.spins.banners) + ' banners in ' + plural(s.spins.spins, 'spin', 'spins'));
if (s.zones) L.push('\u{1F4E1} Zones: <b>' + n(s.zones.views) + '</b> ad views on ' + plural(s.zones.zones, 'zone', 'zones') + ' · ' + n(s.zones.viewable) + ' viewable');
if (s.pages) L.push('\u{1F4C4} Pages: <b>' + n(s.pages.views) + '</b> views on ' + plural(s.pages.published, 'published page', 'published pages') + ' · ' + n(s.pages.leads) + ' leads' + (s.pages.created ? ' · ' + plural(s.pages.created, 'new page', 'new pages') : ''));
L.push('\u{1F465} Sign-ups: <b>' + n(s.signups) + '</b>' + trend(s.signups, s.signupsPrior, 'the day before') + ' · ' + n(s.activations) + ' switched on payouts · ' + n(s.seen24h) + ' signed in');
L.push('\u{1F9FE} Purchases: <b>' + n(s.buys) + '</b> for $' + n(Math.round(s.usd)) + trend(s.buys, s.buysPrior, 'the day before') + ' · <b>' + pol(s.paidWei) + ' POL</b> paid to members in the same transactions');
L.push('\u{1F4E3} Campaigns: <b>' + n(s.campaigns) + '</b> posted by ' + n(s.advertisers) + ' advertiser' + (s.advertisers === 1 ? '' : 's') + ' · ' + n(s.active) + ' running now · ' + n(s.imps) + ' ad impressions served');
L.push('\u{1F440} Earning: <b>' + n(s.viewers) + '</b> members viewed ads today · ' + n(s.seen24h) + ' signed in');
L.push('\u{1F3C1} So far: <b>' + n(s.members) + '</b> members · ' + n(s.wallets) + ' wallets linked · ' + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' purchases · <b>' + pol(s.lifePaidWei) + ' POL</b> paid out in ' + n(s.lifePayouts) + ' payouts, every one on the public ledger');
L.push('<a href="' + SITE_URL + '/ledger">Live ledger</a>' + (cta ? ' · <a href="' + cta + '">Join free</a>' : ''));
L.push('\u{1F3C1} So far: <b>' + n(s.members) + '</b> accounts · ' + n(s.wallets) + ' wallets linked · ' + n(s.payoutsOn) + ' with payouts on · ' + n(s.lifeBuys) + ' purchases · <b>' + pol(s.lifePaidWei) + ' POL</b> paid out in ' + n(s.lifePayouts) + ' payouts');
if (cta) L.push('\u{1F449} ' + cta);
return L.join('\n');
}
function targetMap(sc) {
return { feed: [sc.telegramChatId, sc.telegramTopicId], support: [sc.telegramSupportChatId, sc.telegramSupportTopicId], echo: [sc.telegramEchoChatId, sc.telegramEchoTopicId] };
}
async function post() {
const sc = X.siteConfig();
if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' };
const s = await gather(); const text = compose(s, sc.telegramCtaUrl);
const targets = String(sc.snapshotTargets || 'feed,echo').split(',').map(x => x.trim());
let sent = 0;
if (targets.includes('feed') && sc.telegramChatId) { if (await X.send(sc.telegramChatId, text, sc.telegramTopicId)) sent++; }
if (targets.includes('echo') && sc.telegramEchoChatId) { if (await X.send(sc.telegramEchoChatId, text, sc.telegramEchoTopicId)) sent++; }
const targets = String(sc.snapshotTargets || 'support').split(',').map(x => x.trim()).filter(Boolean);
const map = targetMap(sc); let sent = 0;
for (const name of targets) {
const t = map[name]; if (!t) continue;
if (!t[0]) { console.warn('snapshot: target "' + name + '" is listed but has no chat id, nothing sent'); continue; }
if (await X.send(t[0], text, t[1])) sent++;
}
const st = state(); st.lastPost = Date.now(); st.lastDay = new Date().toISOString().slice(0, 10); setState(st);
return { ok: true, sent, text };
}
// one destination by name, for a one-off post (admin: POST /api/admin/snapshot/send with {target})
async function postTo(name) {
const sc = X.siteConfig(); if (!sc.telegramBotToken) return { error: 'No Telegram bot token set.' };
const t = targetMap(sc)[name]; if (!t || !t[0]) return { error: 'No chat id for target ' + name + '.' };
const text = compose(await gather(), sc.telegramCtaUrl);
const ok = await X.send(t[0], text, t[1]); return { ok: !!ok, sent: ok ? 1 : 0, target: name, text };
}
// every 10 minutes: post once a day at or after snapshotHourUtc (a restart never double-posts)
async function tick() {
const sc = X.siteConfig();
if (String(sc.snapshotEnabled || '1') !== '1' || !sc.telegramBotToken) return;
if (String(sc.snapshotEnabled || '0') !== '1' || !sc.telegramBotToken) return;
const hour = Number(sc.snapshotHourUtc == null || sc.snapshotHourUtc === '' ? 14 : sc.snapshotHourUtc);
const now = new Date(); const day = now.toISOString().slice(0, 10);
if (now.getUTCHours() < hour) return;
@@ -87,4 +98,4 @@ async function tick() {
async function preview() { const sc = X.siteConfig(); return compose(await gather(), sc.telegramCtaUrl); }
module.exports = { init, gather, compose, post, tick, preview };
module.exports = { init, gather, compose, post, postTo, tick, preview };
+6 -1
View File
@@ -139,6 +139,11 @@ function adminAll() {
return { id: z.id, name: z.name, site: z.site, size: z.size, tier: tierOf(z), active: !!z.active, paused: !!z.adminPaused, note: z.adminNote || '', owner: z.owner, created: z.created,
views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(seen / imps.length * 100) : null, clicks30: imps.filter(i => i.k).length, offsite30: imps.filter(i => i.off).length, credits: z.credits || 0, status: st.state, statusLabel: st.label, lastSeen: last[z.id] || 0 }; });
}
// site-wide figures for the daily snapshot: real impressions inside the `since` window and new zones
function window24(since) {
const imps = J.db.imps.filter(i => i.ts >= since && !i.bot);
return { zones: J.db.zones.length, created: J.db.zones.filter(z => (z.created || 0) >= since).length, views: imps.length, viewable: imps.filter(i => i.ok).length };
}
function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; }
// -- publisher program totals (Reports screen + the public strip): the last N days, Central days, per day and per zone.
// "live" = switched on, not admin-paused, and seen by a real visitor inside the window. Credits are read from the pay log
@@ -164,4 +169,4 @@ function publisherPublic() {
rates: { viewsPerCredit: s.viewsPerCredit, nasViewsPerCredit: s.nasViewsPerCredit, nasViewsPerCreditVerified: s.nasViewsPerCreditVerified, capPerVisitorDay: s.capPerVisitorDay }, warmup: WARMUP, holdRatio: HOLD_RATIO, updated: Date.now() };
pubCache = { ts: Date.now(), data }; return data;
}
module.exports = { init, SIZES, NAS_SIZES, TIERS, WARMUP, HOLD_RATIO, settings, tierOf, rateFor, nasFrame, list, create, update, tag, serve, seen, click, totals, publisherTotals, publisherPublic, adminList, adminSet, adminAll };
module.exports = { init, SIZES, NAS_SIZES, TIERS, WARMUP, HOLD_RATIO, settings, tierOf, rateFor, nasFrame, list, create, update, tag, serve, seen, click, totals, window24, publisherTotals, publisherPublic, adminList, adminSet, adminAll };