diff --git a/coach.js b/coach.js index caf6ee9..71e8e12 100644 --- a/coach.js +++ b/coach.js @@ -5,6 +5,7 @@ const fs = require('fs'); const path = require('path'); const db = require('./db'); +const walletnudge = require('./walletnudge'); // POL waiting in the games with no wallet linked let DATA_DIR = null, chain = null, accounts = null, mailer = null; const DAY = 86400000; @@ -80,6 +81,7 @@ async function coachView(email) { // PIF gift target: a direct with a linked wallet who has NOT bought a package yet (rung < 3). Switching payouts on // no longer hides the button (Marty 2026-10-07: a prospect with payouts on still needed his first $20). c.address = (d.address && c.rung < 3) ? d.address : null; + c.polWaiting = d.address ? 0 : walletnudge.waitingFor(d.email); // earned in the games, stuck behind a missing wallet out.push(Object.assign({ email: d.email, name: d.username ? '@' + d.username : (d.memberId ? 'member #' + d.memberId : d.email.replace(/^(.).*(@.*)$/, '$1***$2')), memberId: d.memberId || 0 }, c)); } // most actionable first: stalled lowest rung, then quiet days diff --git a/public/assets/my.js b/public/assets/my.js index 22ff31f..035634f 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -1730,6 +1730,7 @@ $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') + + (x.polWaiting ? ' ' + x.polWaiting.toFixed(2) + ' POL waiting · no wallet' : '') + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' + '' + esc(x.label) + ' → ' + esc(x.next) + '' + 'rung ' + x.rung + '/6' diff --git a/public/my.html b/public/my.html index 2af7008..536c0d6 100644 --- a/public/my.html +++ b/public/my.html @@ -1149,7 +1149,7 @@ - + diff --git a/server.js b/server.js index b078109..f5a6723 100644 --- a/server.js +++ b/server.js @@ -25,7 +25,8 @@ let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } const chatbot = require('./chatbot'); const fraud = require('./fraud'); const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats -const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward +const tank = require('./tank'); +const walletnudge = require('./walletnudge'); // players with POL waiting in the games and no wallet (2026-10-07) // holding tank: unsponsored free members, adoptions, pay-it-forward const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) const promos = require('./promos'); @@ -527,6 +528,10 @@ async function boot() { setInterval(() => wednesday.tick().catch(e => console.error('wednesday', e.message)), 5 * 60 * 1000); setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com' }); + walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com', + message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } }); + setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window + setInterval(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 60 * 60 * 1000); await fraud.init({ dataDir: DATA_DIR }); { // a suspended account is signed out everywhere: every member route sees no session const realFrom = auth.fromRequest.bind(auth); @@ -2674,6 +2679,8 @@ const server = http.createServer(async (req, res) => { const r = await tank.recordGift(s.email, b.email, b.tx, b.pol); return json(res, r.error ? 400 : 200, r); } + if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); } + if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); } if (p === '/api/admin/tank' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tank.adminView()); diff --git a/updates.js b/updates.js index df2fcf7..e8f136e 100644 --- a/updates.js +++ b/updates.js @@ -110,4 +110,4 @@ function draft() { try { return JSON.parse(fs.readFileSync(DRAFT(), 'utf8')); } function saveDraft(d) { const v = { subject: String(d.subject || '').slice(0, 150), intro: String(d.intro || '').slice(0, 8000), closing: String(d.closing || '').slice(0, 2000), noteIds: (d.noteIds || []).map(String).slice(0, 40), audience: AUDIENCES[d.audience] ? d.audience : 'optin', savedAt: Date.now() }; try { fs.writeFileSync(DRAFT(), JSON.stringify(v)); } catch (e) {} return v; } function status() { const l = log(); if (running) { const k = l.sends.find(x => x.id === running.id); if (k) Object.assign(k, running); } return { sends: l.sends.slice(0, 12), running: !!running }; } function lastSentAt() { const l = log(); const d = l.sends.find(x => x.status === 'done'); return d ? d.ts : 0; } -module.exports = { init, AUDIENCES, counts, countsSnapshot, compose, send, status, lastSentAt, draft, saveDraft }; +module.exports = { init, AUDIENCES, counts, countsSnapshot, compose, send, status, lastSentAt, draft, saveDraft, optedIn }; diff --git a/walletnudge.js b/walletnudge.js new file mode 100644 index 0000000..43e12aa --- /dev/null +++ b/walletnudge.js @@ -0,0 +1,98 @@ +// Wallet-link nudges (Marty, 2026-10-07): players who earned POL in the games but never linked a wallet get told, +// so the first reward actually reaches them. Every hour this asks each game (signed with the shared SSO secret) +// for its players with an unpaid balance and no wallet, folds them by InstantAdPay account, and sends at most +// three touches per person: at once, at 3 days, at 10 days. In-app notice always (kind 'notice', never a pop-up +// broadcast); email only when the member opted in and outbound mail is on. Stops the moment a wallet is linked. +// State: DATA_DIR/wallet-nudge.json. The coach card reads waitingFor() to badge a direct. +const fs = require('fs'), path = require('path'), crypto = require('crypto'), https = require('https'), http = require('http'); +let R = {}, DATA_DIR = '.'; +const FILE = () => path.join(DATA_DIR, 'wallet-nudge.json'); +const blank = () => ({ v: 1, people: {}, stats: { sent: 0, converted: 0, runs: 0 }, lastRun: 0, lastRows: {} }); +const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } }; +const save = s => { try { fs.writeFileSync(FILE(), JSON.stringify(s)); } catch (e) {} }; +const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +const STAGES = [0, 3 * 86400000, 10 * 86400000]; // first touch now, reminder at 3 days, last word at 10 days + +function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; } +// the games that pay POL through a balance (PolHunter sends each drip directly and never holds one) +function games() { + return [ + { key: 'spookydoors', name: 'Spooky Doors', url: process.env.SD_URL, secret: process.env.SD_SSO_SECRET }, + { key: 'gemkingdom', name: 'Gem Kingdom', url: process.env.GK_URL, secret: process.env.GK_SSO_SECRET }, + { key: 'clutterhunt', name: 'ClutterHunt', url: process.env.SEEK_URL, secret: process.env.SEEK_SSO_SECRET }, + { key: 'driprunner', name: 'Drip Runner', url: process.env.DR_URL, secret: process.env.DR_SSO_SECRET } + ].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32); +} +function fetchRows(g) { + return new Promise(resolve => { + const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', String(g.secret).trim()).update('unpaid\n' + ts).digest('hex'); + let url; try { url = new URL(String(g.url).replace(/\/+$/, '') + '/api/iap/unpaid?ts=' + ts + '&sig=' + sig); } catch (e) { return resolve(null); } + const mod = url.protocol === 'https:' ? https : http; + const rq = mod.get(url, { timeout: 8000, headers: { 'User-Agent': 'InstantAdPay wallet-nudge/1.0' } }, r => { + let d = ''; r.on('data', c => { if (d.length < 2e6) d += c; }); r.on('end', () => { try { const j = JSON.parse(d); resolve(j && j.ok && Array.isArray(j.rows) ? j.rows : null); } catch (e) { resolve(null); } }); + }); + rq.on('timeout', () => { rq.destroy(); resolve(null); }); rq.on('error', () => resolve(null)); + }); +} +function copy(games, stage, link) { + const total = games.reduce((n, g) => n + g.unpaid, 0); + const list = games.map(g => g.unpaid.toFixed(2) + ' POL from ' + g.name).join(', '); + const subject = total.toFixed(2) + ' POL is waiting for your wallet'; + const p1 = 'You have ' + list + ' sitting in your game balance' + (games.length > 1 ? 's' : '') + '. It cannot be paid out yet because no wallet is linked to your InstantAdPay account.'; + const p2 = 'Link a wallet on your Wallet tab. It is one free signature, no transaction, and it cannot move funds. Your POL pays out on the next sweep, and every game pays that same wallet from then on.'; + const p3 = stage >= 2 ? 'This is the last reminder about this balance. It stays yours; it just waits for a wallet.' : 'Not sure which wallet to use? SafePal is the one we recommend; MetaMask and Phantom work too. The Wallet tab has a short guide.'; + const text = [p1, '', p2, '', 'Link your wallet: ' + link, '', p3].join('\n'); + const html = '

' + esc(p1).replace(esc(list), '' + esc(list) + '') + '

' + esc(p2) + '

Link your wallet

' + esc(p3) + '

'; + return { subject, text, html, total }; +} +async function tick() { + const S = load(); S.stats.runs++; S.lastRun = Date.now(); + const byEmail = new Map(), snapshot = {}; + for (const g of games()) { + const rows = await fetchRows(g); snapshot[g.key] = rows ? rows.length : null; if (!rows) continue; + for (const r of rows) { + let email = String(r.email || '').trim().toLowerCase(); + if (!email && r.memberId && R.accounts.byMemberId) { const a = await R.accounts.byMemberId(Number(r.memberId)); email = a ? a.email : ''; } + if (!email) continue; + const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid: Math.max(0, Number(r.unpaid) || 0) }); byEmail.set(email, cur); + } + } + S.lastRows = snapshot; + const now = Date.now(); let sent = 0; + // conversions: someone we nudged who now has a wallet. The game's own sweep pays them; we just stop. + for (const [email, p] of Object.entries(S.people)) { + if (p.done) continue; + const a = await R.accounts.byEmail(email); + if (a && a.address) { p.done = 'linked'; p.doneAt = now; S.stats.converted++; } + else if (!byEmail.has(email) && now - (p.last || p.first) > 14 * 86400000) { p.done = 'gone'; p.doneAt = now; } + } + for (const [email, gs] of byEmail) { + const a = await R.accounts.byEmail(email); if (!a || a.address) continue; + const p = S.people[email] || (S.people[email] = { first: now, sent: [], games: {} }); + p.last = now; gs.forEach(g => { p.games[g.key] = g.unpaid; }); + const stage = p.sent.length; if (stage >= STAGES.length) continue; + if (now - p.first < STAGES[stage]) continue; + const link = (R.site || 'https://instantadpay.com') + '/my#wallet'; + const c = copy(gs, stage, link); + let ok = false; + try { await R.message(email, c.subject, c.html); ok = true; } catch (e) {} + if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && R.optedIn) { try { if (await R.optedIn(email)) { await R.mailer.send(email, c.subject, c.text, c.html); ok = true; } } catch (e) {} } + if (ok) { p.sent.push({ ts: now, stage, total: Number(c.total.toFixed(4)) }); S.stats.sent++; sent++; } + } + save(S); + return { ok: true, sent, people: byEmail.size, games: snapshot }; +} +// POL a specific member has waiting across the games (0 when none, or once they linked a wallet) +function waitingFor(email) { + const p = load().people[String(email || '').trim().toLowerCase()]; + if (!p || p.done) return 0; + return Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)); +} +function adminView() { + const S = load(); + const people = Object.entries(S.people).map(([email, p]) => ({ email, first: p.first, last: p.last || p.first, sent: p.sent.length, lastSent: p.sent.length ? p.sent[p.sent.length - 1].ts : 0, done: p.done || null, games: p.games, total: Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)) })); + people.sort((a, b) => b.total - a.total); + return { stats: S.stats, lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url })), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) }; +} +module.exports = { init, tick, waitingFor, adminView, games, STAGES };