Pass tiers: Explorer ($20/30 days) and Champion ($40/30 days) beside the weekly Game Pass, behind sovTiers (default off, admin-only preview)
Islands and looks in Shards of Valor, never power and never more POL: every tier gets exactly the weekly pass caps and polgrant
still answers pass: true. Per-tier expiry side by side (record.tiers, legacy until mirrors weekly, lazy migration); flag() adds
tier (highest active) and tiers; hand-off token gamePass { active, until, tier }; /api/partner/player pass { active, until, tier,
tiers }. Buy { tier } with purchased credits or a waiting order per tier that a big-enough package fulfils (highest price first,
each tx once). No auto-renew, no proration. Admin: per-tier stats (Central week/month), comp per tier, end-a-tier (refund).
Tournament pool keeps weekly sales only unless passTournamentTierSales. Member card shows three tiers; /my#passes opens it.
Tests: qa/sov-passes-store.cjs, qa/sov-passes-local.mjs (bash qa/run.sh sov-passes). Cache tags my.js/admin.js 20261018tiers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+152
-45
@@ -11,6 +11,15 @@
|
||||
//
|
||||
// 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; only ADMIN_EMAIL can see and buy them while it is off). No proration, no auto-renew: buying again
|
||||
// extends that tier from max(now, until).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
@@ -20,6 +29,10 @@ const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarr
|
||||
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' };
|
||||
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 TIERS = ['weekly', 'explorer', 'champion']; // lowest to highest
|
||||
const TIER_NAMES = { weekly: 'Game Pass', explorer: 'Explorer', champion: 'Champion' };
|
||||
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
|
||||
@@ -44,10 +57,21 @@ 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: ['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))),
|
||||
enabled: on('gamePassEnabled'),
|
||||
price, days,
|
||||
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Explorer/Champion need the master
|
||||
// switch sovTiers AND the weekly pass switched on; their own gamePass<Tier>Enabled is a kill switch (missing = on).
|
||||
tierSales: on('sovTiers'),
|
||||
tiers: {
|
||||
weekly: { price, days, sale: on('gamePassEnabled') },
|
||||
explorer: { price: Math.max(1, Math.round(n('gamePassExplorerPriceCredits', 2000))), days: Math.max(1, Math.round(n('gamePassExplorerDays', 30))), sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePassExplorerEnabled') },
|
||||
champion: { price: Math.max(1, Math.round(n('gamePassChampionPriceCredits', 4000))), days: Math.max(1, Math.round(n('gamePassChampionDays', 30))), sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePassChampionEnabled') },
|
||||
},
|
||||
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)) },
|
||||
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 : '',
|
||||
@@ -80,60 +104,117 @@ function init(deps) {
|
||||
|
||||
// ---- 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 };
|
||||
// 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 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
|
||||
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; }
|
||||
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 account testing Explorer/Champion while sovTiers is off
|
||||
const tierOpen = (c, tier, admin) => !!(c.tiers[tier].sale || (admin && 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
|
||||
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);
|
||||
// GET /api/my/gamepass. opts.admin = the ADMIN_EMAIL account (sees Explorer/Champion 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.admin); const T = tiersOf(p);
|
||||
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,
|
||||
// the tier rows this member sees: weekly always; Explorer/Champion while on sale, to the admin, 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], 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), 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) } };
|
||||
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. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }.
|
||||
async function buy(email, charge, now) {
|
||||
// POST /api/my/gamepass/buy { tier }. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }.
|
||||
// tier missing = weekly (exactly the pass as it was before tiers). opts.admin = the ADMIN_EMAIL account.
|
||||
async function buy(email, charge, now, tier, opts) {
|
||||
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)');
|
||||
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.admin))) return { error: 'The ' + name + ' pass is not open yet.' };
|
||||
const r = await charge(tc.price, (tier === 'weekly' ? 'Game Pass' : name + ' pass') + ' (' + tc.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' };
|
||||
const x = extend(e, 'credits', { credits: tc.price, campaignId: r.campaignId || null }, t, tier);
|
||||
console.log('gamepass bought with credits', tier, e, tc.price, 'until', new Date(x.until).toISOString());
|
||||
return { ok: true, active: true, tier, until: x.until, days: tc.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.' };
|
||||
// no purchased-grade credits on a position: the pass waits for a package of at least its price (bought while the order waits, it fulfils it)
|
||||
let w = waitingOrder(e, tier);
|
||||
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);
|
||||
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, price: tc.price, usd: tc.price / 100, package: pkg, available: r.available || 0, need: r.need || tc.price,
|
||||
message: (tier === 'weekly' ? 'The pass' : 'The ' + name + ' pass') + ' is paid with purchased credits. Buy a $' + pkg + ' 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)
|
||||
// a package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers
|
||||
// (one pass per purchase of $5 or more, each tx counted once)
|
||||
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 c = cfg(); const cents = ev.priceCents || 0;
|
||||
if (!TIERS.some(k => cents >= c.tiers[k].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 };
|
||||
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price).sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].price || x.ts - y.ts)[0];
|
||||
if (!w) return null;
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now() }));
|
||||
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order }, ev.ts || Date.now(), w.tier);
|
||||
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), 'until', new Date(x.until).toISOString());
|
||||
return { order: w.order, until: x.until, tier: w.tier };
|
||||
}
|
||||
|
||||
// ---- the caps ----
|
||||
@@ -209,13 +290,14 @@ function voidGrant(o) {
|
||||
|
||||
// ---- 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) {
|
||||
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (Explorer and Champion include everything Weekly gives)
|
||||
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); }
|
||||
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
|
||||
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 }; }
|
||||
// the pool counts weekly pass sales only, unless passTournamentTierSales adds Explorer/Champion sales (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));
|
||||
@@ -225,7 +307,7 @@ async function runTournament(startTs, opts) {
|
||||
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 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 = [];
|
||||
@@ -253,7 +335,7 @@ async function tournamentTick(now) {
|
||||
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 (!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);
|
||||
}
|
||||
@@ -268,10 +350,34 @@ function markPaid(week, place, tx, by) {
|
||||
}
|
||||
|
||||
// ---- 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;
|
||||
}
|
||||
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 [, 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 };
|
||||
@@ -292,8 +398,9 @@ function adminStats(now) {
|
||||
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) },
|
||||
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 },
|
||||
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 },
|
||||
@@ -315,5 +422,5 @@ function prune(now) {
|
||||
return n;
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, GAMES, NAMES, flag, view, buy, comp, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||||
module.exports = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, flag, view, buy, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||||
_ledger: () => L };
|
||||
|
||||
Reference in New Issue
Block a user