Files

246 lines
18 KiB
JavaScript

// 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 a 100-credit Featured bonus 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 => /Featured bonus/.test(e.opts.log.note)); assert.strictEqual(feat.length, 1); assert.strictEqual(feat[0].credits, 100);
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);
})();