Refill notices on LinkSpin (Fuel Your Offers stage 1, Marty approved 2026-10-24): refill.js copied from InstantAdPay. Low (80% of budget delivered, refillLowPct), out, and idle (7 days after an unanswered out notice, 100+ credits free, nothing running): one email + one on-site notice per owner per pass, naming each ad and what it delivered, then the relaunch line (100+ credits free) or the /credits link, then the packages from the chain catalog and a streak-line hook for stage 2. Email skips drip unsubscribes and carries the unsubscribe link; the notice (kind notice) always goes. Every send is watched 45 days for purchase / relaunch / resumed / topup. marks.js: one-time claims shared by both app copies during a deploy (event_marks with a DB, exclusive file create on the shared volume without one); every send is claimed first. Settings refillNotices '1' (default on) + refillLowPct 80; admin GET /api/admin/refill, POST /run and /reset, an Overview card (admin-refill.js). qa/refill.test.cjs (12 checks incl. two app copies on one volume) + run.sh fuel mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-24 05:11:12 -05:00
parent 7b3844b757
commit ab4f1693df
7 changed files with 523 additions and 1 deletions
+62
View File
@@ -0,0 +1,62 @@
// One-time claims shared by every running copy of the app (same idea as InstantAdPay's marks.js, 2026-10-24).
//
// Why: a Coolify deploy starts the new container and only stops the old one once the new one is healthy, so for
// about half a minute two copies of this app run side by side. Anything deduped in process memory or in a JSON
// file that each copy rewrites from its own memory can fire twice (InstantAdPay, 2026-09-25: two emails and a
// doubled Friday bonus). `claim(key)` is true for exactly one caller across all copies, false for everyone else.
//
// With a database: a row in event_marks that only one INSERT can win. Without one (LinkSpin production runs on
// the JSON store): an exclusive file create (open with 'wx') in DATA_DIR/marks/. Both copies mount the same
// volume, and O_EXCL creation is atomic on it, so exactly one copy gets the file. Marks older than 60 days are
// pruned: every event they guard has long since been handled.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let db = null, DIR = null;
const local = new Set();
function init(deps) {
db = deps && deps.db;
DIR = deps && deps.dataDir ? path.join(deps.dataDir, 'marks') : null;
if (DIR) { try { fs.mkdirSync(DIR, { recursive: true }); } catch (e) {} }
}
const dbOn = () => !!(db && db.enabled && db.enabled());
async function ensureTable() {
if (!dbOn()) return;
await db.q('CREATE TABLE IF NOT EXISTS event_marks (k VARCHAR(160) PRIMARY KEY, ts BIGINT NOT NULL) ENGINE=InnoDB');
}
const fileOf = key => path.join(DIR, crypto.createHash('sha1').update(key).digest('hex') + '.m');
// true = this caller owns the key; false = someone (possibly another copy of the app) already does.
async function claim(key) {
key = String(key).slice(0, 160);
if (dbOn()) {
try {
const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', [key, Date.now()]);
return !!(r && r.affectedRows === 1);
} catch (e) { console.error('marks: claim fell back to the file for ' + key + ': ' + e.message); }
}
if (DIR) {
try { const fd = fs.openSync(fileOf(key), 'wx'); try { fs.writeSync(fd, key + '\n' + Date.now()); } finally { fs.closeSync(fd); } return true; }
catch (e) { if (e.code === 'EEXIST') return false; console.error('marks: file claim failed for ' + key + ': ' + e.message); }
}
if (local.has(key)) return false; local.add(key); return true;
}
// whether a key was already claimed (read only, never claims)
async function has(key) {
key = String(key).slice(0, 160);
if (dbOn()) { try { const r = await db.q('SELECT 1 FROM event_marks WHERE k=?', [key]); return r.length > 0; } catch (e) {} }
if (DIR) return fs.existsSync(fileOf(key));
return local.has(key);
}
async function prune() {
const cut = Date.now() - 60 * 86400000;
if (dbOn()) { try { await db.q('DELETE FROM event_marks WHERE ts < ?', [cut]); } catch (e) {} }
if (DIR) { try { for (const f of fs.readdirSync(DIR)) { const p = path.join(DIR, f); try { if (fs.statSync(p).mtimeMs < cut) fs.unlinkSync(p); } catch (e) {} } } catch (e) {} }
}
module.exports = { init, ensureTable, claim, has, prune };
+6 -1
View File
@@ -90,6 +90,11 @@
<div id="ovChain" class="small">…</div>
</div>
</div>
<div class="card">
<div class="card-head"><h3>Refill notices</h3><span class="sub" id="rfSub">low, out and idle ads: one message per owner</span></div>
<div id="rfBox" class="small muted">&hellip;</div>
<p style="margin:10px 0 0"><button class="btn small sec" id="rfRun" type="button">Send the next batch now</button></p>
</div>
<div class="card">
<div class="card-head"><h3>Quick actions</h3></div>
<p style="display:flex;gap:10px;flex-wrap:wrap;margin:0">
@@ -519,6 +524,6 @@
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
<script src="/assets/admin.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
// Admin > Overview > Refill notices (2026-10-24): who was told their ads ran low, ran out or sat idle, and what they did next.
(function () {
const $ = id => document.getElementById(id);
if (!$('rfBox')) return;
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const ct = ts => new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT';
const STATE = { low: 'running low', out: 'out of credits', idle: 'idle a week' };
async function load() {
try {
const r = await (await fetch('/api/admin/refill', { cache: 'no-store' })).json();
if (r.error) throw new Error(r.error);
const t = r.totals || {};
$('rfSub').textContent = (r.enabled ? 'on' : 'OFF (site setting refillNotices)') + ', low at ' + r.lowPct + '% delivered';
const st = Object.entries(r.byState || {}).map(([k, v]) => esc(STATE[k] || k) + ': ' + v.sent + ' sent, ' + v.converted + ' acted').join(' &middot; ');
const kinds = Object.entries(r.byKind || {}).map(([k, v]) => esc(k) + ' ' + v).join(', ');
$('rfBox').innerHTML = '<p class="small" style="margin:0 0 8px"><b>' + (t.sent || 0) + '</b> sent (' + (t.emailed || 0) + ' emailed), <b>' + (t.converted || 0) + '</b> acted on it (' + (t.ratePct || 0) + '%)'
+ (t.purchasesUsd ? ', $' + t.purchasesUsd + ' in packages after a notice' : '') + (t.medianHours != null ? ', median ' + t.medianHours + ' h' : '') + '</p>'
+ '<p class="small muted" style="margin:0 0 8px">' + st + (kinds ? '<br>' + kinds : '') + '</p>'
+ ((r.recent || []).length ? '<div class="tbl-wrap"><table class="tbl small"><tr><th>When</th><th>Owner</th><th>State</th><th>Ads</th><th>Credits then</th><th>Next</th></tr>'
+ r.recent.slice(0, 20).map(x => '<tr><td>' + esc(ct(x.at)) + '</td><td>' + esc(x.owner) + '</td><td>' + esc(STATE[x.state] || x.state) + (x.emailed ? '' : ' <span class="muted">(on-site only)</span>') + '</td><td>' + esc((x.names || []).join(', ')) + '</td><td>' + Number(x.credits || 0).toLocaleString() + '</td><td>' + (x.converted ? esc(x.converted.kind) + ' after ' + x.converted.hours + ' h' : '<span class="muted">nothing yet</span>') + '</td></tr>').join('') + '</table></div>' : '<p class="small muted">Nothing sent yet.</p>');
} catch (e) { $('rfBox').textContent = 'Could not load: ' + e.message; }
}
$('rfRun') && $('rfRun').addEventListener('click', async () => {
$('rfRun').disabled = true;
try { const r = await (await fetch('/api/admin/refill/run', { method: 'POST', cache: 'no-store' })).json(); $('rfSub').textContent = 'pass done: ' + (r.sent || 0) + ' sent'; } catch (e) {}
$('rfRun').disabled = false; load();
});
load();
})();
+123
View File
@@ -0,0 +1,123 @@
// Refill notices (refill.js) on throwaway data: stubbed ads/accounts/chain/mail, a temp DATA_DIR, file marks.
// Run: node qa/refill.test.cjs
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
const ROOT = path.join(__dirname, '..');
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-refill-'));
let fails = 0, n = 0;
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } }
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
const now = Date.now();
function world() {
const W = {
campaigns: [
{ id: 1, owner: 'a@x.test', type: 'banner', name: 'Alpha banner', budget: 1000, spent: 850, imps: 4000, clicks: 30, status: 'active', created: now - 20 * 864e5 },
{ id: 2, owner: 'a@x.test', type: 'text', name: 'Alpha text', budget: 500, spent: 500, imps: 5000, clicks: 12, status: 'out', created: now - 20 * 864e5 },
{ id: 3, owner: 'b@x.test', type: 'banner', name: 'Bravo', budget: 2500, spent: 2500, imps: 12000, clicks: 80, status: 'out', created: now - 20 * 864e5 },
{ id: 4, owner: 'house@linkspin', house: true, type: 'banner', name: 'House', budget: 100, spent: 100, status: 'out', created: now },
{ id: 5, owner: 'c@x.test', type: 'banner', name: 'Charlie', budget: 1000, spent: 100, status: 'active', created: now },
],
credits: { 'a@x.test': 40, 'b@x.test': 1200, 'c@x.test': 0 },
unsub: new Set(['b@x.test']),
inbox: [], mail: [], events: [],
};
W.deps = {
dataDir: DIR, siteUrl: 'https://linkspin.app', houseOwner: 'house@linkspin',
siteConfig: () => W.cfg || {},
ads: { adminList: async () => W.campaigns.map(c => Object.assign({}, c)) },
accounts: { byEmail: async e => ({ email: e, memberId: { 'a@x.test': 11, 'b@x.test': 12, 'c@x.test': 13 }[e] || 0 }), positions: async () => [] },
chain: { recentEvents: () => W.events, catalog: async () => [{ priceCents: 1000, creditAmount: 1000 }, { priceCents: 2500, creditAmount: 2500 }] },
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
drip: { isUnsubscribed: async e => W.unsub.has(e), unsubUrl: e => 'https://linkspin.app/unsubscribe?e=' + e },
creditsFor: async e => W.credits[e] || 0,
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
};
return W;
}
(async () => {
const marks = fresh('marks.js'); marks.init({ dataDir: DIR });
let W = world();
const refill = fresh('refill.js');
refill.init(Object.assign({ marks }, W.deps));
await t('one message per owner per pass; out beats low; house and healthy ads skipped', async () => {
const r = await refill.tick();
assert.strictEqual(r.sent, 2);
assert.deepStrictEqual(W.inbox.map(x => x.to).sort(), ['a@x.test', 'b@x.test']);
const a = W.inbox.find(x => x.to === 'a@x.test');
assert.ok(/finished delivering/.test(a.subject), a.subject);
assert.ok(/Alpha text/.test(a.html) && !/Alpha banner/.test(a.html), 'only the out campaign in the out notice');
});
await t('email respects unsubscribes; the on-site notice still goes', async () => {
assert.ok(W.inbox.some(x => x.to === 'b@x.test'));
assert.ok(!W.mail.some(x => x.to === 'b@x.test'));
const m = W.mail.find(x => x.to === 'a@x.test');
assert.ok(m && /Stop these emails/.test(m.text));
});
await t('relaunch line with 100+ credits, buy link below', async () => {
const b = W.inbox.find(x => x.to === 'b@x.test'); assert.ok(/without buying anything/.test(b.html) && /linkspin\.app\/ads/.test(b.html));
const a = W.mail.find(x => x.to === 'a@x.test'); assert.ok(/needs a package first/.test(a.text) && /linkspin\.app\/credits/.test(a.text));
});
await t('campaign lines say what each delivered; packages from the catalog', async () => {
const a = W.mail.find(x => x.to === 'a@x.test');
assert.ok(/"Alpha text" \(text\): 500 of 500 credits delivered, 5,000 impressions, 12 clicks/.test(a.text), a.text);
assert.ok(/\$25 {2}-> {2}2,500 credits/.test(a.text));
});
await t('no em dashes, no income promises', async () => {
for (const m of W.mail.concat(W.inbox)) { const s = (m.text || m.html) + m.subject; assert.ok(!/—/.test(s), 'em dash'); assert.ok(!/(earn|make) (money|\$)|guarantee/i.test(s), 'income claim'); }
});
await t('next pass: the low notice for the other ad, then nothing', async () => {
const r = await refill.tick(); assert.strictEqual(r.sent, 1);
assert.ok(/nearly out/.test(W.inbox[W.inbox.length - 1].subject));
const r2 = await refill.tick(); assert.strictEqual(r2.sent, 0);
});
await t('settings switch off: nothing sent', async () => {
W.cfg = { refillNotices: '0' }; W.campaigns.push({ id: 6, owner: 'c@x.test', type: 'banner', name: 'Charlie 2', budget: 100, spent: 100, status: 'out', created: now });
const r = await refill.tick(); assert.strictEqual(r.sent, 0); W.cfg = {};
});
await t('conversion: a purchase after the send', async () => {
W.events.push({ type: 'Purchase', buyerId: 12, priceCents: 2500, tx: '0xbuy', ts: Date.now() + 1000 });
await refill.tick();
const s = refill.stats(); const b = s.recent.find(x => x.owner === 'b@x.test');
assert.ok(b.converted && b.converted.kind === 'purchase', JSON.stringify(b));
assert.strictEqual(s.totals.purchasesUsd, 25);
});
await t('idle follow-up after 7 days, once, only with 100+ credits and nothing running', async () => {
// a's out record: make it 8 days old, give a credits, stop a's running ad
const f = path.join(DIR, 'refill.json'); const S = JSON.parse(fs.readFileSync(f, 'utf8'));
for (const r of Object.values(S.records)) if (r.owner === 'a@x.test' && r.state === 'out') r.ts = Date.now() - 8 * 864e5;
fs.writeFileSync(f, JSON.stringify(S));
W.credits['a@x.test'] = 700; W.campaigns.find(c => c.id === 1).status = 'paused';
const before = W.inbox.length; await refill.tick();
const idle = W.inbox.slice(before).filter(x => x.to === 'a@x.test');
assert.strictEqual(idle.length, 1); assert.ok(/700 credits are sitting idle/.test(idle[0].subject));
const b2 = W.inbox.length; await refill.tick(); assert.strictEqual(W.inbox.length, b2);
});
await t('admin stats', async () => {
const s = refill.stats(); assert.ok(s.enabled); assert.ok(s.byState.idle.sent === 1); assert.ok(s.totals.sent >= 4);
});
await t('streak hook line lands in the bonus block', async () => {
const r2 = fresh('refill.js'); r2.init(Object.assign({}, W.deps, { streakLine: async () => ({ text: 'Refuel streak: month 2.', html: '<b>Refuel streak</b>: month 2.' }) }));
const m = await r2.compose('a@x.test', [W.campaigns[0]], 'low', 50);
assert.ok(/Refuel streak: month 2\./.test(m.text) && /Refuel streak<\/b>/.test(m.html));
});
await t('two app copies on one volume: one message, not two', async () => {
const D2 = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-refill2-'));
const W2 = world(); W2.deps.dataDir = D2;
const mk = () => { const m = fresh('marks.js'); m.init({ dataDir: D2 }); const r = fresh('refill.js'); r.init(Object.assign({}, W2.deps, { marks: m })); return r; };
const A = mk(), B = mk();
await Promise.all([A.tick(), B.tick()]);
const per = {}; for (const x of W2.inbox) per[x.to] = (per[x.to] || 0) + 1;
assert.deepStrictEqual(per, { 'a@x.test': 1, 'b@x.test': 1 }, JSON.stringify(per));
assert.strictEqual(W2.mail.length, 1);
});
console.log('\n' + (n - fails) + '/' + n + ' passed');
try { fs.rmSync(DIR, { recursive: true, force: true }); } catch (e) {}
process.exit(fails ? 1 : 0);
})();
+3
View File
@@ -10,6 +10,7 @@
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data)
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u
@@ -33,6 +34,8 @@ stop_local() { # $1 = port
if [ "$MODE" = "public" ]; then
node qa/walk.mjs public || status=1
elif [ "$MODE" = "fuel" ]; then
for f in qa/refill.test.cjs qa/refuel*.test.cjs; do [ -f "$f" ] && { node "$f" || status=1; }; done
elif [ "$MODE" = "override" ]; then
node qa/override.test.cjs || status=1
elif [ "$MODE" = "member" ]; then
+274
View File
@@ -0,0 +1,274 @@
// 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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
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 };
+26
View File
@@ -64,6 +64,8 @@ const rotator = require('./rotator');
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
const refill = require('./refill'); // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
@@ -599,6 +601,9 @@ async function editAd(id, b, who) {
}
async function boot() {
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
marks.init({ db, dataDir: DATA_DIR });
marks.ensureTable().catch(e => console.error('marks table', e.message));
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {});
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {}); } });
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
@@ -624,6 +629,13 @@ async function boot() {
try { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [c.owner], subject, html, 'notice'); } catch (e) { console.error('login queue notice', e.message); }
try { if (mailer.hasKey() && !(await drip.isUnsubscribed(c.owner))) await mailer.send(c.owner, subject, text + '\n\nStop these emails: ' + drip.unsubUrl(c.owner) + '\n\nLinkSpin'); } catch (e) { console.error('login queue email', e.message); }
});
// campaign refill notices (2026-10-24, copied from InstantAdPay): told when an ad is nearly out, when it stops, and once more
// a week later if credits sit idle; one email + one on-site notice per owner, every send watched for what they did next
refill.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, siteUrl: SITE_URL, houseOwner: ads.HOUSE_OWNER,
creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; },
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
// follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot)
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig });
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
@@ -754,6 +766,7 @@ function siteConfig() {
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
pnlFixedMonthlyUsd: 0,
refillNotices: '1', refillLowPct: 80, // refill notices (2026-10-24): '0' turns them off; the share of a budget delivered that counts as running low
campaignEditFee: 100 // credits per ad edit after each campaign's first, free one (Orlando's ask, 2026-10-18); 0 = edits always free
}, saved);
}
@@ -3803,6 +3816,19 @@ const server = http.createServer(async (req, res) => {
passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length },
wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() });
}
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran low or out, and what they did next
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, refill.stats());
}
if (p === '/api/admin/refill/reset' && req.method === 'POST') { // re-decide conversions under a corrected rule
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req);
return json(res, 200, refill.resetConversions(Array.isArray(b.kinds) ? b.kinds : null));
}
if (p === '/api/admin/refill/run' && req.method === 'POST') { // send the next batch now instead of waiting for the tick
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await refill.tick());
}
if (p === '/api/admin/burner' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, burner.status());