7bcde25116
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
163 lines
11 KiB
JavaScript
163 lines
11 KiB
JavaScript
// The Monthly Refuel streak, LinkSpin side (Fuel Your Offers, 2026-10-24). The streak itself lives on InstantAdPay
|
|
// (its refuel.js is the source of truth: ONE streak per member across both sites). LinkSpin only:
|
|
// 1. reports each LinkSpin package of $25+ (signed POST <IAP>/api/partner/refuel/purchase), once per tx: the copy
|
|
// of the app that wins the claim 'rfev:<tx>' writes a pending file (DATA_DIR/refuel-pending/<tx>.json) and
|
|
// retries it every minute until InstantAdPay answers, so an outage never loses a refuel
|
|
// 2. applies LinkSpin's grants and reminders from InstantAdPay's outbox (signed /outbox, then /ack). Each grant is
|
|
// claimed 'rfg:<ref>' first (marks.js), so two copies of the app never double-grant, and a lost ack only means
|
|
// the row comes back and is acked without being applied twice
|
|
// 3. shows the member's Refuel card from InstantAdPay's view of them (signed /status, cached 60 s)
|
|
// MASTER SWITCH: site setting refuelStreak (default '0'): off = nothing reported, pulled or shown. InstantAdPay has
|
|
// its own switch; a purchase it is not counting comes back { on:false } and is dropped.
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
|
|
let X = {}, PENDING = null;
|
|
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
|
const IAP = () => String(X.iapBase ? X.iapBase() : (process.env.IAP_URL || 'https://instantadpay.com')).replace(/\/+$/, '');
|
|
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
const money = n => Number(n || 0).toLocaleString('en-US');
|
|
|
|
function init(opts) {
|
|
X = opts || {};
|
|
PENDING = path.join(X.dataDir, 'refuel-pending');
|
|
try { fs.mkdirSync(PENDING, { recursive: true }); } catch (e) {}
|
|
}
|
|
function cfg() {
|
|
const c = (X.siteConfig && X.siteConfig()) || {};
|
|
return { on: String(c.refuelStreak == null ? '0' : c.refuelStreak) === '1', minCents: Math.max(0, Number(c.refuelMinLsCents) || 2500) };
|
|
}
|
|
const linked = () => SECRET().length >= 32;
|
|
|
|
async function post(pth, body, timeoutMs) {
|
|
if (X.post) return X.post(pth, body); // tests
|
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
|
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
|
const r = await fetch(IAP() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
|
|
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
|
if (!r.ok) throw new Error((j && j.error) || ('InstantAdPay ' + r.status));
|
|
return j || {};
|
|
}
|
|
|
|
// ---- 1. a LinkSpin package ---------------------------------------------------------------------------
|
|
async function ownerOf(buyerId) {
|
|
let a = await X.accounts.byMemberId(Number(buyerId)).catch(() => null);
|
|
if (!a && X.accounts.positionByMember) { const p = await X.accounts.positionByMember(Number(buyerId)).catch(() => null); if (p && p.email) a = await X.accounts.byEmail(p.email).catch(() => null); }
|
|
return a && a.email ? String(a.email).toLowerCase() : null;
|
|
}
|
|
const fileOf = tx => path.join(PENDING, crypto.createHash('sha1').update(String(tx)).digest('hex') + '.json');
|
|
async function onPurchase(ev) {
|
|
const c = cfg();
|
|
if (!ev || ev.type !== 'Purchase' || !c.on || (Number(ev.priceCents) || 0) < c.minCents) return null;
|
|
if (X.marks && !(await X.marks.claim('rfev:' + ev.tx))) return null; // the other copy of the app has it
|
|
const email = await ownerOf(ev.buyerId); if (!email) return null;
|
|
const item = { email, tx: ev.tx, cents: Number(ev.priceCents) || 0, credits: Number(ev.creditAmount) || 0, ts: Number(ev.ts) || Date.now(), tries: 0 };
|
|
try { fs.writeFileSync(fileOf(ev.tx), JSON.stringify(item)); } catch (e) { console.error('refuel pending write', e.message); }
|
|
return pushOne(item);
|
|
}
|
|
async function pushOne(item) {
|
|
if (!linked()) return { queued: true };
|
|
try {
|
|
const r = await post('/api/partner/refuel/purchase', { email: item.email, tx: item.tx, cents: item.cents, credits: item.credits, ts: item.ts });
|
|
try { fs.unlinkSync(fileOf(item.tx)); } catch (e) {}
|
|
if (r && r.on && Array.isArray(r.items)) await applyAll(r.items);
|
|
return r;
|
|
} catch (e) {
|
|
item.tries = (item.tries || 0) + 1; item.lastError = e.message;
|
|
try { if (fs.existsSync(fileOf(item.tx))) fs.writeFileSync(fileOf(item.tx), JSON.stringify(item)); } catch (er) {}
|
|
console.error('refuel report failed (will retry)', String(item.tx).slice(0, 12), e.message);
|
|
return { queued: true, error: e.message };
|
|
}
|
|
}
|
|
async function retryPending() {
|
|
let n = 0;
|
|
for (const f of (() => { try { return fs.readdirSync(PENDING); } catch (e) { return []; } })()) {
|
|
if (!f.endsWith('.json')) continue;
|
|
let item; try { item = JSON.parse(fs.readFileSync(path.join(PENDING, f), 'utf8')); } catch (e) { continue; }
|
|
const r = await pushOne(item); if (r && !r.queued) n++;
|
|
}
|
|
return n;
|
|
}
|
|
|
|
// ---- 2. grants and reminders from InstantAdPay's outbox -----------------------------------------------
|
|
async function applyAll(items) {
|
|
const done = [];
|
|
for (const it of items || []) {
|
|
try { await applyOne(it); done.push(it.ref); } catch (e) { console.error('refuel apply', it.ref, e.message); }
|
|
}
|
|
if (done.length) { try { await post('/api/partner/refuel/ack', { refs: done }); } catch (e) { console.error('refuel ack', e.message); } }
|
|
return done.length;
|
|
}
|
|
async function applyOne(it) {
|
|
const mine = X.marks ? await X.marks.claim('rfg:' + it.ref) : true;
|
|
if (!mine) return false; // applied before (or by the other copy): ack only
|
|
const p = it.payload || {};
|
|
if (it.kind === 'grant') {
|
|
const credits = Math.max(0, Math.round(Number(p.credits) || 0)); if (!credits) return false;
|
|
await X.ads.addEarned(it.email, credits, { purchased: true });
|
|
if (X.ads.logCredit) await X.ads.logCredit(it.email, credits, String(p.note || 'Refuel streak bonus').slice(0, 160));
|
|
try { await X.message(it.email, subjectOf(p), htmlOf(p)); } catch (e) { console.error('refuel notice', e.message); }
|
|
console.log('refuel grant applied', it.ref.slice(0, 40), credits);
|
|
} else if (it.kind === 'reminder') {
|
|
const html = '<p>' + esc(p.text) + '</p><p><a href="' + X.siteUrl + '/credits">Buy a package</a></p><p style="color:#556">Bonus credits buy ad delivery only; they are never cash.</p>';
|
|
try { await X.message(it.email, p.subject, html); } catch (e) { console.error('refuel reminder inbox', e.message); }
|
|
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(it.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(it.email) : '';
|
|
try { await X.mailer.send(it.email, p.subject, p.text + '\n\nBuy a package: ' + X.siteUrl + '/credits' + foot + '\n\nLinkSpin'); } catch (e) { console.error('refuel reminder mail', e.message); }
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
function subjectOf(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 === 'refuelday') return 'Refuel Day bonus: +' + money(p.credits) + ' credits';
|
|
return 'Refuel counted: +' + money(p.credits) + ' bonus credits (month ' + (p.month || 1) + ')';
|
|
}
|
|
function htmlOf(p) {
|
|
return '<p>' + esc(p.note) + '. <b>' + money(p.credits) + ' bonus ad credits</b> were added to your LinkSpin balance, purchased-grade, so they run on any format, login ads included.</p>'
|
|
+ (p.kind === 'pitstop' ? '<p>A Pit Stop keeps an ad running between refuel days. It does not count as your monthly refuel.</p>' : '')
|
|
+ '<p>Your refuel day and streak are on the Refuel card under Credits. Bonus credits buy ad delivery only; they are never cash.</p>';
|
|
}
|
|
let pulling = false;
|
|
async function pull() {
|
|
if (!cfg().on || !linked() || pulling) return 0;
|
|
pulling = true;
|
|
try { const r = await post('/api/partner/refuel/outbox', {}); return r && r.on ? await applyAll(r.items || []) : 0; }
|
|
catch (e) { console.error('refuel pull', e.message); return 0; }
|
|
finally { pulling = false; }
|
|
}
|
|
async function tick() { if (!cfg().on) return { on: false }; const retried = await retryPending(); const applied = await pull(); return { on: true, retried, applied }; }
|
|
|
|
// ---- 3. the member's card ---------------------------------------------------------------------------------
|
|
const cache = new Map();
|
|
async function status(email) {
|
|
if (!cfg().on) return { on: false };
|
|
email = String(email || '').toLowerCase(); if (!email) return { on: false };
|
|
const hit = cache.get(email); if (hit && Date.now() - hit.at < 60000) return hit.v;
|
|
if (!linked()) return { on: false, reason: 'not linked' };
|
|
let v;
|
|
try { v = await post('/api/partner/refuel/status', { email }, 6000); } catch (e) { return { on: true, error: 'InstantAdPay did not answer just now.' }; }
|
|
cache.set(email, { at: Date.now(), v }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
|
return v;
|
|
}
|
|
// the refill notice's streak line, from the same view
|
|
async function streakLine(email) {
|
|
const v = await status(email).catch(() => null);
|
|
if (!v || !v.on || v.error) return null;
|
|
let t;
|
|
if (!v.active) t = 'Refuel streak: a $' + v.minUsd.linkspin + '+ package here (or $' + v.minUsd.iap + '+ on InstantAdPay) 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: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') + ', and your refuel window is open (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.linkspin ? ' A $' + v.minUsd.linkspin + '+ top-up before then earns a Pit Stop bonus of +' + v.pitStop.pct + '%.' : '');
|
|
return { text: t, html: '<b>Refuel streak:</b> ' + esc(t.replace(/^Refuel streak: /, '')) };
|
|
}
|
|
function adminView() {
|
|
let pending = []; try { pending = fs.readdirSync(PENDING).filter(f => f.endsWith('.json')).map(f => { try { return JSON.parse(fs.readFileSync(path.join(PENDING, f), 'utf8')); } catch (e) { return null; } }).filter(Boolean); } catch (e) {}
|
|
return { on: cfg().on, linked: linked(), iap: IAP(), pending: pending.map(p => ({ email: p.email, tx: p.tx, cents: p.cents, tries: p.tries || 0, lastError: p.lastError || null })) };
|
|
}
|
|
|
|
module.exports = { init, cfg, onPurchase, retryPending, pull, tick, status, streakLine, applyAll, adminView };
|