diff --git a/qa/refill.test.cjs b/qa/refill.test.cjs new file mode 100644 index 0000000..4684da7 --- /dev/null +++ b/qa/refill.test.cjs @@ -0,0 +1,75 @@ +// Refill notice copy + deploy-overlap claim (refill.js) on throwaway data. Run: node qa/refill.test.cjs +'use strict'; +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const assert = require('assert'); + +const ROOT = path.join(__dirname, '..'); +let fails = 0, n = 0; +async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } } +function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); } +const now = Date.now(); + +function world(dir, cfg) { + const W = { inbox: [], mail: [], cfg: cfg || {} }; + W.campaigns = [ + { id: 1, owner: 'a@x.test', type: 'banner', name: 'Alpha', budget: 1000, spent: 1000, accrued: 0, imps: 5000, clicks: 40, status: 'out', created: now - 30 * 864e5 }, + { id: 2, owner: 'b@x.test', type: 'text', name: 'Bravo', budget: 1000, spent: 850, accrued: 0, imps: 8500, clicks: 9, status: 'active', created: now - 30 * 864e5 }, + ]; + W.deps = { + dataDir: dir, siteConfig: () => W.cfg, + ads: { adminList: async () => W.campaigns.map(c => Object.assign({}, c)), rates: () => ({ videoTiers: [] }) }, + accounts: { byEmail: async e => ({ email: e, memberId: 5 }), positions: async () => [] }, + chain: { recentEvents: () => [] }, + mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } }, + drip: { isUnsubscribed: async () => false }, + creditsFor: async () => 300, + message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); }, + }; + return W; +} + +(async () => { + await t('bonus block names Five Dollar Friday AND Wired Wednesday ($20 floor, +25%)', async () => { + const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-'))); + const r = fresh('refill.js'); r.init(W.deps); + const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300); + assert.ok(/Five Dollar Friday: any package from \$5 up/.test(m.text), 'friday text'); + assert.ok(/Wired Wednesday: any package from \$20 up, bought on a Wednesday \(Central time\), earns an extra 25%/.test(m.text), 'wednesday text'); + assert.ok(/Wired Wednesday:<\/b>/.test(m.html), 'wednesday html'); + assert.ok(!/—/.test(m.text + m.html), 'no em dash'); + }); + await t('Wednesday follows its settings (off, other floor and pct)', async () => { + const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')), { wednesdayPromo: '0' }); + const r = fresh('refill.js'); r.init(W.deps); + let m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300); + assert.ok(!/Wired Wednesday/.test(m.text)); + W.cfg = { wednesdayBonusPct: '30', wednesdayMinCents: '5000', fridayPromo: '0' }; + m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300); + assert.ok(/from \$50 up.*extra 30%/.test(m.text) && !/Five Dollar Friday/.test(m.text)); + }); + await t('streak hook line (stage 2) lands in text and html; absent hook changes nothing', async () => { + const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-'))); + const r = fresh('refill.js'); r.init(Object.assign({}, W.deps, { streakLine: async e => e === 'a@x.test' ? { text: 'Refuel streak: 2 months.', html: 'Refuel streak: 2 months.' } : null })); + const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300); + assert.ok(/Refuel streak: 2 months\./.test(m.text) && /Refuel streak:<\/b>/.test(m.html)); + const m2 = await r.compose('b@x.test', [W.campaigns[1]], 'low', 300); + assert.ok(!/Refuel streak/.test(m2.text)); + }); + await t('two app copies (shared claims): each owner gets one message', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')); + const W = world(dir); + const marks = fresh('marks.js'); marks.init({}); // no DB: one process-wide set stands in for event_marks + const A = fresh('refill.js'); A.init(Object.assign({}, W.deps, { marks })); + const B = fresh('refill.js'); B.init(Object.assign({}, W.deps, { marks })); + await Promise.all([A.tick(), B.tick()]); + const per = {}; for (const x of W.inbox) per[x.to] = (per[x.to] || 0) + 1; + assert.deepStrictEqual(per, { 'a@x.test': 1, 'b@x.test': 1 }, JSON.stringify(per)); + assert.strictEqual(W.mail.length, 2); + await Promise.all([A.tick(), B.tick()]); + assert.strictEqual(W.inbox.length, 2, 'nothing repeats on later passes'); + }); + console.log('\n' + (n - fails) + '/' + n + ' passed'); + process.exit(fails ? 1 : 0); +})(); diff --git a/qa/run.sh b/qa/run.sh index dcb7c6d..72892f4 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -13,6 +13,7 @@ # bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos) # bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data) # bash qa/run.sh convpixel # conversion pixel: lsclk click ids on /api/ads/click, signed push to a MOCK LinkSpin, own-click self flag, Campaigns > Conversion tracking + cost per goal, LinkSpin down (local copy, throwaway data) +# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data) # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. set -u @@ -57,6 +58,8 @@ elif [ "$MODE" = "login-queue" ]; then node qa/login-queue-sql.cjs || status=1 elif [ "$MODE" = "convpixel" ]; then node qa/convpixel.test.mjs || status=1 +elif [ "$MODE" = "fuel" ]; then + for f in qa/refill.test.cjs qa/refuel*.test.cjs; do [ -f "$f" ] && { node "$f" || status=1; }; done elif [ "$MODE" = "override" ]; then node qa/override.test.cjs || status=1 elif [ "$MODE" = "gamepass-games" ]; then diff --git a/refill.js b/refill.js index 113f1ac..9de3f17 100644 --- a/refill.js +++ b/refill.js @@ -10,6 +10,10 @@ // // Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget // delivered that counts as "running low". +// +// 2026-10-24 (Fuel Your Offers): the bonus block names Wired Wednesday next to Five Dollar Friday, and takes +// the member's refuel-streak line from X.streakLine(owner) -> { text, html } | null when the streak is on. +// Every send is claimed first (marks.js), so the two app copies of a deploy never both write to a person. 'use strict'; const fs = require('fs'); const path = require('path'); @@ -32,6 +36,9 @@ function cfg() { lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)), fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1', fridayPct: Number(c.fridayBonusPct) || 20, + wedOn: String(c.wednesdayPromo == null ? '1' : c.wednesdayPromo) === '1', + wedPct: Math.max(0, Number(c.wednesdayBonusPct) || 25), + wedMinUsd: Math.max(0, Number(c.wednesdayMinCents) || 2000) / 100, }; } @@ -61,21 +68,34 @@ const PACKS = [ { price: 500, credits: 70000, bonus: 40 }, ]; -function ladderText() { +// the day bonuses, one line each; Friday and Wednesday never fall on the same day +function dayBonusLines() { + const c = cfg(); const out = []; + if (c.fridayOn) out.push({ title: 'Five Dollar Friday', body: 'any package from $5 up, bought on a Friday (Central time), earns an extra ' + c.fridayPct + '% in credits on top of the above.' }); + if (c.wedOn) out.push({ title: 'Wired Wednesday', body: 'any package from $' + c.wedMinUsd + ' up, bought on a Wednesday (Central time), earns an extra ' + c.wedPct + '% in credits, wired in the moment it settles.' }); + return out; +} +async function streakLine(owner) { + if (typeof X.streakLine !== 'function' || !owner) return null; + try { return await X.streakLine(owner); } catch (e) { return null; } +} +function ladderText(sl) { const c = cfg(); const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : '')); let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n') + '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.'; - if (c.fridayOn) s += '\n\nFive Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.'; + for (const d of dayBonusLines()) s += '\n\n' + d.title + ': ' + d.body; + if (sl && sl.text) s += '\n\n' + sl.text; return s; } -function ladderHtml() { +function ladderHtml(sl) { const c = cfg(); const rows = PACKS.map(p => '$' + p.price + '' + money(p.credits) + ' credits' + (p.bonus ? p.bonus + '% more per dollar' : '') + '').join(''); return '

Ad packages, and what each one adds to your balance:

' + rows + '
' + '

A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.

' - + (c.fridayOn ? '

Five Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.

' : ''); + + dayBonusLines().map(d => '

' + d.title + ': ' + esc(d.body) + '

').join('') + + (sl && sl.html ? '

' + sl.html + '

' : ''); } // what one owner's batch of campaigns says in the body @@ -112,7 +132,8 @@ async function compose(owner, list, state, credits) { : canRelaunch ? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns' : 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy'; - const lines = [opener, totals, next, ladderText(), + const sl = await streakLine(owner); + const lines = [opener, totals, next, ladderText(sl), 'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.']; const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay'; const html = '

' + opener + '

' + (totals ? '

' + totals + '

' : '') @@ -120,7 +141,7 @@ async function compose(owner, list, state, credits) { + '

What each one did:

' - + ladderHtml() + + ladderHtml(sl) + '

Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.

'; return { subject, text, html }; } @@ -178,7 +199,7 @@ async function followUps(all, alreadySent) { if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; } const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x); const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; }); - r.followUp = ok ? S.seq : 'failed'; + r.followUp = ok ? S.seq : 'claimed'; if (ok) sent++; } if (due.length) save(); @@ -186,6 +207,9 @@ async function followUps(all, alreadySent) { } async function notify(owner, list, state, parentId) { + // claim before anything goes out: one copy of the app per message, ever (deploy overlap) + const claimKey = 'refill:' + (state === 'idle' ? 'idle:' + parentId : list.map(c => c.id).sort((a, b) => a - b).join(',') + ':' + state); + if (X.marks && !(await X.marks.claim(claimKey))) { if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = S.sent[key(cm.id, state)] || -1; return false; } const acct = await X.accounts.byEmail(owner); if (!acct) return false; const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false; let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {} @@ -281,4 +305,4 @@ function resetConversions(kinds) { return { cleared: n }; } -module.exports = { init, tick, stats, resetConversions, PACKS }; +module.exports = { init, tick, stats, resetConversions, PACKS, compose }; diff --git a/server.js b/server.js index 6126697..f5670e8 100644 --- a/server.js +++ b/server.js @@ -570,7 +570,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, + dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, 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'); }, });