Files
instantadpay/refuel.js

415 lines
32 KiB
JavaScript

// The Monthly Refuel streak (Fuel Your Offers, Marty approved the build 2026-10-24; rules decided 2026-10-23).
// ONE streak per member across InstantAdPay and LinkSpin, kept HERE (InstantAdPay is the source of truth). LinkSpin
// reports its purchases through a signed partner call and collects its own grants and reminders from the outbox.
//
// THE RULES
// counted refuel a NEW on-chain package of $20+ on InstantAdPay (refuelMinIapCents) or $25+ on LinkSpin
// (refuelMinLsCents), bought by one of the member's own positions
// refuel day the first counted refuel starts the streak; the next is due 30 days after the last counted
// refuel (Central-time calendar days). The window opens 5 days before the due day and closes at
// the end of a 5-day grace after it. A purchase before the window is a Pit Stop, not a refuel.
// missing the grace passes with no refuel: the streak resets, unless the member's one free miss per
// 365 days covers it (the streak is kept, the month does not count, and the very next qualifying
// package counts as the next refuel)
// streak bonus purchased-grade credits on the site where bought, credit log labelled "Refuel streak":
// one engine m1 +10% m2 +15% m3 +20% m4+ +25%
// both m1 +15% m2 +20% m3 +30% m4+ +40% (+ a 100-credit Featured bonus on InstantAdPay at m4+, Marty 2026-10-24)
// both engines the other site's first qualifying package in the same cycle (any time before the next window)
// gets the both-rate, and the first site's bonus is topped up to the both-rate (difference only)
// stacking separate grants: Five Dollar Friday and Wired Wednesday still add their own on the same package
// Pit Stop a qualifying package between refuel days gets half the current streak rate, once per site per
// cycle; it is not a counted refuel
// badges 3, 6 and 12 months in a row: the InstantAdPay badge posts (one time each, like every badge)
// reminders 5 days before the refuel day, on the day, and a last call at the end of the grace: email +
// on-site notice from the site of the member's last counted refuel, from refuelReminderHour (CT)
// Refuel Day optional network bonus on the 1st of the month (refuelDayPromo, default OFF): +refuelDayPct
// on a counted refuel bought that day
// MASTER SWITCH: site setting refuelStreak (default '0'). Off: nothing is counted or granted, no reminders, the
// cards report { on:false } and stay hidden. Purchases made while it is off are never counted later.
//
// ONCE, EVERYWHERE: every purchase is decided inside a lock on the member (MySQL GET_LOCK across app copies) and
// stored by tx, so a repeat call returns the same decision. Every grant is an outbox row keyed by a unique ref
// (rf:<site>:<tx>, rftop:<site>:<tx>, rfpit:<site>:<tx>, rfday:<site>:<tx>, rffeat:<email>:<cycle>); the site
// that applies it claims 'rfg:<ref>' first (marks.js), so two copies of either app never double-grant.
'use strict';
const fs = require('fs');
const path = require('path');
let X = {}, FILE = null;
const TZ = 'America/Chicago';
const SITE = 'https://instantadpay.com';
const LS_SITE = 'https://linkspin.app';
const SINGLE = [10, 15, 20, 25];
const BOTH = [15, 20, 30, 40];
const CYCLE_DAYS = 30, EARLY_DAYS = 5, GRACE_DAYS = 5, FREE_MISS_DAYS = 365;
const BADGE_AT = [3, 6, 12];
const NAME = { iap: 'InstantAdPay', linkspin: 'LinkSpin' };
// ---- Central-time calendar days -----------------------------------------------------------------
const ctDay = ts => new Date(ts === undefined ? Date.now() : ts).toLocaleDateString('en-CA', { timeZone: TZ });
const ctHour = ts => Number(new Date(ts === undefined ? Date.now() : ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false })) % 24;
const utcOf = day => { const [y, m, d] = String(day).split('-').map(Number); return Date.UTC(y, m - 1, d); };
const addDays = (day, n) => new Date(utcOf(day) + n * 86400000).toISOString().slice(0, 10);
const diffDays = (a, b) => Math.round((utcOf(b) - utcOf(a)) / 86400000); // b - a
const label = day => day ? new Date(utcOf(day) + 12 * 3600000).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' }) : null;
const rateSingle = k => SINGLE[Math.min(Math.max(k, 1), 4) - 1];
const rateBoth = k => BOTH[Math.min(Math.max(k, 1), 4) - 1];
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
const money = n => Number(n || 0).toLocaleString('en-US');
const esc = s => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function init(opts) { X = opts || {}; FILE = path.join(X.dataDir, 'refuel.json'); }
function cfg() {
const c = (X.siteConfig && X.siteConfig()) || {};
return {
on: String(c.refuelStreak == null ? '0' : c.refuelStreak) === '1',
reminders: String(c.refuelReminders == null ? '1' : c.refuelReminders) === '1',
reminderHour: Math.min(23, Math.max(0, Number(c.refuelReminderHour == null ? 9 : c.refuelReminderHour) || 0)),
dayPromo: String(c.refuelDayPromo == null ? '0' : c.refuelDayPromo) === '1',
dayPct: Math.max(0, Math.min(100, Number(c.refuelDayPct == null ? 10 : c.refuelDayPct) || 0)),
minIap: Math.max(0, Number(c.refuelMinIapCents) || 2000),
minLs: Math.max(0, Number(c.refuelMinLsCents) || 2500),
};
}
const minFor = (site, c) => site === 'linkspin' ? c.minLs : c.minIap;
const dbOn = () => !!(X.db && X.db.enabled && X.db.enabled());
// ---- storage: MySQL when there is one, else one JSON file (read and written synchronously, no await in between) ----
let tablesReady = null;
async function ensureTables() {
if (!dbOn()) return;
if (!tablesReady) tablesReady = (async () => {
await X.db.q('CREATE TABLE IF NOT EXISTS refuel_members (email VARCHAR(190) PRIMARY KEY, data MEDIUMTEXT NOT NULL, updated BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await X.db.q("CREATE TABLE IF NOT EXISTS refuel_outbox (ref VARCHAR(160) PRIMARY KEY, site VARCHAR(12) NOT NULL, email VARCHAR(190) NOT NULL, kind VARCHAR(16) NOT NULL, payload TEXT NOT NULL, status VARCHAR(8) NOT NULL DEFAULT 'pending', created BIGINT NOT NULL, done BIGINT NULL, INDEX (site, status), INDEX (email)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
})().catch(e => { tablesReady = null; throw e; });
return tablesReady;
}
function readFile() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.members = s.members || {}; s.outbox = s.outbox || {}; return s; } catch (e) { return { members: {}, outbox: {} }; } }
function writeFile(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s)); fs.renameSync(tmp, FILE); }
async function getRec(email) {
if (dbOn()) { await ensureTables(); const r = await X.db.q('SELECT data FROM refuel_members WHERE email=?', [email]); return r.length ? JSON.parse(r[0].data) : null; }
return readFile().members[email] || null;
}
async function putRec(rec) {
if (dbOn()) { await ensureTables(); await X.db.q('INSERT INTO refuel_members (email, data, updated) VALUES (?,?,?) ON DUPLICATE KEY UPDATE data=VALUES(data), updated=VALUES(updated)', [rec.email, JSON.stringify(rec), Date.now()]); return; }
const s = readFile(); s.members[rec.email] = rec; writeFile(s);
}
async function allRecs() {
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT data FROM refuel_members')).map(r => JSON.parse(r.data)); }
return Object.values(readFile().members);
}
// an outbox row is added once per ref, whatever happens after
async function addOut(item) {
const row = { ref: item.ref, site: item.site, email: item.email, kind: item.kind, payload: item.payload, status: 'pending', created: Date.now(), done: null };
if (dbOn()) { await ensureTables(); await X.db.q('INSERT IGNORE INTO refuel_outbox (ref, site, email, kind, payload, status, created) VALUES (?,?,?,?,?,?,?)', [row.ref, row.site, row.email, row.kind, JSON.stringify(row.payload), 'pending', row.created]); return; }
const s = readFile(); if (!s.outbox[row.ref]) { s.outbox[row.ref] = row; writeFile(s); }
}
async function pendingOut(site, email, limit) {
if (dbOn()) {
await ensureTables();
const rows = email ? await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' AND email=? ORDER BY created LIMIT ?", [site, email, limit || 200])
: await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' ORDER BY created LIMIT ?", [site, limit || 200]);
return rows.map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind, payload: JSON.parse(r.payload), created: Number(r.created) }));
}
return Object.values(readFile().outbox).filter(r => r.site === site && r.status === 'pending' && (!email || r.email === email)).sort((a, b) => a.created - b.created).slice(0, limit || 200);
}
async function markDone(site, refs) {
refs = (refs || []).map(String).filter(Boolean).slice(0, 500); if (!refs.length) return 0;
if (dbOn()) { await ensureTables(); const r = await X.db.q("UPDATE refuel_outbox SET status='done', done=? WHERE site=? AND ref IN (?) AND status='pending'", [Date.now(), site, refs]); return r.affectedRows || 0; }
const s = readFile(); let n = 0; for (const ref of refs) { const r = s.outbox[ref]; if (r && r.site === site && r.status === 'pending') { r.status = 'done'; r.done = Date.now(); n++; } } writeFile(s); return n;
}
async function outRows(filter) {
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT ref, site, email, kind, payload, status, created, done FROM refuel_outbox ORDER BY created DESC LIMIT 2000')).map(r => Object.assign(r, { payload: JSON.parse(r.payload), created: Number(r.created) })).filter(filter || (() => true)); }
return Object.values(readFile().outbox).sort((a, b) => b.created - a.created).filter(filter || (() => true));
}
const lock = (email, fn) => X.db && X.db.withLock ? X.db.withLock('rf:' + email, fn, 15) : fn();
// ---- the record ---------------------------------------------------------------------------------
function blank(email) { return { v: 1, email, active: false, streak: 0, best: 0, firstDay: null, lastDay: null, dueDay: null, opensDay: null, graceEnd: null, home: null, cycle: null, history: [], misses: [], freeMissDay: null, txs: {}, badges: {} }; }
function archive(rec) { if (rec.cycle) { rec.history.unshift(rec.cycle); rec.history = rec.history.slice(0, 24); } rec.cycle = null; }
// walk the calendar forward to `today`: every grace that passed with no refuel is a miss
function settle(rec, today) {
let changed = false;
for (let guard = 0; rec.active && rec.graceEnd && today > rec.graceEnd && guard < 40; guard++) {
changed = true;
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
if (freeOk) {
rec.misses.unshift({ day: rec.dueDay, free: true }); rec.freeMissDay = rec.graceEnd;
archive(rec);
rec.opensDay = addDays(rec.graceEnd, 1); // the very next qualifying package counts
rec.dueDay = addDays(rec.dueDay, CYCLE_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
} else {
rec.misses.unshift({ day: rec.dueDay, free: false, streak: rec.streak });
archive(rec); rec.active = false; rec.streak = 0; rec.dueDay = rec.opensDay = rec.graceEnd = null;
}
rec.misses = rec.misses.slice(0, 24);
}
return changed;
}
function startCycle(rec, site, day, k) {
archive(rec);
rec.active = true; rec.streak = k; rec.best = Math.max(rec.best || 0, k);
rec.firstDay = rec.firstDay || day; rec.lastDay = day; rec.home = site;
rec.dueDay = addDays(day, CYCLE_DAYS); rec.opensDay = addDays(rec.dueDay, -EARLY_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
rec.cycle = { n: k, startDay: day, sites: {}, pit: {}, both: false, featured: false };
}
const pctOf = (credits, pct) => Math.round((Number(credits) || 0) * pct / 100);
// classify one purchase and build its grants. Pure on (rec, purchase, config): the tests drive it directly.
function decide(rec, p, c) {
const day = ctDay(p.ts); const site = p.site; const other = site === 'iap' ? 'linkspin' : 'iap';
settle(rec, day);
const grants = [];
const g = (gs, kind, credits, note, extra) => { if (credits > 0) grants.push(Object.assign({ site: gs, kind, credits, note, ref: null }, extra || {})); };
let kind = 'none'; const firstEver = !rec.firstDay;
if (!rec.active || !rec.cycle || day >= rec.opensDay) {
// a counted refuel that opens a new cycle (first ever, after a reset, after a free miss, or in the window)
const k = rec.active ? rec.streak + 1 : 1;
startCycle(rec, site, day, k);
const pct = rateSingle(k), bonus = pctOf(p.credits, pct);
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
kind = 'refuel';
g(site, 'streak', bonus, 'Refuel streak month ' + k + ': +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k });
} else if (!rec.cycle.sites[site]) {
// the second engine in the same cycle: both-rate here, and the first site topped up to it
const k = rec.cycle.n, pct = rateBoth(k), bonus = pctOf(p.credits, pct);
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
rec.cycle.both = true; kind = 'refuel';
g(site, 'streak', bonus, 'Refuel streak month ' + k + ', both engines: +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k, both: true });
const o = rec.cycle.sites[other];
if (o) {
const owed = pctOf(o.credits, pct) - (o.bonus || 0);
if (owed > 0) { g(other, 'topup', owed, 'Twin Engine top-up: your month ' + k + ' refuel raised to +' + pct + '%', { ref: 'rftop:' + other + ':' + p.tx, pct, month: k }); o.bonus += owed; o.pct = pct; }
}
if (k >= 4 && !rec.cycle.featured) {
rec.cycle.featured = true;
const per = Math.max(0, Number(X.featuredBonus ? X.featuredBonus() : 100) || 100); // Marty 2026-10-24: 100 credits (was one day's Featured price, 40)
g('iap', 'featured', per, 'Twin Engine month ' + k + ': Featured bonus (' + per + ' credits)', { ref: 'rffeat:' + rec.email + ':' + rec.cycle.startDay, month: k });
}
} else if (!rec.cycle.pit[site]) {
const k = rec.cycle.n, cur = rec.cycle.both ? rateBoth(k) : rateSingle(k), pct = cur / 2;
rec.cycle.pit[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus: pctOf(p.credits, pct), day };
kind = 'pitstop';
g(site, 'pitstop', pctOf(p.credits, pct), 'Pit Stop: +' + pct + '% (half your +' + cur + '% streak rate) on your ' + usd(p.cents) + ' package', { ref: 'rfpit:' + site + ':' + p.tx, pct, month: k });
}
// the Refuel Kit: a counted refuel unlocks the kit of its Central-time month, remembered with the streak month it came at
if (kind === 'refuel') { rec.kits = rec.kits || {}; const m = day.slice(0, 7); if (!rec.kits[m]) rec.kits[m] = rec.cycle ? rec.cycle.n : 1; }
if (kind === 'refuel' && c.dayPromo && c.dayPct > 0 && day.slice(8) === '01') g(site, 'refuelday', pctOf(p.credits, c.dayPct), 'Refuel Day (the 1st): +' + c.dayPct + '% on your ' + usd(p.cents) + ' package', { ref: 'rfday:' + site + ':' + p.tx, pct: c.dayPct });
// badges: Engine Started at the first counted refuel ever (Marty 2026-10-24), then 3, 6 and 12 months in a row
const badges = [];
const opened = kind === 'refuel' && rec.cycle && rec.cycle.startDay === day && Object.keys(rec.cycle.sites).length === 1;
if (kind === 'refuel' && firstEver && !rec.badges.refuelStart) badges.push('refuelStart');
if (opened && BADGE_AT.includes(rec.streak) && !rec.badges['refuel' + rec.streak]) badges.push('refuel' + rec.streak);
for (const b of badges) rec.badges[b] = Date.now();
return { kind, day, month: rec.cycle ? rec.cycle.n : 0, grants, badges, both: !!(rec.cycle && rec.cycle.both) };
}
// ---- recording a purchase (both sites come through here) ------------------------------------------
async function record(p) {
const c = cfg(); if (!c.on) return { on: false };
const email = String(p.email || '').toLowerCase(); const site = p.site === 'linkspin' ? 'linkspin' : 'iap';
const tx = String(p.tx || ''); const cents = Number(p.cents) || 0; const credits = Number(p.credits) || 0;
if (!email || !tx) return { on: true, error: 'email and tx required' };
if (cents < minFor(site, c)) return { on: true, kind: 'below', minCents: minFor(site, c) };
const out = await lock(email, async () => {
const rec = (await getRec(email)) || blank(email);
if (rec.txs[tx]) return Object.assign({ repeat: true }, rec.txs[tx]);
const d = decide(rec, { site, tx, cents, credits, ts: Number(p.ts) || Date.now() }, c);
for (const gr of d.grants) {
const payload = { credits: gr.credits, note: gr.note, kind: gr.kind, pct: gr.pct || null, month: gr.month || null, cents, tx };
await addOut({ ref: gr.ref, site: gr.site, email, kind: 'grant', payload });
}
rec.txs[tx] = { kind: d.kind, site, day: d.day, month: d.month, both: d.both, refs: d.grants.map(x => x.ref), at: Date.now() };
const keys = Object.keys(rec.txs); if (keys.length > 400) for (const k of keys.slice(0, keys.length - 400)) delete rec.txs[k];
await putRec(rec);
return Object.assign({ badges: d.badges }, rec.txs[tx]);
});
if (!out.repeat && out.badges && X.badge) for (const b of out.badges) { try { await X.badge(email, b); } catch (e) { console.error('refuel badge', e.message); } }
// one short line in the payments feed for every counted refuel (never a Pit Stop), once per tx across app copies
if (!out.repeat && out.kind === 'refuel' && X.feed && (!X.marks || await X.marks.claim('rffeed:' + tx))) {
try { await X.feed(await feedLine(email, out)); } catch (e) { console.error('refuel feed', e.message); }
}
await drainLocal().catch(e => console.error('refuel drain', e.message));
if (out.kind && out.kind !== 'none') console.log('refuel:', site, out.kind, 'month', out.month, email.replace(/^(.).*(@.*)$/, '$1***$2'), String(tx).slice(0, 12));
return Object.assign({ on: true }, out);
}
async function whoOf(email) {
let a = null; try { a = await X.accounts.byEmail(email); } catch (e) {}
return a && a.username ? '@' + a.username : a && a.memberId ? 'member #' + a.memberId : 'a member';
}
async function feedLine(email, out) {
const who = (await whoOf(email)).replace(/[<>&]/g, '');
const what = out.both ? 'refueled both engines' : 'refueled ' + NAME[out.site];
return '⛽ <b>' + who + '</b> ' + what + ' · streak ' + out.month;
}
// Monday roundup of the week that just ended (Mon..Sun, Central), one per week across app copies
function weekOf(today) { const dow = new Date(utcOf(today)).getUTCDay(); const mon = addDays(today, -((dow + 6) % 7)); return { thisMon: mon, from: addDays(mon, -7), to: addDays(mon, -1) }; }
async function roundup(today) {
const w = weekOf(today); let members = 0, fresh = 0, longest = 0;
for (const r of await allRecs()) {
const hits = Object.values(r.txs || {}).filter(x => x.kind === 'refuel' && x.day >= w.from && x.day <= w.to);
if (hits.length) { members++; if (hits.some(x => x.month === 1)) fresh++; }
if (r.active) longest = Math.max(longest, r.streak || 0);
}
return { week: w, members, fresh, longest };
}
// an InstantAdPay chain Purchase: resolve the owner (main member or a linked position) and record it
async function onIapPurchase(ev) {
if (!ev || ev.type !== 'Purchase' || !cfg().on) return null;
let a = await X.accounts.byMemberId(ev.buyerId).catch(() => null);
if (!a && X.accounts.positionByMember) { const pos = await X.accounts.positionByMember(ev.buyerId).catch(() => null); if (pos && pos.email) a = await X.accounts.byEmail(pos.email).catch(() => null); }
if (!a || !a.email) return null;
return record({ site: 'iap', email: a.email, tx: ev.tx, cents: ev.priceCents, credits: ev.creditAmount, ts: ev.ts });
}
// ---- applying InstantAdPay's own outbox rows ---------------------------------------------------------
let draining = false;
async function drainLocal() {
if (draining) return 0; draining = true; let n = 0;
try {
for (const it of await pendingOut('iap', null, 200)) {
const mine = X.marks ? await X.marks.claim('rfg:' + it.ref) : true;
if (mine) {
if (it.kind === 'grant') {
await X.ads.addEarned(it.email, it.payload.credits, { purchased: true, log: { kind: 'bonus', note: it.payload.note, ref: it.ref.slice(0, 60) } });
try { await X.message(it.email, grantSubject(it.payload), grantHtml(it.payload, 'iap')); } catch (e) { console.error('refuel notice', e.message); }
} else if (it.kind === 'reminder') await sendReminder(it.email, it.payload, 'iap');
n++;
}
await markDone('iap', [it.ref]);
}
} finally { draining = false; }
return n;
}
function grantSubject(p) {
if (p.kind === 'topup') return 'Twin Engine top-up: +' + money(p.credits) + ' bonus credits';
if (p.kind === 'pitstop') return 'Pit Stop bonus: +' + money(p.credits) + ' credits';
if (p.kind === 'featured') return 'Twin Engine: +' + money(p.credits) + ' Featured bonus credits';
if (p.kind === 'refuelday') return 'Refuel Day bonus: +' + money(p.credits) + ' credits';
return 'Refuel counted: +' + money(p.credits) + ' bonus credits (month ' + (p.month || 1) + ')';
}
function grantHtml(p, site) {
const where = site === 'linkspin' ? 'Credits' : 'Campaigns';
return '<p>' + esc(p.note) + '. <b>' + money(p.credits) + ' bonus ad credits</b> were added to your ' + NAME[site] + ' balance, purchased-grade, so they run on any format, login ads included, and the credit log names them.</p>'
+ (p.kind === 'featured' ? '<p>Enough for two Featured days and more: book Featured links under Campaigns whenever you like, or spend them on any format.</p>' : '')
+ (p.kind === 'pitstop' ? '<p>A Pit Stop keeps an ad running between refuel days. It does not count as your monthly refuel: that is still due on your refuel day.</p>' : '')
+ '<p>See your refuel day and streak on the Refuel card (' + where + '). Bonus credits buy ad delivery only; they are never cash.</p>';
}
// ---- the LinkSpin side of the outbox --------------------------------------------------------------
async function outbox(site, email) { return pendingOut(site === 'linkspin' ? 'linkspin' : 'iap', email ? String(email).toLowerCase() : null, 200); }
async function ack(site, refs) { return markDone(site === 'linkspin' ? 'linkspin' : 'iap', refs); }
// ---- reminders ---------------------------------------------------------------------------------------
function reminderCopy(rec, kind) {
const k = rec.streak, next = k + 1, sOne = rateSingle(next), sBoth = rateBoth(next);
const due = label(rec.dueDay), grace = label(rec.graceEnd);
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
const offer = 'A $20+ package on InstantAdPay or $25+ on LinkSpin counts. Your next refuel earns +' + sOne + '% bonus ad credits, or +' + sBoth + '% on each site when you refuel both in the same cycle.';
if (kind === 'soon') return { subject: 'Your refuel day is ' + due, text: 'Your refuel day is ' + due + ' (Central time), and your window is open from today. ' + offer + ' Keep your ' + k + '-month streak by ' + grace + ', the end of your 5-day grace.' };
if (kind === 'day') return { subject: 'Today is your refuel day', text: 'Today is your refuel day. ' + offer + ' You have until ' + grace + ' (Central time) to keep your ' + k + '-month streak.' };
return { subject: 'Last call: your refuel grace ends tonight', text: 'Today is the last day of your 5-day grace. Refuel before midnight Central to keep your ' + k + '-month streak. ' + offer
+ (freeOk ? ' If you skip it, your one free miss this year keeps the streak, and your next package counts as the refuel.' : ' Your free miss for this year is already used, so after tonight the streak starts again from month 1.') };
}
async function sendReminder(email, payload, site) {
const host = site === 'linkspin' ? LS_SITE + '/credits' : SITE + '/my#buy';
const text = payload.text + '\n\nBuy a package: ' + host;
const html = '<p>' + esc(payload.text) + '</p><p><a href="' + host + '">Buy a package</a></p><p style="color:#556">Bonus credits buy ad delivery only; they are never cash.</p>';
try { await X.message(email, payload.subject, html); } catch (e) { console.error('refuel reminder inbox', e.message); }
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(email).catch(() => false) : false;
if (!stopped && X.mailer && X.mailer.hasKey()) {
const foot = X.drip && X.drip.unsubUrl ? '\n\nStop these emails: ' + X.drip.unsubUrl(email) : '';
try { await X.mailer.send(email, payload.subject, text + foot + '\n\nInstantAdPay'); } catch (e) { console.error('refuel reminder mail', e.message); }
}
}
// the daily pass: settle misses, queue the reminders that came due today, apply our outbox
let ticking = false;
async function tick(now) {
const c = cfg(); if (!c.on || ticking) return { on: c.on };
ticking = true; let reminders = 0, settled = 0;
try {
const t = now || Date.now(); const today = ctDay(t); const hourOk = ctHour(t) >= c.reminderHour;
for (const r0 of await allRecs()) {
if (!r0.active) continue;
const res = await lock(r0.email, async () => {
const rec = await getRec(r0.email); if (!rec) return null;
if (settle(rec, today)) { await putRec(rec); settled++; }
if (!rec.active || !c.reminders || !hourOk) return null;
const kind = today === addDays(rec.dueDay, -EARLY_DAYS) ? 'soon' : today === rec.dueDay ? 'day' : today === rec.graceEnd ? 'last' : null;
if (!kind) return null;
if (rec.cycle && rec.cycle.startDay >= rec.opensDay) return null; // already refueled in this window
const ref = 'rfrem:' + rec.email + ':' + rec.dueDay + ':' + kind;
await addOut({ ref, site: rec.home === 'linkspin' ? 'linkspin' : 'iap', email: rec.email, kind: 'reminder', payload: Object.assign({ remind: kind, dueDay: rec.dueDay, graceEnd: rec.graceEnd, streak: rec.streak }, reminderCopy(rec, kind)) });
return kind;
});
if (res) reminders++;
}
await drainLocal();
// Monday after the reminder hour: last week's roundup to the payments feed (skipped when nobody refueled)
if (X.feed && new Date(utcOf(today)).getUTCDay() === 1 && ctHour(t) >= Math.max(9, c.reminderHour)) {
const ru = await roundup(today);
if (ru.members > 0 && (!X.marks || await X.marks.claim('rfweek:' + ru.week.thisMon))) {
try { await X.feed('⛽ <b>Refueled this week:</b> ' + ru.members + ' member' + (ru.members === 1 ? '' : 's') + ', ' + ru.fresh + ' new streak' + (ru.fresh === 1 ? '' : 's') + ', longest streak ' + ru.longest); } catch (e) { console.error('refuel roundup', e.message); }
}
}
} finally { ticking = false; }
return { on: true, settled, reminders };
}
// ---- what the member sees ----------------------------------------------------------------------------
async function view(email, now) {
const c = cfg(); if (!c.on) return { on: false };
email = String(email || '').toLowerCase();
const rec0 = await getRec(email); const today = ctDay(now || Date.now());
const rec = rec0 ? JSON.parse(JSON.stringify(rec0)) : blank(email);
settle(rec, today); // read-only copy: a passed grace shows as it will be stored on the next tick
const k = rec.active ? rec.streak : 0, next = k + 1;
const cy = rec.cycle;
const curRate = cy ? (cy.both ? rateBoth(cy.n) : rateSingle(cy.n)) : 0;
const windowOpen = !rec.active || !cy || today >= rec.opensDay;
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, today) >= FREE_MISS_DAYS;
const siteState = s => cy && cy.sites[s] ? { refueled: true, credits: cy.sites[s].credits, pct: cy.sites[s].pct, bonus: cy.sites[s].bonus, day: cy.sites[s].day, dayLabel: label(cy.sites[s].day) } : { refueled: false };
return {
on: true, started: !!rec.firstDay, engineUnlocked: !!rec.firstDay, active: rec.active, streak: k, best: rec.best || 0,
firstDay: rec.firstDay, lastDay: rec.lastDay, refuelDay: rec.dueDay, refuelDayLabel: label(rec.dueDay), opensDay: rec.opensDay, opensLabel: label(rec.opensDay),
graceEnd: rec.graceEnd, graceLabel: label(rec.graceEnd), today, daysToRefuel: rec.dueDay ? diffDays(today, rec.dueDay) : null, windowOpen,
cycle: cy ? { month: cy.n, startDay: cy.startDay, both: !!cy.both, iap: siteState('iap'), linkspin: siteState('linkspin'), rate: curRate } : null,
next: windowOpen ? { month: next, single: rateSingle(next), both: rateBoth(next) } : { month: cy.n, secondEngine: rateBoth(cy.n) },
pitStop: cy && !windowOpen ? { pct: curRate / 2, iap: !cy.pit.iap && !!cy.sites.iap, linkspin: !cy.pit.linkspin && !!cy.sites.linkspin, usedIap: !!cy.pit.iap, usedLinkspin: !!cy.pit.linkspin } : null,
freeMiss: { available: freeOk, usedDay: rec.freeMissDay }, misses: rec.misses.slice(0, 6), badges: Object.keys(rec.badges || {}),
kits: rec.kits || {}, goal: rec.engineGoal || null,
minUsd: { iap: c.minIap / 100, linkspin: c.minLs / 100 }, ladder: { single: SINGLE, both: BOTH }, refuelDay1: c.dayPromo ? c.dayPct : 0,
};
}
// the line the refill notices add to their bonus block
async function streakLine(email) {
const v = await view(email).catch(() => null);
if (!v || !v.on) return null;
let t;
if (!v.active) t = 'Refuel streak: a $20+ package on InstantAdPay (or $25+ on LinkSpin) starts your monthly refuel streak with +10% bonus ad credits, +15% on each site when you refuel both.';
else if (v.windowOpen) t = 'Refuel streak: you are on ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') + ', and your refuel window is open now (refuel day ' + v.refuelDayLabel + ', grace to ' + v.graceLabel + ', Central time). Refuel now for +' + v.next.single + '%, or +' + v.next.both + '% on each site with both.';
else t = 'Refuel streak: month ' + v.streak + ', next refuel day ' + v.refuelDayLabel + ' (Central time).' + (v.pitStop && (v.pitStop.iap || v.pitStop.linkspin) ? ' A top-up before then earns a Pit Stop bonus of +' + v.pitStop.pct + '% (once per site this cycle).' : '');
return { text: t, html: '<b>Refuel streak:</b> ' + esc(t.replace(/^Refuel streak: /, '')) };
}
// the member's own monthly goal for the Engine Room's goals dial (conversions from the pixel); 0 clears it
async function setGoal(email, goal) {
if (!cfg().on) return { error: 'The Engine Room is not switched on.' };
email = String(email || '').toLowerCase(); const g = Math.max(0, Math.min(100000, Math.round(Number(goal) || 0)));
return lock(email, async () => { const rec = (await getRec(email)) || blank(email); rec.engineGoal = g || null; await putRec(rec); return { ok: true, goal: rec.engineGoal }; });
}
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
// ---- admin ------------------------------------------------------------------------------------------
async function stats() {
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
const by = {}; for (const r of rows) { const k = r.kind === 'grant' ? r.payload.kind : 'reminder'; const b = by[k] || (by[k] = { n: 0, credits: 0, pending: 0 }); b.n++; b.credits += Number(r.payload.credits) || 0; if (r.status === 'pending') b.pending++; }
return { settings: c, members: recs.length, active: recs.filter(r => r.active).length, both: recs.filter(r => r.cycle && r.cycle.both).length,
byMonth: recs.filter(r => r.active).reduce((m, r) => { const k = Math.min(r.streak, 12); m[k] = (m[k] || 0) + 1; return m; }, {}),
grants: by, pending: rows.filter(r => r.status === 'pending').length,
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
}
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };