ab4f1693df
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
275 lines
16 KiB
JavaScript
275 lines
16 KiB
JavaScript
// Campaign refill notices on LinkSpin (Marty approved the Fuel Your Offers build, 2026-10-24). Copied from InstantAdPay's
|
|
// refill.js: until now a LinkSpin ad that spent its budget simply went dark, and the only sign was the "Running low" /
|
|
// "Out of credits" light on the Ads screen, which nobody sees unless they open it.
|
|
//
|
|
// Three moments, ONE email + ONE on-site notice per owner per pass (never one per campaign):
|
|
// low an active campaign past refillLowPct (80%) of its budget delivered
|
|
// out a campaign at status 'out'
|
|
// idle 7 days after an unanswered 'out' notice, the owner still holds 100+ credits and has nothing running
|
|
// Each message names every ad and what it delivered, then either "relaunch now, no purchase needed" (100+ credits
|
|
// free) or the buy link, then the packages. Email skips anyone who unsubscribed (drip); the on-site notice always goes.
|
|
//
|
|
// Every send is recorded and watched for 45 days for what the owner did next: a package bought on any of their
|
|
// positions (purchase), a campaign created after the send (relaunch), a named stopped ad back to active (resumed),
|
|
// a named ad's budget raised (topup). That is the conversion history in DATA_DIR/refill.json.
|
|
//
|
|
// Deploy overlap: two copies of the app run for ~30 s on each deploy. Every send is claimed first (marks.js:
|
|
// event_marks in MySQL, or an exclusive file on the shared volume), so only one copy writes to a person.
|
|
//
|
|
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80).
|
|
// Hook: X.streakLine(owner) -> { text, html } | null adds the member's refuel-streak line to the bonus block (stage 2).
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
let X = {}, FILE = null, S = null;
|
|
const DAY = 86400000;
|
|
const LOOKBACK = 45 * DAY;
|
|
const MAX_PER_TICK = 25;
|
|
const IDLE_AFTER = 7 * DAY;
|
|
const IDLE_MIN_CREDITS = 100;
|
|
// LinkSpin packages when the chain catalog cannot be read (one credit = one cent: 100 credits per dollar on every size)
|
|
const FALLBACK_PACKS = [10, 25, 50, 100, 250, 500].map(p => ({ price: p, credits: p * 100 }));
|
|
|
|
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'refill.json'); S = load(); }
|
|
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.sent = s.sent || {}; s.records = s.records || {}; s.seq = s.seq || 0; return s; } catch (e) { return { sent: {}, records: {}, seq: 0 }; } }
|
|
function save() { try { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(S)); fs.renameSync(tmp, FILE); } catch (e) {} }
|
|
|
|
function cfg() {
|
|
const c = (X.siteConfig && X.siteConfig()) || {};
|
|
return {
|
|
on: String(c.refillNotices == null ? '1' : c.refillNotices) === '1',
|
|
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
|
|
};
|
|
}
|
|
const SITE = () => String(X.siteUrl || 'https://linkspin.app').replace(/\/+$/, '');
|
|
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : 0);
|
|
const money = n => Number(n || 0).toLocaleString('en-US');
|
|
// LinkSpin's admin list (ads.pubC) already folds accrued into spent
|
|
const delivered = c => n0(c.spent);
|
|
const unit = c => c.type === 'video' ? 'watches' : 'impressions';
|
|
const key = (id, state) => id + ':' + state;
|
|
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
const nameOf = c => c.name || c.title || ('campaign #' + c.id);
|
|
|
|
// the packages, from the chain catalog (cached an hour), so the list is never hand-typed
|
|
let packCache = { at: 0, list: null };
|
|
async function packs() {
|
|
if (packCache.list && Date.now() - packCache.at < 3600000) return packCache.list;
|
|
let list = null;
|
|
try {
|
|
const cat = X.chain && X.chain.catalog ? await X.chain.catalog() : null;
|
|
const rows = (cat && (cat.products || cat)) || [];
|
|
list = rows.filter(p => p && p.priceCents > 0 && p.creditAmount > 0).map(p => ({ price: p.priceCents / 100, credits: Number(p.creditAmount) }))
|
|
.sort((a, b) => a.price - b.price);
|
|
} catch (e) { list = null; }
|
|
if (!list || !list.length) list = FALLBACK_PACKS;
|
|
packCache = { at: Date.now(), list };
|
|
return list;
|
|
}
|
|
|
|
async function streakLine(owner) {
|
|
if (typeof X.streakLine !== 'function') return null;
|
|
try { return await X.streakLine(owner); } catch (e) { return null; }
|
|
}
|
|
async function ladderText(owner) {
|
|
const rows = (await packs()).map(p => ' $' + money(p.price) + ' -> ' + money(p.credits) + ' credits');
|
|
const sl = await streakLine(owner);
|
|
return 'LinkSpin packages, and what each one adds to your balance:\n\n' + rows.join('\n')
|
|
+ '\n\nA credit is one cent of ad delivery. Packages of $25 and up also unlock Banner Spin.'
|
|
+ (sl && sl.text ? '\n\n' + sl.text : '');
|
|
}
|
|
async function ladderHtml(owner) {
|
|
const rows = (await packs()).map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + money(p.price) + '</b></td><td style="padding:6px 0">' + money(p.credits) + ' credits</td></tr>').join('');
|
|
const sl = await streakLine(owner);
|
|
return '<p><b>LinkSpin packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
|
|
+ '<p style="color:#556">A credit is one cent of ad delivery. Packages of $25 and up also unlock Banner Spin.</p>'
|
|
+ (sl && sl.html ? '<p>' + sl.html + '</p>' : '');
|
|
}
|
|
|
|
function lineOf(c) {
|
|
const bits = [money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'];
|
|
if (n0(c.imps)) bits.push(money(n0(c.imps)) + ' ' + unit(c));
|
|
if (n0(c.clicks)) bits.push(money(n0(c.clicks)) + ' clicks');
|
|
return { name: nameOf(c), type: c.type || 'ad', bits };
|
|
}
|
|
|
|
async function compose(owner, list, state, credits) {
|
|
const many = list.length > 1;
|
|
const first = nameOf(list[0]);
|
|
const totalImps = list.reduce((n, c) => n + n0(c.imps), 0);
|
|
const totalClicks = list.reduce((n, c) => n + n0(c.clicks), 0);
|
|
const canRelaunch = credits >= IDLE_MIN_CREDITS;
|
|
const subject = state === 'idle' ? money(Math.round(credits)) + ' credits are sitting idle on your LinkSpin account'
|
|
: state === 'out' ? (many ? 'Your LinkSpin ads have finished delivering' : 'Your LinkSpin ad "' + first + '" has finished delivering')
|
|
: (many ? 'Your LinkSpin ads are nearly out of credits' : 'Your LinkSpin ad "' + first + '" is nearly out of credits');
|
|
const opener = state === 'idle'
|
|
? 'A week ago ' + (many ? 'your ads' : 'your ad "' + first + '"') + ' finished delivering, and nothing has run since. Your credits are still there, and nobody is seeing your link while they sit.'
|
|
: state === 'out'
|
|
? (many ? 'Your ' + list.length + ' campaigns have spent their full budget and stopped. They delivered everything you paid for.' : 'That campaign spent its full budget and stopped. It delivered everything you paid for.')
|
|
: (many ? 'Your ' + list.length + ' campaigns are close to spending their full budget. When they do, they stop.' : 'That campaign is close to spending its full budget. When it does, it stops.');
|
|
const totals = (totalImps || totalClicks) ? 'Between them so far: ' + money(totalImps) + (list.every(c => c.type === 'video') ? ' watches' : ' impressions') + ' and ' + money(totalClicks) + ' clicks.' : '';
|
|
const adsUrl = SITE() + '/ads', buyUrl = SITE() + '/credits';
|
|
const next = state === 'idle'
|
|
? money(Math.round(credits)) + ' credits are ready to run. A banner or text ad takes a minute to set up and starts showing the moment you launch it, no purchase needed: ' + adsUrl
|
|
: canRelaunch
|
|
? 'You still have ' + money(Math.round(credits)) + ' credits free, which is enough to put an ad back up right now without buying anything. Open Ads and start one: ' + adsUrl
|
|
: 'Your free balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a package first: ' + buyUrl;
|
|
const lines = list.map(lineOf);
|
|
const ladderT = await ladderText(owner), ladderH = await ladderHtml(owner);
|
|
const tail = 'Every package pays your sponsor line in the same on-chain transaction. Ad credits buy delivery only.';
|
|
const text = [opener, totals, next].filter(Boolean).join('\n\n')
|
|
+ '\n\nWhat each one did:\n' + lines.map(l => ' "' + l.name + '" (' + l.type + '): ' + l.bits.join(', ')).join('\n')
|
|
+ '\n\n' + ladderT + '\n\n' + tail;
|
|
const html = '<p>' + esc(opener) + '</p>' + (totals ? '<p>' + esc(totals) + '</p>' : '')
|
|
+ '<p>' + esc(next).replace(/(https:\/\/[^\s]+)/g, '<a href="$1">$1</a>') + '</p>'
|
|
+ '<p><b>What each one did:</b></p><ul>' + lines.map(l => '<li>' + esc(l.name) + ' (' + esc(l.type) + '): ' + esc(l.bits.join(', ')) + '</li>').join('') + '</ul>'
|
|
+ ladderH + '<p style="color:#556">' + tail + '</p>';
|
|
return { subject, text, html };
|
|
}
|
|
|
|
// ---- the pass -------------------------------------------------------------------------------
|
|
let running = false;
|
|
async function tick() {
|
|
if (running || !cfg().on) return { sent: 0 };
|
|
running = true;
|
|
try {
|
|
S = load(); // the other copy of the app may have written since we last looked
|
|
const c = cfg();
|
|
const all = await X.ads.adminList(5000);
|
|
const mine = all.filter(x => !x.house && x.owner && x.owner !== X.houseOwner && x.type !== 'game');
|
|
const due = new Map();
|
|
for (const cm of mine) {
|
|
const b = n0(cm.budget); if (b <= 0) continue;
|
|
let state = null;
|
|
if (cm.status === 'out') state = 'out';
|
|
else if (cm.status === 'active' && delivered(cm) >= b * (c.lowPct / 100)) state = 'low';
|
|
if (!state) continue;
|
|
if (S.sent[key(cm.id, state)]) continue;
|
|
if (state === 'low' && S.sent[key(cm.id, 'out')]) continue;
|
|
const g = due.get(cm.owner) || {}; (g[state] = g[state] || []).push(cm); due.set(cm.owner, g);
|
|
}
|
|
let sent = 0;
|
|
for (const [owner, byState] of due) {
|
|
if (sent >= MAX_PER_TICK) break;
|
|
for (const state of ['out', 'low']) {
|
|
const list = byState[state]; if (!list || !list.length) continue;
|
|
const ok = await notify(owner, list, state).catch(e => { console.error('refill notify', e.message); return false; });
|
|
if (ok) sent++;
|
|
break; // one state per owner per pass: "out" is the louder message
|
|
}
|
|
}
|
|
await checkConversions(all);
|
|
sent += await followUps(all, sent);
|
|
save();
|
|
if (sent) console.log('refill notices sent:', sent);
|
|
return { sent };
|
|
} finally { running = false; }
|
|
}
|
|
|
|
async function followUps(all, alreadySent) {
|
|
const now = Date.now(); let sent = 0;
|
|
const due = Object.values(S.records).filter(r => r.state === 'out' && !r.converted && !r.followUp && now - r.ts >= IDLE_AFTER && now - r.ts < LOOKBACK);
|
|
for (const r of due) {
|
|
if (alreadySent + sent >= MAX_PER_TICK) break;
|
|
const live = all.some(c => c.owner === r.owner && !c.house && c.status === 'active');
|
|
if (live) { r.followUp = 'running'; continue; }
|
|
let credits = 0; try { credits = await X.creditsFor(r.owner); } catch (e) {}
|
|
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
|
|
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
|
|
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', e.message); return false; });
|
|
r.followUp = ok ? S.seq : 'claimed';
|
|
if (ok) sent++;
|
|
}
|
|
return sent;
|
|
}
|
|
|
|
async function notify(owner, list, state, parentId) {
|
|
// claim before anything goes out: one copy of the app per message, ever
|
|
const claimKey = 'refill:' + (state === 'idle' ? 'idle:' + parentId : list.map(c => c.id).sort((a, b) => a - b).join(',') + ':' + state);
|
|
const mine = X.marks ? await X.marks.claim(claimKey) : true;
|
|
if (!mine) { if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = S.sent[key(cm.id, state)] || -1; return false; }
|
|
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
|
|
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
|
|
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
|
|
const m = await compose(owner, list, state, credits);
|
|
try { await X.message(owner, m.subject, m.html); } catch (e) { console.error('refill inbox', e.message); }
|
|
const canMail = !stopped && X.mailer && X.mailer.hasKey();
|
|
if (canMail) {
|
|
const foot = X.drip && X.drip.unsubUrl ? '\n\nStop these emails: ' + X.drip.unsubUrl(owner) : '';
|
|
try { await X.mailer.send(owner, m.subject, m.text + foot + '\n\nLinkSpin'); } catch (e) { console.error('refill mail', e.message); }
|
|
}
|
|
const rec = {
|
|
id: ++S.seq, owner, state, ts: Date.now(), emailed: !!canMail, unsubscribed: !!stopped,
|
|
campaigns: list.map(c => ({ id: c.id, name: c.name || null, type: c.type || null, budget: Math.round(n0(c.budget)), delivered: Math.round(delivered(c)), imps: n0(c.imps), clicks: n0(c.clicks) })),
|
|
creditsAtSend: Math.round(credits), memberId: acct.memberId || 0, converted: null, parent: parentId || null,
|
|
};
|
|
if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = rec.id;
|
|
S.records[rec.id] = rec;
|
|
save();
|
|
return true;
|
|
}
|
|
|
|
// ---- did anything come of it? ---------------------------------------------------------------
|
|
async function checkConversions(allIn) {
|
|
const open = Object.values(S.records).filter(r => !r.converted && Date.now() - r.ts < LOOKBACK);
|
|
if (!open.length) return;
|
|
const all = allIn || await X.ads.adminList(5000);
|
|
const evs = (X.chain.recentEvents(1e9) || []).filter(e => e.type === 'Purchase');
|
|
for (const r of open) {
|
|
const since = r.ts;
|
|
let ids = [r.memberId].filter(Boolean);
|
|
try { const ps = await X.accounts.positions(r.owner); ids = [...new Set([...ids, ...ps.map(p => p.memberId).filter(Boolean)])]; } catch (e) {}
|
|
const buy = evs.find(e => ids.includes(Number(e.buyerId)) && norm(e) > since);
|
|
if (buy) { mark(r, 'purchase', { cents: n0(buy.priceCents), tx: buy.tx || null }); continue; }
|
|
const fresh = all.find(c => c.owner === r.owner && !c.house && n0(c.created) > since);
|
|
if (fresh) { mark(r, 'relaunch', { campaignId: fresh.id, name: fresh.name || null }); continue; }
|
|
if (r.state === 'out' || r.state === 'idle') {
|
|
const revived = all.find(c => c.status === 'active' && r.campaigns.some(x => x.id === c.id) && delivered(c) < n0(c.budget));
|
|
if (revived) { mark(r, 'resumed', { campaignId: revived.id, name: revived.name || null }); continue; }
|
|
}
|
|
const topped = all.find(c => { const was = r.campaigns.find(x => x.id === c.id); return was && n0(c.budget) > was.budget; });
|
|
if (topped) mark(r, 'topup', { campaignId: topped.id, added: Math.round(n0(topped.budget) - r.campaigns.find(x => x.id === topped.id).budget) });
|
|
}
|
|
}
|
|
const norm = e => { let t = n0(e.ts); if (t < 1e12) t *= 1000; return t; };
|
|
function mark(r, kind, detail) {
|
|
r.converted = { kind, at: Date.now(), hours: Math.round((Date.now() - r.ts) / 3600000), detail: detail || null };
|
|
console.log('refill converted:', kind, 'after', r.converted.hours + 'h');
|
|
}
|
|
|
|
// ---- what the admin sees --------------------------------------------------------------------
|
|
function stats() {
|
|
S = load();
|
|
const recs = Object.values(S.records).sort((a, b) => b.ts - a.ts);
|
|
const by = { out: { sent: 0, converted: 0 }, low: { sent: 0, converted: 0 }, idle: { sent: 0, converted: 0 } };
|
|
const kinds = {}; let revenueCents = 0; const hours = [];
|
|
for (const r of recs) {
|
|
const b = by[r.state] || (by[r.state] = { sent: 0, converted: 0 });
|
|
b.sent++;
|
|
if (r.converted) {
|
|
b.converted++; kinds[r.converted.kind] = (kinds[r.converted.kind] || 0) + 1; hours.push(r.converted.hours);
|
|
if (r.converted.kind === 'purchase') revenueCents += n0(r.converted.detail && r.converted.detail.cents);
|
|
}
|
|
}
|
|
const conv = recs.filter(r => r.converted).length;
|
|
return {
|
|
enabled: cfg().on, lowPct: cfg().lowPct,
|
|
totals: { sent: recs.length, emailed: recs.filter(r => r.emailed).length, converted: conv, ratePct: recs.length ? Math.round(conv / recs.length * 100) : 0,
|
|
purchasesUsd: Math.round(revenueCents / 100), medianHours: hours.length ? hours.sort((a, b) => a - b)[Math.floor(hours.length / 2)] : null },
|
|
byState: by, byKind: kinds,
|
|
recent: recs.slice(0, 60).map(r => ({ id: r.id, owner: r.owner, state: r.state, at: r.ts, emailed: r.emailed, credits: r.creditsAtSend,
|
|
campaigns: r.campaigns.length, names: r.campaigns.map(c => c.name || ('#' + c.id)).slice(0, 4), imps: r.campaigns.reduce((n, c) => n + c.imps, 0), converted: r.converted })),
|
|
};
|
|
}
|
|
function resetConversions(kinds) {
|
|
S = load();
|
|
const want = new Set(kinds && kinds.length ? kinds : ['relaunch']);
|
|
let n = 0;
|
|
for (const r of Object.values(S.records)) if (r.converted && want.has(r.converted.kind)) { r.converted = null; n++; }
|
|
save();
|
|
return { cleared: n };
|
|
}
|
|
|
|
module.exports = { init, tick, stats, resetConversions, compose, _packs: packs };
|