Monthly Refuel streak (Fuel Your Offers stage 2, Marty approved 2026-10-24), InstantAdPay = source of truth for ONE streak per member across InstantAdPay + LinkSpin. refuel.js: counted refuel = a new $20+ package here (refuelMinIapCents) or $25+ on LinkSpin (reported by LinkSpin) by one of the member's own positions (main or linked); the first sets the refuel day, next due 30 Central days after the last counted refuel, window opens 5 days before, 5-day grace, one free miss per 365 days, else reset. Bonus = purchased-grade credits on the site where bought, credit log kind bonus "Refuel streak month k": one engine 10/15/20/25%, both engines in the same cycle 15/20/30/40% (second site gets the both rate, the first is topped up by the difference), m4+ both = one free Featured day credited (featuredPerDay). Stacks on Friday/Wednesday (separate grants). Pit Stop = half the current rate, once per site per cycle, not a refuel. Badges Engine Started (first refuel) + Refueled 3/6/12 months through postBadgeOnce (placeholder gauge art in public/badges/badge-refuel*.jpg; shown in the strip only once earned). Feed: one line per counted refuel to the payments topic (claim rffeed:<tx>, never a Pit Stop) + Monday roundup after 9 AM CT (claim rfweek:<monday>, skipped at 0). Reminders 5 days before / on the day / last call (email with unsubscribe + notice kind notice) from the site of the last counted refuel. Optional Refuel Day on the 1st (refuelDayPromo, default off). Every decision is made under a member lock (db.withLock: MySQL GET_LOCK across app copies) and stored by tx; every grant is an outbox row keyed by a unique ref and claimed rfg:<ref> before it is applied, so two copies never double-grant. Partner endpoints /api/partner/refuel/purchase|outbox|ack|status (HMAC LS_SYNC_SECRET), member /api/my/refuel, admin /api/admin/refuel (+ /tick, /member). Refuel card on the Overview (fuel.js). Chatbot CANNED + FACTS follow the switch (off: "built, not switched on"), KNOWLEDGE_DATE 2026-10-24. MASTER SWITCH refuelStreak default '0': nothing counted or granted, no reminders, no feed lines, card hidden. qa/refuel.test.cjs 19 checks (switch, ladder, both-engine top-up, grace, free miss incl. 365-day return, Pit Stop once, stacking, idempotency, two concurrent workers, Central day + DST, Refuel Day, badges, reminders, roundup, view). my.js?v=20261024rf, fuel.js?v=20261024rf.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@ const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
let PUBLIC_DIR = null;
|
||||
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } };
|
||||
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } , refuelStart: { file: 'badge-refuelstart.jpg', ribbonY: 0.775 }, refuel3: { file: 'badge-refuel3.jpg', ribbonY: 0.775 }, refuel6: { file: 'badge-refuel6.jpg', ribbonY: 0.775 }, refuel12: { file: 'badge-refuel12.jpg', ribbonY: 0.775 } };
|
||||
let FONT;
|
||||
function font() {
|
||||
if (FONT !== undefined) return FONT;
|
||||
|
||||
+13
-4
@@ -22,7 +22,8 @@ let chain = null;
|
||||
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
function init(opts) {
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
function key() {
|
||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||
@@ -31,7 +32,7 @@ function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
// TODO(level-4 override, 2026-10-23): at go-live add the CANNED entry + FACTS line drafted in D:/tmp/override-copy/instantadpay-override-copy.md (section 3), and bump KNOWLEDGE_DATE only in that deploy.
|
||||
const KNOWLEDGE_DATE = '2026-10-23'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-10-24'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
|
||||
const CANNED = [
|
||||
{ id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'],
|
||||
@@ -73,6 +74,9 @@ const CANNED = [
|
||||
{ id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'],
|
||||
re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
|
||||
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
||||
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview. Buy here: https://instantadpay.com/my#buy. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
|
||||
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
||||
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
||||
@@ -208,11 +212,15 @@ function passTiersFact() {
|
||||
return '- GAME PASS TIERS (on sale, Members > Games > Game Pass at https://instantadpay.com/my#games): beside the $5 weekly Game Pass, ' + rows.map(r => r.name + ' $' + r.usd + ' for ' + r.days + ' days (' + 'paid by a new package of at least $' + r.usd + '): ' + r.perks.join('; ')).join(' | ')
|
||||
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in all nine games with the SAME daily POL caps (1.50 / 5 POL): a higher pass never pays more POL. Passes run side by side, each with its own end date; no auto-renew; buying again adds the pass length from its end date (or from now if it ended). Every pass is paid by a NEW package purchase of at least its price, made after tapping Get on that pass; the pass starts when it settles, the sponsor and team are paid from the package as usual, and the member keeps the package credits for ads. Credits already held never buy a pass. Nothing earned in a game is taken away when a pass ends.\n';
|
||||
}
|
||||
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
|
||||
let REFUEL_ON = () => false;
|
||||
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
|
||||
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
|
||||
function systemPrompt(kbBlock) {
|
||||
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
||||
|
||||
FACTS:
|
||||
${passTiersFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||
${passTiersFact()}${refuelFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||
- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time.
|
||||
- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=<username>; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/<username>. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide.
|
||||
- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money.
|
||||
@@ -355,8 +363,9 @@ async function answerRaw(message, historyText) {
|
||||
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||
let hit = null, kbOk = true;
|
||||
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||
let kbBlock = '', kbIds = [];
|
||||
try {
|
||||
|
||||
@@ -425,4 +425,24 @@ async function importJsonOnce() {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, q: (...a) => q(...a) };
|
||||
// A named lock that holds across every app copy (MySQL GET_LOCK on one dedicated connection), for read-modify-write of a
|
||||
// record two copies might touch at once (the refuel streak, 2026-10-24). Without a database: a per-process queue.
|
||||
const localLocks = new Map();
|
||||
async function withLock(name, fn, secs) {
|
||||
const key = String(name).slice(0, 60);
|
||||
if (!enabled() || !pool) {
|
||||
const prev = localLocks.get(key) || Promise.resolve();
|
||||
let release; const mine = new Promise(r => { release = r; });
|
||||
const tail = prev.then(() => mine); localLocks.set(key, tail);
|
||||
await prev;
|
||||
try { return await fn(); } finally { release(); if (localLocks.get(key) === tail) localLocks.delete(key); }
|
||||
}
|
||||
const conn = await pool.getConnection();
|
||||
try {
|
||||
const [[row]] = await conn.query('SELECT GET_LOCK(?, ?) AS ok', [key, Number(secs) || 10]);
|
||||
if (!row || Number(row.ok) !== 1) throw new Error('lock busy: ' + key);
|
||||
try { return await fn(); } finally { try { await conn.query('SELECT RELEASE_LOCK(?)', [key]); } catch (e) {} }
|
||||
} finally { conn.release(); }
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, q: (...a) => q(...a), withLock };
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Fuel Your Offers (2026-10-24): the Refuel card on the Overview. Hidden while the refuelStreak switch is off
|
||||
// (/api/my/refuel answers { on:false }). Everything here is ad credits, never cash.
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||
const goBuy = () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); else location.hash = '#buy'; };
|
||||
window.FUEL = window.FUEL || {};
|
||||
|
||||
function siteLine(name, s, minUsd) {
|
||||
if (s && s.refueled) return '<li><b>' + name + '</b>: refueled ' + esc(s.dayLabel ? 'on ' + s.dayLabel : '') + ', +' + s.pct + '% (' + n(s.bonus) + ' bonus credits)</li>';
|
||||
return '<li><b>' + name + '</b>: not yet this cycle (a $' + minUsd + '+ package counts)</li>';
|
||||
}
|
||||
function cardHtml(v) {
|
||||
const head = '<div class="card-head"><h3>⛽ Monthly Refuel</h3><span class="sub">' + (v.active ? 'streak: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') : 'not started') + '</span></div>';
|
||||
if (!v.active) {
|
||||
const lapsed = v.started ? '<p>Your last streak ended' + (v.misses && v.misses[0] ? ' after ' + esc(v.misses[0].day) : '') + '. Your next package of $' + v.minUsd.iap + '+ here (or $' + v.minUsd.linkspin + '+ on LinkSpin) starts it again at month 1.</p>' : '';
|
||||
return head + (lapsed || '<p>Refuel your ads every month and the bonus grows. A package of <b>$' + v.minUsd.iap + ' or more</b> here, or $' + v.minUsd.linkspin + ' or more on LinkSpin, starts your streak and sets your own refuel day.</p>')
|
||||
+ '<p class="small">Month 1 <b>+' + v.ladder.single[0] + '%</b> bonus ad credits, month 2 +' + v.ladder.single[1] + '%, month 3 +' + v.ladder.single[2] + '%, month 4 and up +' + v.ladder.single[3] + '%. Refuel both InstantAdPay and LinkSpin in the same cycle and each gets +' + v.ladder.both.join('%, +') + '%. It stacks on Five Dollar Friday and Wired Wednesday.</p>'
|
||||
+ '<button class="btn" type="button" data-fuel-buy>Start my streak</button>';
|
||||
}
|
||||
const c = v.cycle || {};
|
||||
const when = v.windowOpen
|
||||
? '<p><b>Your refuel window is open.</b> Refuel day: <b>' + esc(v.refuelDayLabel) + '</b>, grace to ' + esc(v.graceLabel) + ' (Central time). Your next refuel earns <b>+' + v.next.single + '%</b>, or +' + v.next.both + '% on each site when you refuel both.</p>'
|
||||
: '<p>Next refuel day: <b>' + esc(v.refuelDayLabel) + '</b> (Central time). The window opens ' + esc(v.opensLabel) + ' and the grace runs to ' + esc(v.graceLabel) + '.</p>';
|
||||
const sites = c.month ? '<p class="small" style="margin-bottom:2px">This cycle (month ' + c.month + (c.both ? ', both engines' : '') + '):</p><ul class="small" style="margin-top:0">' + siteLine('InstantAdPay', c.iap, v.minUsd.iap) + siteLine('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</ul>' : '';
|
||||
let twin = '';
|
||||
if (!v.windowOpen && c.month && !c.both) twin = '<p class="small">Refuel ' + (c.iap && c.iap.refueled ? 'LinkSpin ($' + v.minUsd.linkspin + '+)' : 'InstantAdPay ($' + v.minUsd.iap + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to <b>+' + v.next.secondEngine + '%</b>; the one you already refueled is topped up to match.</p>';
|
||||
let pit = '';
|
||||
if (v.pitStop) {
|
||||
const here = v.pitStop.iap ? 'available here (+' + v.pitStop.pct + '% on a $' + v.minUsd.iap + '+ top-up, once this cycle)' : v.pitStop.usedIap ? 'used here this cycle' : null;
|
||||
if (here) pit = '<p class="small"><b>Pit Stop:</b> ' + here + '. It keeps your ads running between refuel days; it does not count as your refuel.</p>';
|
||||
}
|
||||
const miss = '<p class="small muted">' + (v.freeMiss.available ? 'You have one free miss this year: if a grace passes, your streak is kept once.' : 'Your free miss for this year is used.') + (v.best > v.streak ? ' Best streak: ' + v.best + ' months.' : '') + '</p>';
|
||||
return head + when + sites + twin + pit + miss + '<button class="btn" type="button" data-fuel-buy>' + (v.windowOpen ? 'Refuel now' : 'Buy a package') + '</button>';
|
||||
}
|
||||
async function loadRefuelCard() {
|
||||
const card = $('rfCard'); if (!card) return;
|
||||
try {
|
||||
const v = await (await fetch('/api/my/refuel', { cache: 'no-store' })).json();
|
||||
window.FUEL.refuel = v;
|
||||
if (!v || !v.on) { card.hidden = true; return; }
|
||||
card.innerHTML = cardHtml(v); card.hidden = false;
|
||||
card.querySelectorAll('[data-fuel-buy]').forEach(b => b.addEventListener('click', goBuy));
|
||||
} catch (e) { card.hidden = true; }
|
||||
}
|
||||
window.FUEL.loadRefuelCard = loadRefuelCard;
|
||||
loadRefuelCard(); setInterval(loadRefuelCard, 300000);
|
||||
})();
|
||||
+7
-2
@@ -82,7 +82,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 },
|
||||
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 },
|
||||
{ key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 },
|
||||
{ key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 }
|
||||
{ key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 },
|
||||
// Monthly Refuel badges (2026-10-24): placeholder gauge art until the final art lands
|
||||
{ key: 'refuelStart', label: 'Engine Started', sub: 'first monthly refuel', img: '/badges/badge-refuelstart.jpg', ribbonY: 0.775, earnedOnly: true },
|
||||
{ key: 'refuel3', label: 'Refueled 3 months', sub: 'three monthly refuels in a row', img: '/badges/badge-refuel3.jpg', ribbonY: 0.775, earnedOnly: true },
|
||||
{ key: 'refuel6', label: 'Refueled 6 months', sub: 'six monthly refuels in a row', img: '/badges/badge-refuel6.jpg', ribbonY: 0.775, earnedOnly: true },
|
||||
{ key: 'refuel12', label: 'Refueled 12 months', sub: 'twelve monthly refuels in a row', img: '/badges/badge-refuel12.jpg', ribbonY: 0.775, earnedOnly: true }
|
||||
];
|
||||
let lastMilestones = [];
|
||||
function renderBadges(d) {
|
||||
@@ -91,7 +96,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
const strip = $('badgeStrip');
|
||||
if (!strip) return;
|
||||
$('badgeCard').hidden = false;
|
||||
strip.innerHTML = BADGES.map(b => {
|
||||
strip.innerHTML = BADGES.filter(b => !b.earnedOnly || reached.includes(b.key)).map(b => { // earnedOnly: shown once earned (refuel badges)
|
||||
const got = reached.includes(b.key);
|
||||
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
|
||||
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 63 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
+3
-1
@@ -183,6 +183,7 @@
|
||||
<div class="card" id="phLaunch" hidden></div>
|
||||
<div class="card" id="fdfCard" hidden></div>
|
||||
<div class="card" id="wwCard" hidden></div>
|
||||
<div class="card" id="rfCard" hidden aria-live="polite"></div>
|
||||
<div class="card" id="gpNudge" hidden></div>
|
||||
<div class="card gs" id="gsCard" hidden>
|
||||
<div class="card-head"><h3>Getting started</h3><span class="sub" id="gsSub"></span></div>
|
||||
@@ -1216,7 +1217,8 @@
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20261016p"></script>
|
||||
<script src="/assets/support.js?v=20261016a"></script>
|
||||
<script src="/assets/my.js?v=20261023cv"></script>
|
||||
<script src="/assets/my.js?v=20261024rf"></script>
|
||||
<script src="/assets/fuel.js?v=20261024rf"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// Monthly Refuel streak (refuel.js): every rule on throwaway data. JSON store in a temp dir, stubbed accounts/ads/mail,
|
||||
// the real db.js lock (per-process queue without DATABASE_URL) and marks.js (per-process claims without a DB).
|
||||
// Run: node qa/refuel.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, '..');
|
||||
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.stack.split('\n').slice(0, 2).join(' | ')); } }
|
||||
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
|
||||
const db = require(path.join(ROOT, 'db.js'));
|
||||
|
||||
// a timestamp at a given Central-time day + hour (handles CST and CDT)
|
||||
function ct(day, hour) {
|
||||
const [y, m, d] = day.split('-').map(Number);
|
||||
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + off, 0); const back = new Date(ts).toLocaleString('en-CA', { timeZone: 'America/Chicago', hour12: false }); if (back.startsWith(day) && Number(back.split(', ')[1].slice(0, 2)) % 24 === (hour == null ? 12 : hour)) return ts; }
|
||||
throw new Error('no ts for ' + day);
|
||||
}
|
||||
|
||||
function world(cfg) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refuel-'));
|
||||
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}), earned: [], inbox: [], mail: [], badges: [], feed: [] };
|
||||
W.marks = fresh('marks.js'); W.marks.init({});
|
||||
W.deps = {
|
||||
dataDir: dir, db, marks: W.marks, siteConfig: () => W.cfg,
|
||||
accounts: { byMemberId: async id => id === 7 ? { email: 'm@x.test', memberId: 7, username: 'mike' } : null, positionByMember: async id => id === 70 ? { email: 'm@x.test', memberId: 70 } : null, byEmail: async e => ({ email: e, username: e === 'm@x.test' ? 'mike' : null, memberId: 9 }) },
|
||||
ads: { addEarned: async (email, credits, opts) => { W.earned.push({ email, credits, opts }); } },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
|
||||
drip: { isUnsubscribed: async () => false, unsubUrl: e => 'https://instantadpay.com/unsubscribe?e=' + e },
|
||||
featuredPerDay: () => 40,
|
||||
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
|
||||
badge: async (email, key) => { W.badges.push(key); },
|
||||
feed: async text => { W.feed.push(text); },
|
||||
};
|
||||
W.R = fresh('refuel.js'); W.R.init(W.deps);
|
||||
W.buy = (site, tx, cents, credits, day, hour, email) => W.R.record({ site, email: email || 'm@x.test', tx, cents, credits, ts: ct(day, hour) });
|
||||
W.out = site => W.R.outbox(site);
|
||||
W.store = () => JSON.parse(fs.readFileSync(path.join(dir, 'refuel.json'), 'utf8'));
|
||||
W.rec = () => W.store().members['m@x.test'];
|
||||
W.grants = () => Object.values(W.store().outbox).filter(r => r.kind === 'grant');
|
||||
return W;
|
||||
}
|
||||
const D = (day, k) => new Date(Date.UTC(...day.split('-').map((v, i) => i === 1 ? v - 1 : Number(v))) + k * 864e5).toISOString().slice(0, 10);
|
||||
|
||||
(async () => {
|
||||
await t('MASTER SWITCH off: nothing recorded, granted, reminded or shown', async () => {
|
||||
const W = world({ refuelStreak: '0' });
|
||||
const r = await W.buy('iap', '0xa', 2000, 2000, '2026-11-02');
|
||||
assert.deepStrictEqual(r, { on: false });
|
||||
assert.ok(!fs.existsSync(path.join(W.dir, 'refuel.json')));
|
||||
assert.deepStrictEqual(await W.R.view('m@x.test'), { on: false });
|
||||
assert.deepStrictEqual(await W.R.tick(), { on: false });
|
||||
assert.strictEqual(await W.R.streakLine('m@x.test'), null);
|
||||
assert.strictEqual(await W.R.onIapPurchase({ type: 'Purchase', buyerId: 7, tx: '0xz', priceCents: 2000, creditAmount: 2000, ts: Date.now() }), null);
|
||||
assert.strictEqual(W.earned.length + W.feed.length + W.badges.length, 0);
|
||||
});
|
||||
await t('first counted refuel: month 1 +10%, purchased-grade, labelled, refuel day +30 (Central), Engine Started badge, feed line', async () => {
|
||||
const W = world();
|
||||
const r = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 1);
|
||||
assert.strictEqual(W.earned.length, 1); const g = W.earned[0];
|
||||
assert.strictEqual(g.credits, 200); assert.ok(g.opts.purchased); assert.strictEqual(g.opts.log.kind, 'bonus'); assert.ok(/^Refuel streak month 1: \+10% on your \$20 package$/.test(g.opts.log.note), g.opts.log.note);
|
||||
const v = await W.R.view('m@x.test', ct('2026-11-03'));
|
||||
assert.strictEqual(v.refuelDay, '2026-12-02'); assert.strictEqual(v.opensDay, '2026-11-27'); assert.strictEqual(v.graceEnd, '2026-12-07');
|
||||
assert.strictEqual(v.streak, 1); assert.ok(v.engineUnlocked); assert.ok(!v.windowOpen);
|
||||
assert.deepStrictEqual(W.badges, ['refuelStart']);
|
||||
assert.strictEqual(W.feed.length, 1); assert.ok(/@mike<\/b> refueled InstantAdPay · streak 1/.test(W.feed[0]), W.feed[0]);
|
||||
});
|
||||
await t('below the floor: $5 on InstantAdPay, $20 on LinkSpin do not count', async () => {
|
||||
const W = world();
|
||||
assert.strictEqual((await W.buy('iap', '0x5', 500, 500, '2026-11-02')).kind, 'below');
|
||||
assert.strictEqual((await W.buy('linkspin', '0x6', 2000, 2000, '2026-11-02')).kind, 'below');
|
||||
assert.strictEqual(W.earned.length, 0); assert.strictEqual((await W.R.view('m@x.test')).started, false);
|
||||
});
|
||||
await t('both engines: second site gets the both-rate, first site topped up by the difference only; outbox per site', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
const r = await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-09');
|
||||
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.both, true);
|
||||
const ls = await W.out('linkspin'); assert.strictEqual(ls.length, 1); assert.strictEqual(ls[0].payload.credits, 375); assert.strictEqual(ls[0].ref, 'rf:linkspin:0xL1');
|
||||
const top = W.earned.find(e => /Twin Engine top-up/.test(e.opts.log.note)); assert.ok(top, 'top-up applied'); assert.strictEqual(top.credits, 100);
|
||||
assert.strictEqual(W.earned.reduce((s, e) => s + e.credits, 0), 300); // 200 + 100 = 15% of 2000
|
||||
assert.ok(/refueled both engines · streak 1/.test(W.feed[1]), W.feed[1]);
|
||||
const v = await W.R.view('m@x.test', ct('2026-11-10'));
|
||||
assert.ok(v.cycle.both); assert.strictEqual(v.cycle.iap.pct, 15); assert.strictEqual(v.cycle.linkspin.bonus, 375);
|
||||
});
|
||||
await t('Pit Stop: half the current rate, once per site per cycle, not a refuel, not posted', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
const p1 = await W.buy('iap', '0xp1', 5000, 5500, '2026-11-12');
|
||||
assert.strictEqual(p1.kind, 'pitstop'); assert.strictEqual(W.earned[1].credits, 275); // 10% / 2 = 5% of 5,500
|
||||
assert.ok(/Pit Stop: \+5% \(half your \+10% streak rate\)/.test(W.earned[1].opts.log.note));
|
||||
const p2 = await W.buy('iap', '0xp2', 2000, 2000, '2026-11-13'); assert.strictEqual(p2.kind, 'none');
|
||||
assert.strictEqual(W.earned.length, 2); assert.strictEqual(W.feed.length, 1);
|
||||
assert.strictEqual((await W.R.view('m@x.test', ct('2026-11-13'))).streak, 1, 'a pit stop is not a counted refuel');
|
||||
// LinkSpin joins (both engines, 15%), then a LinkSpin Pit Stop at half the BOTH rate (7.5%)
|
||||
await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-14');
|
||||
const p3 = await W.buy('linkspin', '0xL2', 10000, 10000, '2026-11-15'); assert.strictEqual(p3.kind, 'pitstop');
|
||||
const lsg = (await W.out('linkspin')).find(x => x.ref === 'rfpit:linkspin:0xL2'); assert.strictEqual(lsg.payload.credits, 750);
|
||||
});
|
||||
await t('window: day 24 is a Pit Stop/none, day 25 (window open) is month 2 at +15%', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
assert.strictEqual((await W.buy('iap', '0x2', 2000, 2000, D('2026-11-02', 24))).kind, 'pitstop');
|
||||
const r = await W.buy('iap', '0x3', 2000, 2000, D('2026-11-02', 25));
|
||||
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 2); assert.strictEqual(W.earned[2].credits, 300);
|
||||
assert.strictEqual(W.rec().dueDay, D(D('2026-11-02', 25), 30), 'next due 30 days after THIS refuel');
|
||||
});
|
||||
await t('grace: refuel on the last grace day keeps the streak; ladder m3 +20%, m4 +25%, m5 stays +25%', async () => {
|
||||
const W = world();
|
||||
let day = '2026-11-02'; await W.buy('iap', 't1', 2000, 2000, day);
|
||||
const pcts = [];
|
||||
for (let k = 2; k <= 5; k++) { day = D(day, 35); const r = await W.buy('iap', 't' + k, 2000, 2000, day); assert.strictEqual(r.month, k, 'month ' + k); pcts.push(W.earned[W.earned.length - 1].credits / 20); }
|
||||
assert.deepStrictEqual(pcts, [15, 20, 25, 25]);
|
||||
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3']);
|
||||
});
|
||||
await t('missed grace: the free miss keeps the streak once; the next package counts as month k+1; a second miss inside 365 days resets', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', 't1', 2000, 2000, '2026-01-05');
|
||||
await W.buy('iap', 't2', 2000, 2000, '2026-02-04'); // month 2, due 03-06, grace to 03-11
|
||||
const r3 = await W.buy('iap', 't3', 2000, 2000, '2026-03-12'); // one day late: free miss covers it
|
||||
assert.strictEqual(r3.kind, 'refuel'); assert.strictEqual(r3.month, 3);
|
||||
const rec = W.rec(); assert.strictEqual(rec.misses[0].free, true); assert.strictEqual(rec.freeMissDay, '2026-03-11');
|
||||
const r4 = await W.buy('iap', 't4', 2000, 2000, D('2026-03-12', 36)); // late again, inside 365 days: reset
|
||||
assert.strictEqual(r4.month, 1); assert.strictEqual(W.rec().misses[0].free, false);
|
||||
});
|
||||
await t('free miss comes back after 365 days', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', 'a1', 2000, 2000, '2026-01-05');
|
||||
await W.buy('iap', 'a2', 2000, 2000, '2026-02-12'); // late: free miss used (grace ended 02-09)
|
||||
assert.strictEqual(W.rec().freeMissDay, '2026-02-09');
|
||||
let day = '2026-02-12', k = 2;
|
||||
while (day < '2027-02-01') { day = D(day, 30); k++; await W.buy('iap', 'a' + k, 2000, 2000, day); }
|
||||
const before = W.rec().streak; const late = D(W.rec().graceEnd, 1);
|
||||
const r = await W.buy('iap', 'late', 2000, 2000, late);
|
||||
assert.strictEqual(r.month, before + 1, 'kept by a fresh free miss'); assert.strictEqual(W.rec().misses[0].free, true);
|
||||
});
|
||||
await t('m4+ both engines: +40% each and one free Featured day on InstantAdPay, once per cycle', async () => {
|
||||
const W = world();
|
||||
let day = '2026-11-02';
|
||||
for (let k = 1; k <= 4; k++) { await W.buy('iap', 'i' + k, 2000, 2000, day); if (k < 4) day = D(day, 30); }
|
||||
await W.buy('linkspin', 'L4', 2500, 2500, D(day, 2));
|
||||
assert.strictEqual((await W.out('linkspin')).find(x => x.ref === 'rf:linkspin:L4').payload.credits, 1000);
|
||||
const feat = W.earned.filter(e => /free Featured day/.test(e.opts.log.note)); assert.strictEqual(feat.length, 1); assert.strictEqual(feat[0].credits, 40);
|
||||
const top = W.earned.find(e => e.opts.log.ref === 'rftop:iap:L4'); assert.strictEqual(top.credits, 800 - 500);
|
||||
});
|
||||
await t('stacking: the streak grant is its own labelled grant (Friday and Wednesday add theirs untouched)', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', '0xfri', 2000, 2000, '2026-11-06'); // a Friday
|
||||
assert.strictEqual(W.earned.length, 1); assert.ok(/^rf:iap:0xfri$/.test(W.earned[0].opts.log.ref));
|
||||
assert.ok(!/Friday|Wednesday/.test(W.earned[0].opts.log.note));
|
||||
});
|
||||
await t('idempotent: the same tx twice = one decision, one grant, one feed line', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
const again = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
assert.ok(again.repeat); assert.strictEqual(W.earned.length, 1); assert.strictEqual(W.feed.length, 1);
|
||||
});
|
||||
await t('two concurrent workers (two module copies, one store): both engines at once, no double grant', async () => {
|
||||
const W = world();
|
||||
const B = fresh('refuel.js'); B.init(W.deps);
|
||||
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||
const tsL = ct('2026-11-05'); const tsI = ct('2026-11-06');
|
||||
await Promise.all([
|
||||
W.R.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
|
||||
B.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
|
||||
B.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
|
||||
W.R.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
|
||||
]);
|
||||
await Promise.all([W.R.drainLocal(), B.drainLocal()]);
|
||||
const refs = W.earned.map(e => e.opts.log.ref).sort();
|
||||
assert.deepStrictEqual(refs, ['rf:iap:0x1', 'rfpit:iap:0xP', 'rftop:iap:0xL'], JSON.stringify(refs));
|
||||
assert.strictEqual((await W.out('linkspin')).length, 1);
|
||||
assert.strictEqual(W.feed.length, 2);
|
||||
});
|
||||
await t('linked position purchase counts for the owner; Central day: 11:30 PM CT Oct 31 is Oct 31 (UTC says Nov 1)', async () => {
|
||||
const W = world();
|
||||
const ts = ct('2026-10-31', 23) + 30 * 60000;
|
||||
assert.strictEqual(new Date(ts).toISOString().slice(0, 10), '2026-11-01');
|
||||
const r = await W.R.onIapPurchase({ type: 'Purchase', buyerId: 70, tx: '0xpos', priceCents: 2000, creditAmount: 2000, ts });
|
||||
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.day, '2026-10-31');
|
||||
assert.strictEqual(W.rec().dueDay, '2026-11-30', 'across the Nov 1 clock change: exactly 30 calendar days');
|
||||
});
|
||||
await t('Refuel Day promo: off by default; on, the 1st (Central) adds its own grant to a counted refuel only', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', 'd1', 2000, 2000, '2026-12-01'); assert.strictEqual(W.earned.length, 1);
|
||||
const W2 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||
await W2.buy('iap', 'd1', 2000, 2000, '2026-12-01');
|
||||
assert.deepStrictEqual(W2.earned.map(e => e.credits), [200, 200]); assert.ok(/Refuel Day \(the 1st\)/.test(W2.earned[1].opts.log.note));
|
||||
const W3 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||
await W3.buy('iap', 'e1', 2000, 2000, '2026-11-20');
|
||||
const pit = await W3.buy('iap', 'e2', 2000, 2000, '2026-12-01', 1); // 1 AM CT on the 1st, but a Pit Stop: no promo
|
||||
assert.strictEqual(pit.kind, 'pitstop'); assert.ok(!W3.earned.some(e => /Refuel Day/.test(e.opts.log.note)));
|
||||
const W4 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||
await W4.buy('iap', 'f1', 2000, 2000, '2026-11-30', 23); // 11 PM CT Nov 30 = Dec 1 in UTC: not the 1st
|
||||
assert.strictEqual(W4.earned.length, 1);
|
||||
});
|
||||
await t('badges at 3, 6 and 12 months, once each', async () => {
|
||||
const W = world(); let day = '2026-01-02';
|
||||
for (let k = 1; k <= 13; k++) { await W.buy('iap', 'b' + k, 2000, 2000, day); day = D(day, 30); }
|
||||
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3', 'refuel6', 'refuel12']);
|
||||
assert.deepStrictEqual((await W.R.badgesOf('m@x.test')).sort(), ['refuel12', 'refuel3', 'refuel6', 'refuelStart']);
|
||||
});
|
||||
await t('reminders: 5 days before, on the day, last call; from the home site; once; after the reminder hour; none once refueled', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', 'r1', 2000, 2000, '2026-11-02'); // due 12-02
|
||||
await W.R.tick(ct('2026-11-27', 8)); assert.strictEqual(W.inbox.filter(m => /refuel day is/i.test(m.subject)).length, 0, 'not before 9 AM CT');
|
||||
await W.R.tick(ct('2026-11-27', 10)); await W.R.tick(ct('2026-11-27', 15));
|
||||
const soon = W.inbox.filter(m => m.subject === 'Your refuel day is Wed, Dec 2'); assert.strictEqual(soon.length, 1);
|
||||
assert.ok(W.mail.some(m => m.subject === 'Your refuel day is Wed, Dec 2' && /Stop these emails/.test(m.text)));
|
||||
await W.R.tick(ct('2026-12-02', 10)); assert.ok(W.inbox.some(m => m.subject === 'Today is your refuel day'));
|
||||
await W.R.tick(ct('2026-12-07', 10)); const last = W.inbox.find(m => /Last call/.test(m.subject)); assert.ok(last && /free miss/.test(last.html));
|
||||
// LinkSpin home: the reminder goes to LinkSpin's outbox instead
|
||||
const W2 = world(); await W2.buy('linkspin', 'L1', 2500, 2500, '2026-11-02');
|
||||
await W2.R.tick(ct('2026-11-27', 10));
|
||||
assert.ok((await W2.out('linkspin')).some(x => x.kind === 'reminder' && x.payload.remind === 'soon')); assert.strictEqual(W2.inbox.length, 0);
|
||||
// refueled inside the window: no "on the day" reminder
|
||||
const W3 = world(); await W3.buy('iap', 'x1', 2000, 2000, '2026-11-02'); await W3.buy('iap', 'x2', 2000, 2000, '2026-11-28');
|
||||
await W3.R.tick(ct('2026-12-02', 10)); assert.ok(!W3.inbox.some(m => /refuel day/i.test(m.subject) && !/Refuel counted/.test(m.subject)));
|
||||
});
|
||||
await t('weekly roundup: Monday after 9 AM CT, last Mon..Sun, once per week, skipped when nobody refueled', async () => {
|
||||
const W = world();
|
||||
await W.buy('iap', 'w1', 2000, 2000, '2026-11-03'); // Tue
|
||||
await W.buy('iap', 'w2', 2000, 2000, '2026-11-05', 12, 'z@x.test');
|
||||
W.feed.length = 0;
|
||||
await W.R.tick(ct('2026-11-09', 8)); assert.strictEqual(W.feed.length, 0, 'before 9 AM');
|
||||
await W.R.tick(ct('2026-11-09', 10)); await W.R.tick(ct('2026-11-09', 11));
|
||||
assert.strictEqual(W.feed.length, 1); assert.ok(/Refueled this week:<\/b> 2 members, 2 new streaks, longest streak 1/.test(W.feed[0]), W.feed[0]);
|
||||
await W.R.tick(ct('2026-11-16', 10)); assert.strictEqual(W.feed.length, 1, 'nobody refueled 11-09..11-15: skipped');
|
||||
});
|
||||
await t('view + streak line: next bonus, Pit Stop status, free miss', async () => {
|
||||
const W = world();
|
||||
const v0 = await W.R.view('m@x.test'); assert.ok(v0.on && !v0.started && v0.next.single === 10 && v0.next.both === 15);
|
||||
await W.buy('iap', 'v1', 2000, 2000, '2026-11-02');
|
||||
const v = await W.R.view('m@x.test', ct('2026-11-04'));
|
||||
assert.deepStrictEqual(v.next, { month: 1, secondEngine: 15 }); assert.strictEqual(v.pitStop.pct, 5); assert.ok(v.pitStop.iap && !v.pitStop.linkspin);
|
||||
assert.ok(v.freeMiss.available);
|
||||
const sl = await W.R.streakLine('m@x.test'); assert.ok(/month 1, next refuel day Wed, Dec 2/.test(sl.text), sl.text);
|
||||
for (const s of [sl.text, JSON.stringify(v)]) assert.ok(!/—/.test(s));
|
||||
});
|
||||
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||
process.exit(fails ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,405 @@
|
||||
// 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% (+ one free Featured day on InstantAdPay at m4+)
|
||||
// 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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
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.featuredPerDay ? X.featuredPerDay() : 40) || 40);
|
||||
g('iap', 'featured', per, 'Twin Engine month ' + k + ': one free Featured day (' + 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 });
|
||||
}
|
||||
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: one free Featured day';
|
||||
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>That is the price of one Featured day: book it under Campaigns whenever you like.</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, 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 || {}),
|
||||
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: /, '')) };
|
||||
}
|
||||
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 = { 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 };
|
||||
@@ -73,6 +73,7 @@ const starter = require('./starter'); // member welcome offer from the games (20
|
||||
const wednesday = require('./wednesday'); // Wired Wednesday: +25% on $10+ packs, wired into a visits campaign (2026-09-29)
|
||||
const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked Sat-Thu by solo + video (2026-09-26)
|
||||
const refill = require('./refill');
|
||||
const refuel = require('./refuel'); // the Monthly Refuel streak, one per member across InstantAdPay + LinkSpin (Fuel Your Offers, 2026-10-24); switch refuelStreak, default off
|
||||
const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20)
|
||||
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
|
||||
const override = require('./override'); // level-4 override: weekly dry-run report; the payer ships OFF (overrideMode 'live' + overrideGoLive + OVERRIDE_PAYER_KEY), 2026-10-23
|
||||
@@ -536,6 +537,7 @@ async function boot() {
|
||||
Promise.all([friday.onEvent(ev).catch(e => { console.error('friday bonus', e.message); return null; }), gamepass.onEvent(ev).catch(e => { console.error('gamepass order', e.message); return null; })])
|
||||
.then(([bonus, gp]) => fridayPassPerk(ev, bonus, gp)).catch(e => console.error('friday pass perk', e.message));
|
||||
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
|
||||
refuel.onIapPurchase(ev).catch(e => console.error('refuel streak', e.message)); // its own bonus, stacked on Friday/Wednesday; no-op while refuelStreak is off
|
||||
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
|
||||
}).catch(e => console.error('marks claim', e.message));
|
||||
} });
|
||||
@@ -546,7 +548,7 @@ async function boot() {
|
||||
messages.init({ dataDir: DATA_DIR });
|
||||
reports.init({ dataDir: DATA_DIR });
|
||||
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' });
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22)
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, refuelOn: () => refuel.cfg().on, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; } }); // pass tiers fact follows sovTiers (2026-10-22)
|
||||
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
||||
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
||||
@@ -570,7 +572,7 @@ async function boot() {
|
||||
// Campaign refill notices: an advertiser is told when an ad is nearly out and when it has stopped,
|
||||
// with the bonus ladder in the same message, and every send is watched for what they did next.
|
||||
refill.init({
|
||||
dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks,
|
||||
dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, streakLine: email => refuel.streakLine(email),
|
||||
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@instantadpay.com', [to], subject, html, 'notice'); },
|
||||
});
|
||||
@@ -593,6 +595,15 @@ async function boot() {
|
||||
console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2'));
|
||||
});
|
||||
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes
|
||||
// the Monthly Refuel streak (refuel.js): source of truth for both sites; LinkSpin reports purchases and collects its grants
|
||||
// through /api/partner/refuel/*. Feed lines go to the payments topic like other InstantAdPay feed lines.
|
||||
refuel.init({ dataDir: DATA_DIR, db, marks, siteConfig, accounts, ads, mailer, drip,
|
||||
featuredPerDay: () => ads.rates().featuredPerDay || 40,
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
|
||||
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
|
||||
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
|
||||
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 120000);
|
||||
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 10 * 60 * 1000);
|
||||
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
|
||||
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
|
||||
setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 60 * 1000);
|
||||
@@ -755,6 +766,10 @@ function siteConfig() {
|
||||
fridayBonusPct: '20', // bonus credits on any $5+ package bought on a Friday, Central
|
||||
fridayStart: '2026-09-25', // the first Five Dollar Friday
|
||||
wednesdayPromo: '1', wednesdayBonusPct: '25', wednesdayMinCents: '2000', wednesdayStart: '2026-09-30', // Wired Wednesday (Marty, 2026-09-29)
|
||||
refuelStreak: '0', // the Monthly Refuel streak master switch (Fuel Your Offers, 2026-10-24): '0' = nothing counted or granted, no reminders, cards hidden
|
||||
refuelReminders: '1', refuelReminderHour: '9', // refuel reminders (email + on-site notice) 5 days before, on the day, last call; Central hour
|
||||
refuelDayPromo: '0', refuelDayPct: '10', // optional network Refuel Day bonus on the 1st of each month (Central), off by default
|
||||
refuelMinIapCents: '2000', refuelMinLsCents: '2500', // what counts as a refuel: $20+ on InstantAdPay, $25+ on LinkSpin
|
||||
wednesdayNotice: '0', wednesdayKick: '0', // the Tuesday email/notice and the Wednesday Telegram kickoff stay off until Marty approves the copy
|
||||
launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark
|
||||
aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation
|
||||
@@ -1469,7 +1484,8 @@ async function telegramSendPhoto(chatId, jpeg, caption, threadId) {
|
||||
rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body);
|
||||
});
|
||||
}
|
||||
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'] };
|
||||
const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'], fridays: ['Five Fridays', 'five Five Dollar Fridays in a row'], gamepass: ['Game Pass', 'Game Pass holder'],
|
||||
refuelStart: ['Engine Started', 'first monthly refuel'], refuel3: ['Refueled 3 months', 'three monthly refuels in a row'], refuel6: ['Refueled 6 months', 'six monthly refuels in a row'], refuel12: ['Refueled 12 months', 'twelve monthly refuels in a row'] };
|
||||
const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json');
|
||||
function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } }
|
||||
// Post a member's badge to the payments topic + General ONCE ever (the same card and caption as an unlock). Used by the
|
||||
@@ -2746,6 +2762,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (bc >= 5) reached.push('level3');
|
||||
try { if (out.memberId && friday.earnedBadge(out.memberId)) reached.push('fridays'); } catch (e) {} // five Five Dollar Fridays in a row
|
||||
try { if (out.email && gamepass.flag(out.email).until) reached.push('gamepass'); } catch (e) {} // ever held a Game Pass (2026-10-22)
|
||||
try { if (out.email) for (const k of await refuel.badgesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // Monthly Refuel badges (2026-10-24)
|
||||
try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned
|
||||
out.milestonesReached = reached;
|
||||
if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached);
|
||||
@@ -3183,6 +3200,20 @@ const server = http.createServer(async (req, res) => {
|
||||
// -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET
|
||||
// over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing
|
||||
// accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js).
|
||||
// -- Monthly Refuel partner calls from LinkSpin (signed like the registry): a LinkSpin package to record (the answer carries
|
||||
// LinkSpin's grants for that member), the outbox of LinkSpin grants + reminders, acks, and one member's status for its card
|
||||
if (p.startsWith('/api/partner/refuel/') && req.method === 'POST') {
|
||||
const sg = await readLsSigned(req, 200000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const b = sg.body; const op = p.slice('/api/partner/refuel/'.length);
|
||||
if (op === 'purchase') {
|
||||
const r = await refuel.record({ site: 'linkspin', email: b.email, tx: b.tx, cents: b.cents, credits: b.credits, ts: b.ts });
|
||||
return json(res, 200, Object.assign({ ok: true }, r, { items: r.on ? await refuel.outbox('linkspin', b.email) : [] }));
|
||||
}
|
||||
if (op === 'outbox') return json(res, 200, { ok: true, on: refuel.cfg().on, items: refuel.cfg().on ? await refuel.outbox('linkspin') : [] });
|
||||
if (op === 'ack') return json(res, 200, { ok: true, acked: await refuel.ack('linkspin', Array.isArray(b.refs) ? b.refs : []) });
|
||||
if (op === 'status') return json(res, 200, Object.assign({ ok: true }, await refuel.view(b.email)));
|
||||
return json(res, 404, { error: 'unknown op' });
|
||||
}
|
||||
if (p === '/api/partner/registry' && req.method === 'POST') {
|
||||
const sg = await readLsSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const b = sg.body;
|
||||
@@ -4696,6 +4727,12 @@ const server = http.createServer(async (req, res) => {
|
||||
return res.end();
|
||||
}
|
||||
// Campaigns > Conversion tracking: the member's goals and counts live on LinkSpin; these proxy the signed calls
|
||||
// -- Monthly Refuel (2026-10-24): the member's refuel day, streak, next bonus and Pit Stop status ({ on:false } while switched off)
|
||||
if (p === '/api/my/refuel' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
return json(res, 200, await refuel.view(s.email));
|
||||
}
|
||||
if (p === '/api/my/conversions' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
@@ -4973,6 +5010,18 @@ const server = http.createServer(async (req, res) => {
|
||||
v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email };
|
||||
return json(res, 200, v);
|
||||
}
|
||||
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel: settings, members on a streak, grants by kind, recent outbox rows
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await refuel.stats());
|
||||
}
|
||||
if (p === '/api/admin/refuel/tick' && req.method === 'POST') { // run the daily pass now (misses, reminders, outbox)
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await refuel.tick());
|
||||
}
|
||||
if (p === '/api/admin/refuel/member' && req.method === 'GET') { // one member's card, as they see it
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await refuel.view(String(u.searchParams.get('email') || '')));
|
||||
}
|
||||
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, refill.stats());
|
||||
|
||||
Reference in New Issue
Block a user