e61475f89b
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
529 lines
45 KiB
JavaScript
529 lines
45 KiB
JavaScript
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (POL Miner 2026-10-28, Turkey Drop for its Nov season), 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')
|
||
// - pass orders order -> { status, email, ts, tx } (every pass is paid by a FRESH package purchase: see buy() / onEvent())
|
||
// - 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).
|
||
//
|
||
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md; Marty approved the "safe" form): beside the $5 weekly pass, the
|
||
// monthly Explorer ($20) and Champion ($40) passes. They sell islands and looks in Shards of Valor, NEVER power and NEVER more
|
||
// POL: every tier gets exactly the weekly pass caps (flag().active is true for any tier, so polgrant answers pass: true and
|
||
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
|
||
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
|
||
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
|
||
// `sovTiers` (default off; while it is off the admin tests them from Admin > Game Pass, never on the member card). No proration, no auto-renew: buying again
|
||
// extends that tier from max(now, until).
|
||
// 2026-10-22 (Marty): every pass rides the package rail so sponsors get paid. Buying a pass never spends a credit balance any more
|
||
// (today's buyer paid from an old balance, so no new money came in and nobody upline was paid). A pass click opens an order; the
|
||
// order is fulfilled ONLY by an on-chain package Purchase of at least the tier price, mined after the order was opened, bought by
|
||
// one of that member's own positions (main or linked), each purchase tx used once. The member keeps that package's credits for ads.
|
||
// Bought rows: via 'package' (with tx and cents). The two rows from before this change are via 'credits' and 'package' and stay.
|
||
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 and Champion $39.99 (30 days), plus Sovereign $99.99 (30 days)
|
||
// and Legend $249.99 (365 days, the yearly pass), all in TIER_DEFS below and all behind the same sovTiers switch. The weekly
|
||
// pass is unchanged ($5 / 7 days / the same caps). Rank weekly < explorer < champion < sovereign < legend.
|
||
// 2026-10-25 (Marty): every tier price equals an InstantAdPay one-click package, so the cheapest qualifying package is exactly
|
||
// the pass price (no silent overpay): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend
|
||
// $250 (was 249.99); weekly $5 unchanged. The pass comes with that package's ad credits.
|
||
'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', 'shardsofvalor', 'polminer', 'warpwares', 'turkeydrop'];
|
||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent', shardsofvalor: 'Shards of Valor', polminer: 'POL Miner', warpwares: 'Warp & Wares', turkeydrop: 'Turkey Drop' };
|
||
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)
|
||
// THE pass table (2026-10-22, Dallas's structure, Marty approved): lowest to highest, a higher tier includes everything below.
|
||
// Rename a tier here (name) and nowhere else: the member card, the admin pane, the charge label and the chatbot read it from here.
|
||
// key = the wire value the games read (flag().tier / tiers); set = the Admin > Settings stem (gamePass<set>Enabled /
|
||
// PriceCredits / Days; weekly keeps its original gamePassPriceCredits / gamePassDays); price = the pass price in cents (100 = $1;
|
||
// the setting keeps its old 'PriceCredits' name): the package that pays for a pass must cost at least this much;
|
||
// perks = what the member card lists. Every tier is a Game Pass holder everywhere with the SAME caps (no extra POL).
|
||
const TIER_DEFS = [
|
||
{ key: 'weekly', name: 'Game Pass', set: '', price: 500, days: 7,
|
||
perks: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and weapons unlocked'] },
|
||
{ key: 'explorer', name: 'Explorer', set: 'Explorer', price: 2000, days: 30,
|
||
perks: ['Everything in the Game Pass, in every game', 'Shards of Valor: weapons and gear unlocked', 'Shards of Valor: 2 bonus islands'] },
|
||
{ key: 'champion', name: 'Champion', set: 'Champion', price: 5000, days: 30,
|
||
perks: ['Everything in Explorer', 'Shards of Valor: 4 bonus islands of your choice', 'Shards of Valor: the Druid hero', 'Shards of Valor: level cap 30'] },
|
||
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
|
||
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: the Necromancer hero', 'Shards of Valor: level cap 40'] },
|
||
{ key: 'legend', name: 'Legend', set: 'Legend', price: 25000, days: 365,
|
||
perks: ['Everything in Sovereign, for a full year', 'Shards of Valor: every bonus island', 'Shards of Valor: every hero, the Archer included, and every new hero as it ships', 'Shards of Valor: level cap 40'] }, // new heroes as a Legend perk: Marty 2026-10-30 (Dallas's $100/year idea folded in here)
|
||
];
|
||
const TIERS = TIER_DEFS.map(d => d.key); // lowest to highest
|
||
const TIER_NAMES = Object.fromEntries(TIER_DEFS.map(d => [d.key, d.name]));
|
||
const TIER_DEF = Object.fromEntries(TIER_DEFS.map(d => [d.key, d]));
|
||
const tierOk = t => TIERS.includes(t);
|
||
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
|
||
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();
|
||
const on = k => ['1', 'true', 'on', 'yes'].includes(String(sc[k]).trim().toLowerCase());
|
||
const offExplicit = k => ['0', 'false', 'off', 'no'].includes(String(sc[k]).trim().toLowerCase());
|
||
const price = Math.max(1, Math.round(n('gamePassPriceCredits', 500))), days = Math.max(1, Math.round(n('gamePassDays', 7)));
|
||
return {
|
||
enabled: on('gamePassEnabled'),
|
||
price, days,
|
||
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Every tier above weekly needs the
|
||
// master switch sovTiers AND the weekly pass switched on; its own gamePass<Set>Enabled is a kill switch (missing = on).
|
||
tierSales: on('sovTiers'),
|
||
tiers: Object.fromEntries(TIER_DEFS.map(d => [d.key, d.key === 'weekly' ? { price, days, sale: on('gamePassEnabled') }
|
||
: { price: Math.max(1, Math.round(n('gamePass' + d.set + 'PriceCredits', d.price))), days: Math.max(1, Math.round(n('gamePass' + d.set + 'Days', d.days))),
|
||
sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePass' + d.set + 'Enabled') }])),
|
||
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
|
||
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
|
||
// the free allowance (Marty 2026-11-02, "cap these so that if the user wants to keep playing they spend a tiny amount"):
|
||
// the most game POL an account EVER receives while it holds no pass, across every game. After that, progress rewards
|
||
// wait as deferred until a pass is active and repeatable rewards are dropped. 2 POL default; admin key capFreeLifetime.
|
||
freeLifetime: Math.max(0, n('capFreeLifetime', 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; }
|
||
// per-tier expiry (ms, 0 = never held). A record from before tiers has no `tiers`: its legacy `until` is the weekly tier
|
||
// (lazy migration, idempotent: every write stores `tiers` and mirrors tiers.weekly into `until`).
|
||
function tiersOf(p) {
|
||
const out = {}; const T = (p && p.tiers) || {};
|
||
for (const k of TIERS) out[k] = Number(T[k] && T[k].until) || 0;
|
||
if (p && !p.tiers) out.weekly = Number(p.until) || 0;
|
||
return out;
|
||
}
|
||
function topTier(T, t) { for (let i = TIERS.length - 1; i >= 0; i--) if (T[TIERS[i]] > t) return TIERS[i]; return null; }
|
||
// { active, until, tier, tiers }: active = any tier on (every tier is a Game Pass holder everywhere, same caps); tier = the
|
||
// highest active tier; until = that tier's end. With nothing active, until is the last end the account ever had (as before
|
||
// tiers) or null. tiers = each tier's end while it is active, else null.
|
||
function flag(email, now) {
|
||
const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const T = tiersOf(p); const tier = topTier(T, t);
|
||
const tiers = {}; for (const k of TIERS) tiers[k] = T[k] > t ? T[k] : null;
|
||
const last = Math.max(...TIERS.map(k => T[k]));
|
||
return { active: !!tier, until: tier ? T[tier] : (last || null), tier, tiers };
|
||
}
|
||
function writeTiers(cur, T, extra) {
|
||
const tiers = {}; for (const k of TIERS) if (T[k]) tiers[k] = { until: T[k] };
|
||
return Object.assign({}, cur, { until: T.weekly || 0, tiers }, extra || {});
|
||
}
|
||
function extend(e, via, extra, now, tier) {
|
||
tier = tierOk(tier) ? tier : 'weekly';
|
||
const c = cfg(); const tc = c.tiers[tier]; const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
|
||
const T = tiersOf(cur);
|
||
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
|
||
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
|
||
passes.set(e, writeTiers(cur, T, { bought, ts: t }));
|
||
return { until, days: tc.days, tier };
|
||
}
|
||
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
|
||
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
|
||
// the admin's tier test: drop a waiting order that was opened for testing, so a later real package never fulfils it by surprise
|
||
function cancelOrder(email, tier) {
|
||
const e = String(email || '').toLowerCase(); const w = waitingOrder(e, tier || 'weekly'); if (!w) return { ok: true, none: true };
|
||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, tier: w.tier };
|
||
}
|
||
function comp(email, why, tier, now) { // support comp: counts as no sale
|
||
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
|
||
return { active: true, until: x.until, days: x.days, tier: x.tier };
|
||
}
|
||
// support refund (never automatic): that tier ends now; the record keeps what it was
|
||
function revoke(email, tier, why, now) {
|
||
const e = String(email || '').toLowerCase(); if (!tierOk(tier)) return { error: 'unknown tier' };
|
||
const t = now || Date.now(); const p = passes.get(e); const T = tiersOf(p);
|
||
if (!p || !(T[tier] > t)) return { error: 'No active ' + TIER_NAMES[tier] + ' pass on this account.' };
|
||
const was = T[tier]; T[tier] = t;
|
||
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
|
||
return { ok: true, tier, was, until: t };
|
||
}
|
||
// on sale for this viewer: the tier's own switch, or the admin portal's tier test (Admin > Game Pass) while sovTiers is off
|
||
const tierOpen = (c, tier, preview) => !!(c.tiers[tier].sale || (preview && tier !== 'weekly'));
|
||
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
|
||
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
|
||
|
||
// GET /api/my/gamepass: exactly what a member sees, for EVERY account, the admin's included (2026-10-25, Marty: no admin-only
|
||
// tier UI on the member card). opts.preview = the admin portal's tier test (GET /api/admin/gamepass/preview): every tier, each
|
||
// one open to the admin's own account while sovTiers is off.
|
||
function view(email, now, opts) {
|
||
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, 'weekly');
|
||
const admin = !!(opts && opts.preview); const T = tiersOf(p);
|
||
const caps = capsFor(e, t);
|
||
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
|
||
// keep their pass when a sale is switched off, they just cannot buy more)
|
||
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
|
||
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
|
||
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
|
||
});
|
||
const tiered = passRows.some(r => r.tier !== 'weekly');
|
||
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, 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) },
|
||
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales };
|
||
}
|
||
|
||
// POST /api/my/gamepass/buy { tier }. tier missing = weekly (exactly the pass as it was before tiers). opts.preview = the admin
|
||
// portal's tier test (POST /api/admin/gamepass/test-buy, the admin's own account only): a tier that is not on sale still opens an order.
|
||
// A pass is ALWAYS paid by a fresh package purchase (2026-10-22, Marty: the pass rides the package rail so sponsors get paid). This never
|
||
// spends credits: it opens (or reuses) a waiting order for that tier and sends the member to buy a package of at least the tier price.
|
||
// The order is fulfilled by onEvent() below; the member keeps every credit of that package for ads.
|
||
function buy(email, now, tier, opts) {
|
||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
|
||
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
|
||
if (!tierOk(tier)) return { error: 'There is no such pass.' };
|
||
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
|
||
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
|
||
else if (!tierOpen(c, tier, !!(opts && opts.preview))) return { error: 'The ' + name + ' pass is not open yet.' };
|
||
let w = waitingOrder(e, tier); const reused = !!w;
|
||
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
|
||
const pkg = packageFor(tc.price / 100);
|
||
if (!reused) console.log('gamepass order opened', tier, e, w.order, 'needs a package of', tc.price, 'cents');
|
||
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, orderTs: w.ts, reused,
|
||
price: tc.price, usd: tc.price / 100, package: pkg,
|
||
message: (tier === 'weekly' ? 'Your Game Pass' : 'Your ' + name + ' pass') + ' starts the moment your next package of $' + pkg + ' or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
|
||
}
|
||
|
||
// A package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers.
|
||
// Rules (2026-10-22): the buyer must be one of this account's own positions (main member id or a linked position); the purchase must
|
||
// be mined AFTER the order was opened (block time, ORDER_SKEW_MS for clock drift); one pass per purchase of $5 or more; each tx used
|
||
// once across every account and order. Credit balances never fulfil an order.
|
||
const ORDER_SKEW_MS = 30000;
|
||
function txUsed(tx) {
|
||
if (!tx) return false;
|
||
for (const [, o] of orders) if (o && o.tx === tx) return true;
|
||
for (const [, p] of passes) if (p && (p.bought || []).some(b => b.tx && b.tx === tx)) return true;
|
||
return false;
|
||
}
|
||
async function ownerOf(ev) { // the account behind the buying position
|
||
if (ev.devEmail && !R.isProd) return String(ev.devEmail).toLowerCase();
|
||
const id = Number(ev.buyerId) || 0; if (!id) return null;
|
||
let a = await R.accounts.byMemberId(id);
|
||
if (!a && R.accounts.positionByMember) { const pos = await R.accounts.positionByMember(id); if (pos && pos.email) a = { email: pos.email }; }
|
||
return a && a.email ? String(a.email).toLowerCase() : null;
|
||
}
|
||
async function minedAt(ev) { // block time in ms; the indexed-at time only when the block cannot be read (it is never earlier than the block)
|
||
if (ev.devMinedAt && !R.isProd) return Number(ev.devMinedAt);
|
||
if (ev.block && R.blockTime) {
|
||
for (let i = 0; i < 3; i++) { try { const s = await R.blockTime(ev.block); if (s > 0) return s * 1000; } catch (e) {} await new Promise(r => setTimeout(r, 1500)); }
|
||
console.warn('gamepass: block time unavailable for', ev.block, '- using the indexed-at time');
|
||
}
|
||
return Number(ev.ts) || Date.now();
|
||
}
|
||
async function onEvent(ev) {
|
||
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
|
||
const c = cfg(); const cents = ev.priceCents || 0;
|
||
if (!TIERS.some(k => cents >= c.tiers[k].price)) return null;
|
||
const e = await ownerOf(ev); if (!e) return null;
|
||
if (!waitingOrders(e).length) return null;
|
||
if (txUsed(ev.tx)) return null; // each purchase counts once, everywhere
|
||
const at = await minedAt(ev);
|
||
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price && at + ORDER_SKEW_MS >= o.ts)
|
||
.sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].price || x.ts - y.ts)[0];
|
||
if (!w) { console.log('gamepass: package', String(ev.tx).slice(0, 12), 'by', e, 'fulfils no order (bought before the order or too small)'); return null; }
|
||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
|
||
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: c.tiers[w.tier].price / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), w.tier);
|
||
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents, until', new Date(x.until).toISOString());
|
||
return { order: w.order, until: x.until, tier: w.tier };
|
||
}
|
||
|
||
// ---- 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 };
|
||
out.lifetime = { cap: c.freeLifetime, used: r6(M && M.freeTotal != null ? M.freeTotal : (M ? Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0) : 0)) }; // the free allowance, what has been used of it
|
||
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
|
||
out.lifetime.done = !pass && out.lifetime.used + 1e-9 >= out.lifetime.cap; // the free allowance is used up (only a pass pays from here)
|
||
out.lifetime.waiting = M ? r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0)) : 0;
|
||
return out;
|
||
}
|
||
|
||
// quest-site check (Zealy, 2026-11-05): has this account earned any game reward, and how much in total
|
||
function activity(email) {
|
||
const M = L.members[String(email || '').toLowerCase()]; if (!M) return { grants: 0, pol: 0 };
|
||
return Object.values(M.days).reduce((o, d) => ({ grants: o.grants + (d.grants || 0), pol: r6(o.pol + (d.total || 0)) }), { grants: 0, pol: 0 });
|
||
}
|
||
|
||
// 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));
|
||
// the free allowance: a running total of what this account received while it held no pass (seeded once from the day rows
|
||
// still on file); once it reaches freeLifetime, a free account's room for today is zero, carry included
|
||
if (M.freeTotal == null) M.freeTotal = r6(Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0));
|
||
let lifetimeHit = false;
|
||
if (!pass && enforced) { const room = Math.max(0, r6(c.freeLifetime - M.freeTotal)); if (room < totalRem) totalRem = room; lifetimeHit = room < pol; } // hit = the allowance, not the day, is what trims this grant
|
||
// 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;
|
||
if (!pass) M.freeTotal = r6((M.freeTotal || 0) + allowed + carried); // counts toward the free allowance only while no pass is held
|
||
// 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, lifetime: !!lifetimeHit } })); }
|
||
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed, lifetimeHit };
|
||
L.refs[key] = out; touch();
|
||
// waiting = every game's progress POL deferred for this account (it pays once a pass is active, inside the pass cap); the games
|
||
// show it in the allowance note (Marty 2026-11-03: tell members at the cap to get the Pass, and what is waiting for them)
|
||
const waiting = r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0));
|
||
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false, lifetimeHit, freeUsed: r6(M.freeTotal || 0), freeLifetime: c.freeLifetime, waiting };
|
||
}
|
||
|
||
// 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) { // any tier holds a Pass Tournament seat (every tier above weekly includes everything Weekly gives)
|
||
const out = [];
|
||
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > 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
|
||
// the pool counts weekly pass sales only, unless passTournamentTierSales adds the sales of every tier above weekly (default off: the pool exactly as before tiers)
|
||
function salesIn(start, end, withTiers) { 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 && (withTiers || rowTier(b) === 'weekly')) { 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, c.tournamentTierSales); 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, c.tournamentTierSales).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 monthStart(ts) { const p = ctParts(ts); return ctMidnight(Date.UTC(p.y, p.mo - 1, 1, 17)); } // the 1st of the Central month, 00:00 Central
|
||
// per tier: active = accounts whose HIGHEST active tier is this one (each account counted once); sales by Central week / month /
|
||
// all time (comps are not sales); renewals30d = purchases in the last 30 days by accounts that held this tier before; expiring7d =
|
||
// this tier ends within the next 7 Central days (today included); waitingOrders = orders waiting for a package.
|
||
function tierStats(t) {
|
||
const ws = weekStart(t), ms = monthStart(t), d30 = t - 30 * 86400000;
|
||
const soon = ctMidnight(ctMidnight(t) + 7 * 86400000 + 3 * 3600000); // Central midnight that ends day 7 (DST-safe)
|
||
const out = {}; for (const k of TIERS) out[k] = { name: TIER_NAMES[k], active: 0, soldWeek: 0, usdWeek: 0, soldMonth: 0, usdMonth: 0, soldTotal: 0, usdTotal: 0, renewals30d: 0, expiring7d: 0, comped: 0, waitingOrders: 0 };
|
||
for (const [, p] of passes) {
|
||
if (!p) continue; const T = tiersOf(p); const top = topTier(T, t); if (top) out[top].active += 1;
|
||
for (const k of TIERS) if (T[k] > t && T[k] <= soon) out[k].expiring7d += 1;
|
||
const rows = p.bought || [];
|
||
for (const b of rows) {
|
||
const k = rowTier(b); const o = out[k]; if (!isSale(b)) { o.comped += 1; continue; }
|
||
const usd = Number(b.usd) || 0; o.soldTotal += 1; o.usdTotal += usd;
|
||
if (b.ts >= ws) { o.soldWeek += 1; o.usdWeek += usd; }
|
||
if (b.ts >= ms) { o.soldMonth += 1; o.usdMonth += usd; }
|
||
if (b.ts >= d30 && rows.some(x => x !== b && rowTier(x) === k && x.ts < b.ts)) o.renewals30d += 1;
|
||
}
|
||
}
|
||
for (const [, o] of orders) if (o.status === 'waiting') out[tierOk(o.tier) ? o.tier : 'weekly'].waitingOrders += 1;
|
||
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
|
||
return out;
|
||
}
|
||
// every sale row, newest first, labelled by how it was paid. Rows from the new package rail carry buyerId (2026-10-22); the two
|
||
// rows from before (one paid with a credit balance, one fulfilled by a package under the old rule) are labelled as such.
|
||
function payLabel(b) {
|
||
if (b.via === 'credits') return 'credit-paid (old rule)';
|
||
if (b.via === 'package') return ('buyerId' in b) ? 'package' : 'package (old rule)';
|
||
return String(b.via || '?');
|
||
}
|
||
function salesList(limit) {
|
||
const out = [];
|
||
for (const [e, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b)) out.push({ ts: b.ts, email: e, tier: rowTier(b), name: TIER_NAMES[rowTier(b)], via: b.via, label: payLabel(b),
|
||
tx: b.tx || null, usd: Number(b.usd) || 0, packageUsd: b.packageUsd || (b.cents ? b.cents / 100 : null), credits: b.credits || null, buyerId: b.buyerId || null });
|
||
return out.sort((a, b) => b.ts - a.ts).slice(0, limit || 50);
|
||
}
|
||
function payMix() {
|
||
const m = { credit: { n: 0, usd: 0 }, packageOld: { n: 0, usd: 0 }, package: { n: 0, usd: 0, packageUsd: 0 } };
|
||
for (const [, p] of passes) for (const b of (p && p.bought) || []) {
|
||
if (!isSale(b)) continue; const usd = Number(b.usd) || 0;
|
||
const k = b.via === 'credits' ? 'credit' : (b.via === 'package' && !('buyerId' in b)) ? 'packageOld' : 'package';
|
||
m[k].n += 1; m[k].usd = Math.round((m[k].usd + usd) * 100) / 100;
|
||
if (k === 'package') m.package.packageUsd = Math.round((m.package.packageUsd + (Number(b.packageUsd) || (b.cents ? b.cents / 100 : 0))) * 100) / 100;
|
||
}
|
||
return m;
|
||
}
|
||
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 (topTier(tiersOf(p), 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, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, 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 },
|
||
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
|
||
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting, pay: payMix() },
|
||
sales: salesList(50),
|
||
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, TIERS, TIER_NAMES, TIER_DEFS, flag, activity, view, buy, cancelOrder, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||
_ledger: () => L };
|