Files
instantadpay/gamepass.js
T
martbost 4d6a0f2f83 Game Pass (IAP side): $5 weekly pass across all nine games + account-wide POL cap service
- gamepass.js: durable pass store, waiting orders fulfilled by the next $5 package, cap ledger
  (daily/total per Central day, progress deferral + next-day carry-forward, idempotent refs kept 90 days,
  void), weekly Pass Tournament (Monday 9 AM Central, marks.claim, prizes recorded for the game faucets),
  admin stats. Settings in site config, caps enforced only from capsStartDate (recorded before).
- server.js: /api/partner/player, /api/partner/polgrant(+/void), /api/partner/tournament/pending|paid,
  /api/my/gamepass(+/buy), /api/admin/gamepass/stats|comp|tournament/run; gamePass claim on every
  sign-in hand-off token; purchase-event fulfilment inside the marks.claim block.
- Members > Games: Game Pass card (Buy via IAP.confirmBox, deep link /my#games?pass=1), Overview nudge
  after a free-cap hit. Admin > Game Pass pane. Chatbot canned answer + FACTS, KNOWLEDGE_DATE 10-16.
- qa/gamepass.mjs scripted test (bash qa/run.sh gamepass), Games tab card in qa/walk.mjs.
- docs/GAME-PASS.md: 3a clarifications + Built section; docs/GAME-PASS-RELEASE.md draft (not sent).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-16 08:18:09 -05:00

320 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Game Pass (2026-10-16): the $5 weekly pass across all nine games, and the account-wide POL cap service the games call
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
//
// What lives here:
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
// - waiting orders order -> { status, email, ts, tx } (a $5+ package bought while an order waits fulfils it: the pwpasses pattern)
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
// - admin stats
//
// Not to be confused with the in-game SIGN-IN pass (server.js gamePassMint/gamePassOpen): that is a session token the games keep
// in localStorage. This module is the paid Game Pass product. Fields on the wire are `pass: { active, until }` (3a).
'use strict';
const fs = require('fs');
const path = require('path');
const TZ = 'America/Chicago';
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent'];
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
let R = null; // deps from server.js
let passes, orders, prizes; // durable persisted maps (server.js open-tokens store, DURABLE set)
let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } }
let saveTimer = null;
// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ----
function ctParts(ts) {
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
}
function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; }
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; }
const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
const weekKey = ts => dayKey(weekStart(ts));
const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
// ---- settings (Admin > Settings, no deploy) ----
function cfg() {
const sc = R.siteConfig();
const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; };
const start = String(sc.capsStartDate || '').trim();
return {
enabled: ['1', 'true', 'on', 'yes'].includes(String(sc.gamePassEnabled).trim().toLowerCase()),
price: Math.max(1, Math.round(n('gamePassPriceCredits', 500))),
days: Math.max(1, Math.round(n('gamePassDays', 7))),
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '',
pct: Math.max(0, n('passTournamentPct', 5)),
gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(),
gamesTopic: String(sc.telegramGamesTopicId || '').trim(),
};
}
const enforcedOn = (c, day) => !!(c.start && day >= c.start);
// ---- ledger file ----
const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json');
function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; }
function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } }
function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); }
function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); }
function dayRow(M, day) {
return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 },
tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } },
would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate
}
function init(deps) {
R = deps;
passes = R.persistedMap('gamepass');
orders = R.persistedMap('gporders');
prizes = R.persistedMap('gpprizes');
load();
}
// ---- the pass ----
function rec(e) { return passes.get(e) || null; }
function flag(email, now) { const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const until = p && Number(p.until) || 0; return { active: until > t, until: until || null }; }
function extend(e, via, extra, now) {
const c = cfg(); const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
const base = Math.max(t, Number(cur.until) || 0);
const until = base + c.days * 86400000;
const bought = [Object.assign({ ts: t, via, usd: c.price / 100, days: c.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
passes.set(e, Object.assign({}, cur, { until, bought, ts: t }));
return { until, days: c.days };
}
function waitingOrder(e) { for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) return Object.assign({ order: k }, o); return null; }
function comp(email, why) { const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }); return { active: true, until: x.until, days: x.days }; } // support comp: counts as no sale
// GET /api/my/gamepass
function view(email, now) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e);
const caps = capsFor(e, t);
return { enabled: c.enabled, active: f.active, until: f.until, price: c.price, days: c.days, usd: c.price / 100,
waiting: !!w, waitingSince: w ? w.ts : null, bought: p ? (p.bought || []).length : 0,
caps, capsStart: c.start || null, lastCapHit: p && p.lastCapHit && (t - p.lastCapHit.ts) < 2 * 86400000 ? p.lastCapHit : null,
tournament: { pct: c.pct, shares: SHARES, next: nextTournamentAt(t) } };
}
// POST /api/my/gamepass/buy. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }.
async function buy(email, charge, now) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
if (!c.enabled) return { error: 'The Game Pass is not open yet.' };
const r = await charge(c.price, 'Game Pass (' + c.days + ' days)');
if (r && r.ok) {
const x = extend(e, 'credits', { credits: c.price, campaignId: r.campaignId || null }, t);
console.log('gamepass bought with credits', e, c.price, 'until', new Date(x.until).toISOString());
return { ok: true, active: true, until: x.until, days: c.days, paid: 'credits' };
}
if (r && r.error === 'short') {
// no purchased-grade credits on a position: the pass waits for a $5 package (bought while the order waits, it fulfils it)
let w = waitingOrder(e);
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t }); w = Object.assign({ order: k }, orders.get(k)); }
return { ok: false, needPay: true, payUrl: '/my?from=gamepass#buy', order: w.order, price: c.price, usd: c.price / 100, available: r.available || 0, need: r.need || c.price,
message: 'The pass is paid with purchased credits. Buy a $' + (c.price / 100) + ' package and the pass starts the moment it settles; you keep every credit of the package for your ads.' };
}
return { error: (r && r.error) || 'The purchase did not go through. Nothing was taken.' };
}
// a package purchase landing on chain fulfils this account's waiting order (one pass per purchase of $5 or more)
async function onEvent(ev) {
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
const c = cfg(); if ((ev.priceCents || 0) < c.price) return null;
const a = (ev.devEmail && !R.isProd) ? { email: ev.devEmail } : await R.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
const e = String(a.email).toLowerCase();
const p = passes.get(e); if (p && (p.bought || []).some(b => b.tx && b.tx === ev.tx)) return null; // each purchase counts once
const w = waitingOrder(e); if (!w) return null;
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() }));
const x = extend(e, 'package', { tx: ev.tx, cents: ev.priceCents, order: w.order }, ev.ts || Date.now());
console.log('gamepass fulfilled by package', e, 'tx', String(ev.tx).slice(0, 12), 'until', new Date(x.until).toISOString());
return { order: w.order, until: x.until };
}
// ---- the caps ----
function capsFor(email, now, game) {
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active;
const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day];
const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) };
const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass };
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
return out;
}
// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat).
function grant(o) {
const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily';
const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t);
if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' };
const key = game + ':' + ref;
const prev = L.refs[key];
if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided };
const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day);
const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free'];
let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily));
// carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap
let carried = 0; const q = M.deferred[game] || [];
for (const d of q) {
if (d.day >= day || d.left <= 0) continue;
const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left;
if (take <= 0) break;
d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20);
}
M.deferred[game] = q.filter(d => d.left > 0);
if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); }
// the new grant
let allowed = pol, deferred = 0, dropped = 0, capHit = null;
const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem);
const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null;
if (enforced) {
allowed = r6(wouldAllowed); capHit = wouldHit;
if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); }
else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } }
if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; }
} else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done
D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed));
D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1;
}
if (kind === 'daily') D.daily = r6(D.daily + allowed);
D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1;
// tournament activity: one point per reported grant (progress and daily weigh the same)
if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; }
if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass } })); }
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed };
L.refs[key] = out; touch();
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false };
}
// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered
// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent.
function voidGrant(o) {
const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref;
const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true };
if (prev.voided) return { ok: true, voided: true, repeat: true };
const M = member(prev.email); const D = dayRow(M, prev.day);
const own = r6(prev.own || 0);
D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own));
const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own));
let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0);
if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed));
const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1;
Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch();
return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } };
}
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
function holdersIn(start, end) {
const out = [];
for (const [e, p] of passes) { if (!p || !(p.until > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
return out;
}
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
function salesIn(start, end) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
function scoresFor(wk, emails) {
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
return { email: e, score, games: g, first }; }).filter(x => x.score > 0).sort((a, b) => b.score - a.score || a.first - b.first || (a.email < b.email ? -1 : 1));
}
async function runTournament(startTs, opts) {
const c = cfg(); const start = weekStart(startTs); const end = start + 7 * 86400000; const wk = dayKey(start);
if (prizes.get(wk) && !(opts && opts.force)) return prizes.get(wk);
const polUsd = await R.polUsd().catch(() => 0);
if (!(polUsd > 0)) return { error: 'POL rate unavailable; the tournament for the week of ' + wk + ' will be settled on the next hourly pass.' };
const sales = salesIn(start, end); const poolUsd = Math.round(sales.usd * c.pct) / 100;
const poolPol = r6(poolUsd / polUsd);
const ranked = scoresFor(wk, holdersIn(start, end));
const winners = [];
for (let i = 0; i < Math.min(3, ranked.length); i++) {
const x = ranked[i]; let a = null; try { a = await R.accounts.byEmail(x.email); } catch (e) {}
winners.push({ place: i + 1, email: x.email, username: (a && a.username) || null, memberId: (a && a.memberId) || 0, wallet: (a && a.address) || null, score: x.score, games: x.games, pol: r6(poolPol * SHARES[i]), usd: Math.round(poolUsd * SHARES[i] * 100) / 100, status: 'pending', tx: null });
}
const row = { week: wk, label: 'week of ' + dayLabel(wk), start, end, sales: sales.n, salesUsd: sales.usd, pct: c.pct, poolUsd, polUsd, poolPol, holders: holdersIn(start, end).length, ranked: ranked.length, winners,
unallocatedPol: r6(poolPol - winners.reduce((n, w) => n + w.pol, 0)), ranAt: Date.now(), posted: false };
prizes.set(wk, row);
console.log('gamepass tournament', wk, 'sales', sales.n, 'pool', poolPol, 'POL', 'winners', winners.length);
if (winners.length && c.enabled) {
const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}'];
const lines = winners.map(w => medal[w.place - 1] + ' ' + (w.username ? '@' + w.username : 'member #' + (w.memberId || '?')) + ' · ' + w.score + ' plays · ' + w.pol.toFixed(2) + ' POL');
const html = '\u{1F3AE} <b>Game Pass Tournament</b> · ' + row.label + '\n' + lines.join('\n') + '\n' + sales.n + ' pass' + (sales.n === 1 ? '' : 'es') + ' sold · prize pool ' + poolPol.toFixed(2) + ' POL (' + c.pct + '% of pass sales)\n'
+ 'Prizes are paid in POL by the games to the winners’ InstantAdPay wallets. Get the Pass: https://instantadpay.com/my#games?pass=1';
try { await R.telegram(html); row.posted = true; prizes.set(wk, row); } catch (e) { console.error('gamepass tournament post', e.message); }
for (const w of winners) { try { await R.notify(w.email, 'Game Pass Tournament: you placed #' + w.place, '<p>You finished <b>#' + w.place + '</b> in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of <b>' + w.pol.toFixed(2) + ' POL</b> is paid to the wallet on your InstantAdPay account by the games this week.</p>'); } catch (e) {} }
}
return row;
}
// hourly: once Monday 9 AM Central has passed and the closed week has no row yet, exactly one app copy settles it (marks.claim)
async function tournamentTick(now) {
const t = now || Date.now(); const c = cfg(); if (!c.enabled) return null;
const ws = weekStart(t); if (t < ws + 9 * 3600000) return null; // not yet 9 AM Monday for the week that just closed
const prev = ws - 7 * 86400000; const wk = dayKey(prev);
if (prizes.get(wk)) return null;
if (!holdersIn(prev, ws).length && !salesIn(prev, ws).n) { prizes.set(wk, { week: wk, label: 'week of ' + dayLabel(wk), start: prev, end: ws, sales: 0, salesUsd: 0, poolPol: 0, winners: [], ranAt: Date.now(), empty: true }); return null; }
if (!(await R.marks.claim('gamepass-tournament:' + wk))) return null;
return runTournament(prev);
}
// GET /api/partner/tournament/pending: prize rows the games still have to pay (the Road Agent faucet pattern)
function pending() { const out = []; for (const [, row] of prizes) for (const w of row.winners || []) if (w.status === 'pending') out.push({ week: row.week, label: row.label, place: w.place, email: w.email, username: w.username, memberId: w.memberId, wallet: w.wallet, pol: w.pol, usd: w.usd, score: w.score }); return out.sort((a, b) => a.week < b.week ? -1 : a.week > b.week ? 1 : a.place - b.place); }
function markPaid(week, place, tx, by) {
const row = prizes.get(String(week)); if (!row) return { error: 'no such week' };
const w = (row.winners || []).find(x => x.place === Number(place)); if (!w) return { error: 'no such place' };
if (w.status === 'paid') return { ok: true, repeat: true, tx: w.tx };
Object.assign(w, { status: 'paid', tx: String(tx || '').slice(0, 80), paidAt: Date.now(), paidBy: by || null }); prizes.set(String(week), row);
return { ok: true };
}
// ---- admin ----
function adminStats(now) {
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
for (const [, p] of passes) { if (!p) continue; if ((p.until || 0) > t) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } }
for (const [, o] of orders) if (o.status === 'waiting') waiting += 1;
const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 };
const today = { allowed: 0, grants: 0, players: 0 };
let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {};
for (const [e, M] of Object.entries(L.members)) {
let inWeek = false;
for (const [d, D] of Object.entries(M.days)) {
if (d < wkFrom) continue; inWeek = true;
for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; }
wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants;
for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal;
if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; }
}
if (inWeek) wk.players += 1;
let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); }
if (mine) qMembers += 1;
const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; }
void e;
}
const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1);
return { enabled: c.enabled, settings: { price: c.price, days: c.days, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting },
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } };
}
// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ----
function prune(now) {
const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0;
for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; }
for (const [e, M] of Object.entries(L.members)) {
for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; }
for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; }
if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e];
}
for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten
if (n) touch();
return n;
}
module.exports = { init, cfg, GAMES, NAMES, flag, view, buy, comp, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
_ledger: () => L };