diff --git a/docs/GAME-PASS.md b/docs/GAME-PASS.md index 133e226..0d469b0 100644 --- a/docs/GAME-PASS.md +++ b/docs/GAME-PASS.md @@ -215,6 +215,34 @@ sales. If the POL rate is unavailable the tick retries next hour. - Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the Game Pass keys show in the Site settings form). +## Pass tiers: Explorer and Champion (IAP side, 2026-10-18) + +Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form: paid tiers add Shards of Valor islands and looks, never +power, never more POL. The weekly pass is unchanged. + +- **Tiers**: `weekly` (500 credits, 7 days), `explorer` (2000, 30 days), `champion` (4000, 30 days). Every tier is a Game Pass + holder everywhere with exactly the pass caps; `polgrant` keeps answering `pass: true` (a boolean). +- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until } }`, the legacy `until` mirrors the weekly + tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing = weekly). Lazy migration: a record + without `tiers` reads its `until` as the weekly tier. +- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end). The hand-off token + carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries `pass: { active, until, tier, tiers }`. +- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Explorer/Champion need `sovTiers` on (and the weekly pass on); + while off, only the `ADMIN_EMAIL` account sees and can buy them (admin preview on the card). Short of purchased credits: a + waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase, + each tx once). There is no $40 package, so Champion's copy names the $50 one. +- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)`. Tiers run side by side; + when a higher one ends the next one shows through. Admin comp takes a tier; `POST /api/admin/gamepass/revoke { email, tier, why }` + ends one tier now (support refunds only, credits are not returned by it). +- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1`. +- **Settings**: `sovTiers` 0, `gamePassExplorerEnabled` 1 / `gamePassChampionEnabled` 1 (a `0` stops one tier), + `gamePassExplorerPriceCredits` 2000, `gamePassChampionPriceCredits` 4000, `gamePassExplorerDays` / `gamePassChampionDays` 30, + `passTournamentTierSales` 0. +- **Member UI**: the Games tab card shows the three tiers side by side (end dates in Central time); `/my#passes` opens it (the + Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button. +- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer through the real + `ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`). + ## Games: as built (2026-10-16, local commits only, nothing deployed) Everything is behind `GAMEPASS=on` (env, default off = today's behaviour, so the games can be deployed before launch). `IAP_URL` is diff --git a/gamepass.js b/gamepass.js index 6b51deb..b067c04 100644 --- a/gamepass.js +++ b/gamepass.js @@ -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 gamePassEnabled 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 }; diff --git a/public/admin.html b/public/admin.html index 7af8735..6abb6e6 100644 --- a/public/admin.html +++ b/public/admin.html @@ -520,10 +520,14 @@
-

Comp a pass

support: one pass week, recorded as no sale
-

+

By pass tier

+
…
-

Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.

+
+

Comp a pass

support: one pass period, recorded as no sale
+

+
+

Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Monthly tiers: sovTiers (1/0, the Explorer + Champion sale switch; off = only the admin account sees them), gamePassExplorerEnabled / gamePassChampionEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (4000), gamePassExplorerDays / gamePassChampionDays (30), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.

- + diff --git a/public/assets/admin.js b/public/assets/admin.js index 2812bc3..9a3d667 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -1159,6 +1159,12 @@ + 'Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)' + S.price + ' credits · ' + S.days + ' days' + '' + (Q.byGame && Object.keys(Q.byGame).length ? '

By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '

' : ''); + // per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month + const TS = r.tiers || {}, TC = S.tiers || {}; + $('gpTiersSub').textContent = 'Explorer + Champion sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' monthly sales'; + $('gpTiers').innerHTML = '' + + ['weekly', 'explorer', 'champion'].map(k => { const x = TS[k] || {}, c = TC[k] || {}; return ''; }).join('') + + '
TierPriceActiveSold weekSold monthAll timeRenewals 30dEnding in 7 daysCompedWaiting
' + esc(x.name || k) + (c.sale ? '' : '
not on sale') + '
' + (c.price || 0) + ' cr · ' + (c.days || 0) + ' d' + (x.active || 0) + '' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '' + (x.renewals30d || 0) + '' + (x.expiring7d || 0) + '' + (x.comped || 0) + '' + (x.waitingOrders || 0) + '

Every tier gets the same pass caps (no extra POL). Monthly tiers add Shards of Valor islands and looks only.

'; $('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid'; const L = T.last; $('gpTour').innerHTML = !L ? '

No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).

' @@ -1167,7 +1173,12 @@ + ((T.history || []).length > 1 ? '

Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '

' : ''); } $('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); })); - $('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value }); IAP.status('Pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); })); + $('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); })); + $('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => { + const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; } + if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return; + const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass(); + })); async function loadSettings() { const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]); diff --git a/public/assets/my.js b/public/assets/my.js index 095908f..4ea4a76 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -651,7 +651,7 @@ box.innerHTML = v.eligible ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; - if (from) setPane('buy'); + if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card } function jumpTo(pane, id) { setPane(pane); @@ -788,7 +788,8 @@ earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', wallet: 'Wallet & account', profile: 'Profile' }; function setPane(name) { - const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) + let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) + if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card if (!PANES.includes(name)) name = 'overview'; for (const p of PANES) { const el = $('pane-' + p); @@ -1691,10 +1692,58 @@ // ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ---- const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }); const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, ''); + // Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add + // islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time. + const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)'; + const GP_TIER_PERKS = { + weekly: ['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 the Weekly look'], + explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'], + champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'], + }; + function renderPassTiers(card, gp, highlight) { + const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier); + const state = top ? '' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '' + : 'No pass active'; + const caps = gp.caps || {}; + const capsLine = caps.enforced ? 'Today: ' + gpPol(caps.used && caps.used.total) + ' of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : ''; + const box = r => { + const btn = r.waiting ? '' + : r.open ? '' + : 'Not on sale right now. Your pass keeps running.'; + return '

' + esc(r.name) + '

' + + '

$' + r.usd + ' for ' + r.days + ' days

' + + '' + + '

' + (r.active ? 'Active until ' + esc(gpCT(r.until)) + '' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '

' + + btn + '
'; + }; + card.hidden = false; card.classList.toggle('gp-hl', !!highlight); + card.innerHTML = '

\u{1F39F}️ Game Passes

weekly or monthly · every game
' + + (gp.tierPreview ? '

Admin preview. Explorer and Champion are hidden from members until sovTiers is switched on in Settings.

' : '') + + '

' + state + '

' + + '

Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. The monthly passes add islands to explore and looks in Shards of Valor. Paid passes never make you stronger than players who earn their gear, and they never pay more POL.

' + + '
' + rows.map(box).join('') + '
' + + (capsLine ? '

' + capsLine + '

' : '') + + '

Paid with purchased credits from your packages (earned credits never buy a pass). Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.

'; + card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => { + const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return; + const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + r.days + ' days' : 'Get ' + r.name + ' for ' + r.days + ' days') + ' for ' + r.price + ' purchased credits ($' + r.usd + ')? It starts at once. Islands and looks only: no extra power, no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' }); + if (!yes) return; + b.disabled = true; + try { + const x = await api('/api/my/gamepass/buy', { tier: r.tier }); + if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; } + IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok'); + await loadGamePassCard(true); + } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } + })); + card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy'))); + if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} } + } async function loadGamePassCard(highlight) { const card = $('gpCard'); if (!card) return; let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {} - if (!gp || !gp.enabled) { card.hidden = true; return; } + if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; } + if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); // Explorer / Champion on sale (or admin preview, or a holder) const caps = gp.caps || {}; const price = gp.price || 500; const state = gp.active ? 'Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '' : gp.waiting ? 'Waiting for a $' + (gp.usd || 5) + ' package' : 'Not active'; diff --git a/public/my.html b/public/my.html index f23d13c..2d491a4 100644 --- a/public/my.html +++ b/public/my.html @@ -1093,6 +1093,13 @@ .game-card .btn{margin-top:auto;text-align:center} .game-card{position:relative} #gpCard.gp-hl{outline:2px solid var(--gold,#e2b04a);outline-offset:2px} +.gp-tiers{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-top:10px} +.gp-tier{border:1px solid var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px} +.gp-tier.on{border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset} +.gp-tier h4{margin:0;font-size:16px;color:var(--ink);font-family:var(--disp)} +.gp-tier .gp-price{margin:0;font-size:20px;font-weight:700} +.gp-tier ul{margin:4px 0;padding-left:18px;font-size:13px} +.gp-tier .btn{margin-top:auto;align-self:flex-start} .game-card .gc-ribbon{position:absolute;top:10px;right:10px;display:inline-flex;align-items:center;gap:6px;background:#FF5FA2;color:#2b0418;font-weight:700;font-size:11px;letter-spacing:.1em;text-transform:uppercase;padding:5px 10px;border-radius:6px;box-shadow:0 3px 0 #9c2a5d} .game-card .gc-ribbon i{width:7px;height:7px;border-radius:50%;background:#2b0418;display:inline-block;animation:gcPulse 1.4s ease-in-out infinite} @keyframes gcPulse{50%{opacity:.25}} @@ -1179,7 +1186,7 @@ - + diff --git a/qa/run.sh b/qa/run.sh index bf66257..120c3a0 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -6,6 +6,7 @@ # bash qa/run.sh all # public + member + earn # bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) # bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) +# bash qa/run.sh sov-passes # Explorer/Champion tiers: store unit checks + admin buys Explorer with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes) # bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos) # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. @@ -37,6 +38,9 @@ elif [ "$MODE" = "door" ]; then node qa/door.mjs || status=1 elif [ "$MODE" = "gamepass" ]; then node qa/gamepass.mjs || status=1 +elif [ "$MODE" = "sov-passes" ]; then + node qa/sov-passes-store.cjs || status=1 + node qa/sov-passes-local.mjs || status=1 elif [ "$MODE" = "gamepass-games" ]; then node qa/gamepass-games.cjs || status=1 elif [ "$MODE" = "earn" ]; then diff --git a/qa/sov-passes-local.mjs b/qa/sov-passes-local.mjs new file mode 100644 index 0000000..12e9414 --- /dev/null +++ b/qa/sov-passes-local.mjs @@ -0,0 +1,139 @@ +// Explorer / Champion passes end to end on a LOCAL throwaway copy (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md). +// node qa/sov-passes-local.mjs screenshots -> SHOTS (default D:/tmp/sov-passes) +// Boots server.js with a throwaway DATA_DIR and throwaway SOV secret, preloading qa/sov-passes-stub.cjs, which seeds 2500 +// purchased-grade credits on one fake position owned by the admin account. Nothing touches production. +// Covers: sovTiers off -> a member sees and can buy only the weekly pass; the ADMIN_EMAIL account sees the admin preview and buys +// Explorer in the browser through the REAL ads.gamePurchase(purchasedOnly) charge; the 500 left is short for a second Explorer +// (waiting order, $20 package copy); the Shards of Valor hand-off token and GET /api/partner/player carry tier explorer; +// polgrant answers pass: true with the weekly pass caps; Admin > Game Pass shows the tier table. Exit 1 on any failure. +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; + +const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; +const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default; +const PORT = Number(process.env.SOV_PORT || 8798); +const B = 'http://127.0.0.1:' + PORT; +const SHOTS = process.env.SHOTS || 'D:/tmp/sov-passes'; fs.mkdirSync(SHOTS, { recursive: true }); +const SOV = crypto.randomBytes(24).toString('hex'); // throwaway, never printed +const ADMIN_PW = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com', MEMBER = 'qa-sov-member@example.com'; +const SEED_ID = 9001, SEED_CREDITS = 2500; +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovpasses-')); fs.mkdirSync(path.join(DATA, 'uploads')); +let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; }; +const hide = page => page.evaluate(() => { document.querySelectorAll('.lgate,.iap-welcome,#onboardModal').forEach(m => m.hidden = true); }); +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +const srv = spawn(process.execPath, ['-r', './qa/sov-passes-stub.cjs', 'server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'], + env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN_PW, SOV_SSO_SECRET: SOV, DEV_POL_USD: '0.10', + QA_SEED_EMAIL: ADMIN_EMAIL, QA_SEED_ID: String(SEED_ID), QA_SEED_CREDITS: String(SEED_CREDITS) }) }); +let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d); +let browser = null; +const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }; + +async function api(p, o, headers) { + const opts = { method: (o && o.method) || (o && 'data' in o ? 'POST' : 'GET'), headers: Object.assign({ 'Content-Type': 'application/json' }, headers || {}), redirect: 'manual' }; + if (o && 'data' in o) opts.body = JSON.stringify(o.data); + const r = await fetch(B + p, opts); let j = null; try { j = await r.json(); } catch (e) {} + return { status: r.status, j, headers: r.headers }; +} +const adminH = { Authorization: 'Bearer ' + ADMIN_PW }; +async function signIn(email, username) { + const s = await api('/api/auth/email/start', { data: { email, fts: Date.now() - 5000 } }); + const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) }); + const cookies = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]); + const cookie = cookies.join('; '); + if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie }); + return { Cookie: cookie, pairs: cookies.map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1) }; }) }; +} +const decode = tok => JSON.parse(Buffer.from(String(tok).split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')); +async function playerOf(email) { + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SOV).update('player:' + email + ':' + ts).digest('hex'); + const r = await fetch(B + '/api/partner/player?' + new URLSearchParams({ game: 'shardsofvalor', m: '0', e: email, ts, sig })); return { status: r.status, j: await r.json() }; +} +async function grant(body) { + const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SOV).update(ts + '\n' + raw).digest('hex'); + const r = await fetch(B + '/api/partner/polgrant', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': sig }, body: raw }); return r.json(); +} +async function pageFor(h) { + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); + await ctx.addCookies(h.pairs.map(c => ({ name: c.name, value: c.value, url: B }))); + await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} }); // the session pop-up would block every click + const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e))); return { page, errs, ctx }; +} + +try { + let up = false; for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) { up = true; break; } } catch (e) {} await sleep(500); } + ok(up && /qa stub: position #9001/.test(srvLog), 'local copy up with the seeded position', ''); + await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1' } }, adminH); + const site = (await api('/api/admin/site', null, adminH)).j; const sc = (site && (site.site || site)) || {}; + ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 2000 && Number(sc.gamePassChampionPriceCredits) === 4000 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 2000 / Champion 4000 credits, 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits })); + const hA = await signIn(ADMIN_EMAIL, 'qaadmin'), hM = await signIn(MEMBER, 'qasovm'); + + // 1. a member with sovTiers off: weekly only, Explorer refused + let g = (await api('/api/my/gamepass', null, hM)).j; + ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'member, sovTiers off: only the weekly pass is offered', JSON.stringify((g.passes || []).map(x => x.tier))); + let r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hM); + ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'member, sovTiers off: Explorer buy refused', JSON.stringify(r.j)); + browser = await chromium.launch(); + { const { page, errs, ctx } = await pageFor(hM); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 }); + const txt = await page.textContent('#gpCard'); ok(!/Explorer|Champion/.test(txt) && errs.length === 0, 'member page: the weekly card as before, no Explorer/Champion text, no page errors', errs.join(' | ')); + await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '1-member-weekly-only.png') }); await ctx.close(); } + + // 2. the admin: preview of all three, buys Explorer in the browser with the seeded purchased credits (the real charge) + g = (await api('/api/my/gamepass', null, hA)).j; + ok(g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion', 'admin, sovTiers off: preview with all three tiers', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open]))); + { const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes'); + await page.waitForSelector('#gpCard [data-gp-tier="explorer"]', { timeout: 15000 }); await sleep(600); await hide(page); + const txt = await page.textContent('#gpCard'); + ok(/never make you stronger than players who earn their gear/.test(txt) && /main story of Shards of Valor is free/.test(txt) && /Admin preview/.test(txt) && !/\u2014/.test(txt), 'tier card copy: never stronger, main story free, admin preview note, no em dashes', ''); + ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url()); + await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-preview-three-tiers.png') }); + await page.click('#gpCard [data-gp-tier="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 }); + await page.screenshot({ path: path.join(SHOTS, '3-admin-confirm-explorer.png') }); + await page.click('#dlgOk'); + await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {}); + const after = await page.textContent('#gpCard'); + ok(/Explorer active/.test(after) && errs.length === 0, 'after the buy the card shows Explorer active (Central date)', errs.join(' | ')); + await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '4-admin-explorer-active.png') }); await ctx.close(); } + g = (await api('/api/my/gamepass', null, hA)).j; + const ex = g.passes.find(x => x.tier === 'explorer'); + ok(g.active && g.tier === 'explorer' && ex.active && Math.abs(ex.until - (Date.now() + 30 * 86400000)) < 120000, 'GET /api/my/gamepass: tier explorer, 30 days', JSON.stringify({ tier: g.tier, until: ex && new Date(ex.until).toISOString() })); + ok(/gamepass bought with credits explorer qa-admin@example.com 2000/.test(srvLog), 'paid through the real ads.gamePurchase(purchasedOnly) path, 2000 credits', ''); + r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA); + ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'explorer' && r.j.available === 500 && /\$20 package/.test(r.j.message), 'a second Explorer: only 500 purchased credits left -> waiting order, "$20 package"', JSON.stringify({ needPay: r.j.needPay, available: r.j.available, payUrl: r.j.payUrl })); + + // 3. the Shards of Valor hand-off token and the partner player answer carry tier explorer + const ho = await api('/api/my/shardsofvalor', null, hA); + const loc = ho.headers.get('location') || ''; const t = new URL(loc).searchParams.get('t'); const claims = t ? decode(t) : null; + ok(ho.status === 302 && claims && claims.gamePass && claims.gamePass.active === true && claims.gamePass.tier === 'explorer' && claims.gamePass.until === ex.until && !('tiers' in claims.gamePass), 'hand-off token: gamePass { active, until, tier: explorer }', JSON.stringify(claims && claims.gamePass)); + const sig = t && crypto.createHmac('sha256', SOV).update(Buffer.from(t.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')).digest('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + ok(sig && sig === t.split('.')[1], 'the token verifies with SOV_SSO_SECRET', ''); + const pl = await playerOf(ADMIN_EMAIL); + ok(pl.status === 200 && pl.j.pass.active === true && pl.j.pass.tier === 'explorer' && pl.j.pass.tiers && pl.j.pass.tiers.explorer === ex.until && pl.j.pass.tiers.champion === null && pl.j.caps.daily === 1.5 && pl.j.caps.total === 5, 'GET /api/partner/player: pass { active, until, tier: explorer, tiers }, weekly pass caps 1.50 / 5', JSON.stringify(pl.j.pass) + ' ' + JSON.stringify({ d: pl.j.caps.daily, t: pl.j.caps.total })); + const plm = await playerOf(MEMBER); + ok(plm.j.pass.active === false && plm.j.pass.tier === null, 'a free member: pass { active false, tier null }', JSON.stringify(plm.j.pass)); + const gr = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 0.2, ref: 'qa:1' }); + ok(gr.pass === true && gr.allowed === 0.2, 'polgrant: pass true (a boolean) for the Explorer holder', JSON.stringify(gr)); + + // 4. Admin > Game Pass: the tier table + const st = (await api('/api/admin/gamepass/stats', null, adminH)).j; + ok(st.tiers && st.tiers.explorer.active === 1 && st.tiers.explorer.soldTotal === 1 && st.tiers.explorer.usdTotal === 20 && st.tiers.explorer.waitingOrders === 1 && st.tierSales === false, 'admin stats: Explorer 1 active, 1 sold ($20), 1 waiting; sale switch off', JSON.stringify(st.tiers.explorer)); + { const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e))); + await page.goto(B + '/admin', { waitUntil: 'networkidle' }); + await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200); + const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForFunction(() => /Explorer/.test((document.getElementById('gpTiers') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {}); } + const txt = await page.textContent('#gpTiers').catch(() => ''); + ok(/Explorer/.test(txt) && /Champion/.test(txt), 'Admin > Game Pass renders the per-tier table', errs.join(' | ') || (nav ? '' : 'admin nav not found (sign-in flow)')); + await sleep(800); await page.locator('#gpTiers').evaluate(e => e.closest('.card').scrollIntoView()); await sleep(400); await page.locator('#gpTiers').evaluate(e => e.closest('.card').id = 'gpTiersCard'); await page.locator('#gpTiersCard').screenshot({ path: path.join(SHOTS, '5-admin-gamepass-tiers.png') }); await ctx.close(); } +} catch (e) { + console.error('FAIL harness error', e && e.stack || e); fails++; +} finally { + await cleanup(); +} +if (fails) console.log('--- server log (tail) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error|qa stub/.test(l)).slice(-30).join('\n')); +console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS'); +process.exit(fails ? 1 : 0); diff --git a/qa/sov-passes-store.cjs b/qa/sov-passes-store.cjs new file mode 100644 index 0000000..698dcb0 --- /dev/null +++ b/qa/sov-passes-store.cjs @@ -0,0 +1,150 @@ +// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md section 8): unit checks of the gamepass.js store, no server. +// node qa/sov-passes-store.cjs +// Loads gamepass.js with in-memory maps and a fake site config. Covers: lazy migration of a weekly-only record, buy per tier, +// extend from max(now, until), side-by-side expiry, highest active tier wins, the sovTiers switch (off refuses, admin may buy), +// waiting orders per tier fulfilled by a big-enough package (each tx once, highest price first), the same caps for every tier +// (no extra POL), comp and revoke, admin stats per tier (each account once at its top tier, Central week/month). Exit 1 on failure. +'use strict'; +const fs = require('fs'); const os = require('os'); const path = require('path'); +const gp = require('../gamepass'); +const DAY = 86400000; +let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; }; +const SC = { gamePassEnabled: '1', sovTiers: '0', capsStartDate: '2026-10-01' }; +const maps = {}; +const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovstore-')); +gp.init({ dataDir, siteConfig: () => Object.assign({}, SC), persistedMap: k => (maps[k] = maps[k] || new Map()), isProd: false, + accounts: { byMemberId: async () => null, byEmail: async () => null }, marks: { claim: async () => true }, polUsd: async () => 0.1, telegram: async () => {}, notify: async () => {} }); +const passes = maps.gamepass, orders = maps.gporders; +const T0 = Date.parse('2026-10-20T17:00:00Z'); // Tue Oct 20, noon Central +const paid = async () => ({ ok: true, campaignId: 1 }); +const short = async () => ({ error: 'short', available: 0, need: 1 }); + +(async () => { + // 1. migration: a record from before tiers (until only) reads as the weekly tier; flag answers as before plus tier + passes.set('old@x.com', { until: T0 + 3 * DAY, bought: [{ ts: T0 - 4 * DAY, via: 'credits', usd: 5, days: 7 }] }); + let f = gp.flag('old@x.com', T0); + ok(f.active === true && f.until === T0 + 3 * DAY && f.tier === 'weekly' && f.tiers.weekly === T0 + 3 * DAY && f.tiers.explorer === null, 'weekly-only record migrates: active, same until, tier weekly', JSON.stringify(f)); + f = gp.flag('old@x.com', T0 + 5 * DAY); + ok(f.active === false && f.tier === null && f.until === T0 + 3 * DAY, 'expired weekly-only record: inactive, until kept as before tiers, tier null', JSON.stringify(f)); + f = gp.flag('never@x.com', T0); ok(f.active === false && f.until === null && f.tier === null, 'never bought: { active false, until null, tier null }', JSON.stringify(f)); + await gp.buy('old@x.com', paid, T0, 'weekly'); + const oldRec = passes.get('old@x.com'); + ok(oldRec.tiers && oldRec.tiers.weekly.until === T0 + 10 * DAY && oldRec.until === T0 + 10 * DAY, 'buying weekly on a migrated record extends from its until and writes tiers + legacy until', JSON.stringify({ until: oldRec.until, tiers: oldRec.tiers })); + + // 2. the switch: off refuses Explorer/Champion for members, the weekly pass is unchanged; the admin may buy + let r = await gp.buy('a@x.com', paid, T0, 'explorer'); + ok(r.error === 'The Explorer pass is not open yet.', 'sovTiers off: Explorer refused', JSON.stringify(r)); + r = await gp.buy('a@x.com', paid, T0, 'champion'); + ok(r.error === 'The Champion pass is not open yet.', 'sovTiers off: Champion refused', JSON.stringify(r)); + ok(!passes.get('a@x.com'), 'a refused buy writes nothing', ''); + let v = gp.view('a@x.com', T0); + ok(v.passes.length === 1 && v.passes[0].tier === 'weekly' && v.show === true && v.tierPreview === false, 'sovTiers off: a member sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier))); + v = gp.view('admin@x.com', T0, { admin: true }); + ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion' && v.tierPreview === true && v.passes[1].open === true && v.passes[1].price === 2000 && v.passes[2].price === 4000 && v.passes[1].days === 30, 'sovTiers off: the admin sees all three (preview), prices 2000 / 4000, 30 days', JSON.stringify(v.passes)); + r = await gp.buy('admin@x.com', paid, T0, 'explorer', { admin: true }); + ok(r.ok && r.tier === 'explorer' && r.until === T0 + 30 * DAY && r.days === 30, 'sovTiers off: the admin can buy Explorer (testing)', JSON.stringify(r)); + r = await gp.buy('a@x.com', paid, T0); // tier missing = weekly + ok(r.ok && r.tier === 'weekly' && r.until === T0 + 7 * DAY && r.days === 7, 'tier missing = weekly: 500 credits, 7 days, as before', JSON.stringify(r)); + let charged = null; await gp.buy('z@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0); + ok(charged && charged.price === 500 && charged.label === 'Game Pass (7 days)', 'weekly charge unchanged: 500 credits, label "Game Pass (7 days)"', JSON.stringify(charged)); + r = await gp.buy('a@x.com', paid, T0, 'platinum'); ok(r.error === 'There is no such pass.', 'unknown tier refused', JSON.stringify(r)); + SC.gamePassEnabled = '0'; SC.sovTiers = '1'; + r = await gp.buy('a@x.com', paid, T0, 'explorer'); ok(!!r.error, 'sovTiers on but the weekly Game Pass off: Explorer refused for members', JSON.stringify(r)); + SC.gamePassEnabled = '1'; + + // 3. on: each tier extends only itself; buying again extends from max(now, until) + charged = null; r = await gp.buy('b@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0, 'explorer'); + ok(r.ok && r.until === T0 + 30 * DAY && charged.price === 2000 && charged.label === 'Explorer pass (30 days)', 'sovTiers on: Explorer charges 2000 credits, 30 days', JSON.stringify(charged)); + let rec = passes.get('b@x.com'); + ok(rec.tiers.explorer.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.champion && rec.until === 0 && rec.bought[0].tier === 'explorer' && rec.bought[0].usd === 20, 'only the Explorer tier moved; legacy until (weekly) stays 0; bought row has tier + $20', JSON.stringify(rec)); + r = await gp.buy('b@x.com', paid, T0 + 10 * DAY, 'explorer'); + ok(r.until === T0 + 60 * DAY, 'Explorer again while active: extends from its until (+30 days, nothing lost)', new Date(r.until).toISOString()); + r = await gp.buy('c@x.com', paid, T0, 'champion'); ok(r.ok && r.until === T0 + 30 * DAY, 'Champion: 30 days', ''); + r = await gp.buy('c@x.com', paid, T0 + 45 * DAY, 'champion'); + ok(r.until === T0 + 75 * DAY, 'Champion again after it ended: extends from now', new Date(r.until).toISOString()); + charged = null; await gp.buy('c2@x.com', async (price) => { charged = price; return { ok: true }; }, T0, 'champion'); ok(charged === 4000, 'Champion charges 4000 credits', String(charged)); + + // 4. side by side: Champion over Explorer, then Explorer shows through; weekly underneath + await gp.buy('d@x.com', paid, T0, 'weekly'); // weekly to T0+7 + await gp.buy('d@x.com', paid, T0, 'explorer'); // explorer to T0+30 + await gp.buy('d@x.com', paid, T0 - 20 * DAY, 'champion'); // champion bought earlier, to T0+10 + f = gp.flag('d@x.com', T0 + DAY); + ok(f.tier === 'champion' && f.until === T0 + 10 * DAY && f.active && f.tiers.weekly === T0 + 7 * DAY && f.tiers.explorer === T0 + 30 * DAY && f.tiers.champion === T0 + 10 * DAY, 'all three on: tier champion, until = Champion end, tiers side by side', JSON.stringify(f)); + f = gp.flag('d@x.com', T0 + 12 * DAY); + ok(f.tier === 'explorer' && f.until === T0 + 30 * DAY && f.tiers.champion === null && f.tiers.weekly === null, 'Champion ended: Explorer shows through', JSON.stringify(f)); + f = gp.flag('d@x.com', T0 + 31 * DAY); ok(f.active === false && f.tier === null, 'all ended: no pass', JSON.stringify(f)); + + // 5. no extra POL: the caps are identical for weekly, explorer and champion holders (and higher than free) + const day = '2026-10-21'; const at = Date.parse(day + 'T17:00:00Z'); + await gp.buy('w@x.com', paid, at, 'weekly'); await gp.buy('e@x.com', paid, at, 'explorer'); await gp.buy('ch@x.com', paid, at, 'champion'); + const capsOf = e => { const c = gp.capsFor(e, at); return [c.pass, c.daily, c.total].join('/'); }; + ok(capsOf('w@x.com') === capsOf('e@x.com') && capsOf('e@x.com') === capsOf('ch@x.com') && capsOf('w@x.com') === 'true/1.5/5' && capsOf('free@x.com') === 'false/0.3/2', 'capsFor: weekly = explorer = champion = pass caps 1.50 / 5', [capsOf('w@x.com'), capsOf('e@x.com'), capsOf('ch@x.com'), capsOf('free@x.com')].join(' ')); + const g = e => gp.grant({ email: e, game: 'polhunter', kind: 'daily', pol: 3, ref: 'cap:' + e, now: at }); + const gw = g('w@x.com'), ge = g('e@x.com'), gc = g('ch@x.com'); + ok(gw.allowed === 1.5 && ge.allowed === 1.5 && gc.allowed === 1.5 && gw.pass && ge.pass && gc.pass, 'polgrant: a 3 POL daily grant allows 1.50 for every tier, pass: true (a boolean)', [gw.allowed, ge.allowed, gc.allowed, typeof gc.pass].join(' ')); + + // 6. waiting orders per tier; a package of at least the tier price fulfils it; each tx once; highest-priced first + r = await gp.buy('p@x.com', short, T0, 'explorer'); + ok(r.needPay && r.tier === 'explorer' && r.payUrl === '/my?from=gamepass&tier=explorer#buy' && r.package === 20 && /\$20 package/.test(r.message), 'Explorer short: waiting order, payUrl with tier, "$20 package"', JSON.stringify({ payUrl: r.payUrl, msg: r.message })); + const ordE = r.order; + r = await gp.buy('p@x.com', short, T0, 'explorer'); ok(r.order === ordE, 'same tier again reuses its waiting order', ''); + r = await gp.buy('p@x.com', short, T0, 'champion'); const ordC = r.order; + ok(r.needPay && r.order !== ordE && r.package === 50 && /\$50 package/.test(r.message), 'Champion short: its own waiting order; copy names the $50 package (there is no $40 one)', r.message); + r = await gp.buy('p@x.com', short, T0, 'weekly'); + ok(r.payUrl === '/my?from=gamepass#buy' && /Buy a \$5 package/.test(r.message), 'weekly short: payUrl and copy exactly as before', r.payUrl); + let ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xa1', ts: T0 + 60000, devEmail: 'p@x.com' }); + ok(ev && ev.tier === 'weekly', 'a $5 package fulfils the weekly order, not Explorer or Champion', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 1000, tx: '0xa2', ts: T0 + 60000, devEmail: 'p@x.com' }); + ok(ev === null, 'a $10 package fulfils nothing (Explorer needs $20)', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 2000, tx: '0xa3', ts: T0 + 60000, devEmail: 'p@x.com' }); + ok(ev && ev.tier === 'explorer' && ev.order === ordE && ev.until === T0 + 60000 + 30 * DAY, 'a $20 package fulfils the Explorer order', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 2000, tx: '0xa3', ts: T0 + 60000, devEmail: 'p@x.com' }); + ok(ev === null, 'the same tx again counts once', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 5000, tx: '0xa4', ts: T0 + 60000, devEmail: 'p@x.com' }); + ok(ev && ev.tier === 'champion' && ev.order === ordC, 'a $50 package fulfils the Champion order', JSON.stringify(ev)); + await gp.buy('q@x.com', short, T0, 'weekly'); await gp.buy('q@x.com', short, T0, 'explorer'); await gp.buy('q@x.com', short, T0, 'champion'); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 2000, tx: '0xb1', ts: T0, devEmail: 'q@x.com' }); + ok(ev && ev.tier === 'explorer', 'three orders waiting, a $20 package: the highest-priced one it covers (Explorer) is fulfilled first', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 50000, tx: '0xb2', ts: T0, devEmail: 'q@x.com' }); + ok(ev && ev.tier === 'champion', 'then a $500 package: Champion (one pass per purchase)', JSON.stringify(ev)); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xb3', ts: T0, devEmail: 'q@x.com' }); + ok(ev && ev.tier === 'weekly', 'then a $5 package: the weekly order', JSON.stringify(ev)); + // an old waiting order (no tier field) is a weekly order + orders.set('gp-legacy', { status: 'waiting', email: 'leg@x.com', ts: T0 }); + ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xc1', ts: T0, devEmail: 'leg@x.com' }); + ok(ev && ev.tier === 'weekly' && ev.order === 'gp-legacy', 'a waiting order from before tiers is fulfilled as weekly', JSON.stringify(ev)); + + // 7. comp and revoke + let cp = gp.comp('k@x.com', 'qa', 'champion', T0); f = gp.flag('k@x.com', T0 + 1); + ok(cp.tier === 'champion' && f.tier === 'champion' && passes.get('k@x.com').bought[0].via === 'admin' && passes.get('k@x.com').bought[0].usd === 0, 'comp champion: an admin row worth $0', JSON.stringify(cp)); + let rv = gp.revoke('k@x.com', 'champion', 'refund qa', T0 + DAY); + ok(rv.ok && gp.flag('k@x.com', T0 + DAY + 1).active === false && passes.get('k@x.com').revokes[0].tier === 'champion', 'revoke ends the tier now and records it', JSON.stringify(rv)); + rv = gp.revoke('k@x.com', 'champion', 'again', T0 + 2 * DAY); ok(!!rv.error, 'revoking an inactive tier is refused', rv.error); + + // 8. admin stats: each account once at its top tier, Central week and month + for (const k of [...passes.keys()]) passes.delete(k); for (const k of [...orders.keys()]) orders.delete(k); + const NOW = Date.parse('2026-11-04T18:00:00Z'); // Wed Nov 4, noon Central (CST); week from Mon Nov 2, month from Nov 1 + await gp.buy('s1@x.com', paid, Date.parse('2026-11-02T06:30:00Z'), 'weekly'); // Mon Nov 2 00:30 Central: this week + await gp.buy('s1@x.com', paid, Date.parse('2026-11-02T05:30:00Z'), 'explorer'); // Sun Nov 1 23:30 Central: last week, this month + await gp.buy('s2@x.com', paid, Date.parse('2026-11-01T04:30:00Z'), 'champion'); // Oct 31 23:30 Central: last month + await gp.buy('s2@x.com', paid, Date.parse('2026-11-03T18:00:00Z'), 'champion'); // a renewal this week + await gp.buy('s3@x.com', paid, NOW - 2 * DAY, 'weekly'); // ends within 7 Central days + gp.comp('s4@x.com', 'qa', 'explorer', NOW - DAY); + await gp.buy('s5@x.com', short, NOW, 'champion'); + const st = gp.adminStats(NOW); const S = st.tiers; + ok(S.weekly.active === 1 && S.explorer.active === 2 && S.champion.active === 1, 'active counts each account once at its top tier (s1 = explorer, not weekly)', JSON.stringify({ w: S.weekly.active, e: S.explorer.active, c: S.champion.active })); + ok(S.weekly.soldWeek === 2 && S.explorer.soldWeek === 0 && S.explorer.soldMonth === 1 && S.champion.soldWeek === 1 && S.champion.soldMonth === 1 && S.champion.soldTotal === 2 && S.champion.usdTotal === 80, 'Central week (from Mon 00:00) and month (from the 1st 00:00) boundaries', JSON.stringify({ w: [S.weekly.soldWeek, S.weekly.soldMonth], e: [S.explorer.soldWeek, S.explorer.soldMonth], c: [S.champion.soldWeek, S.champion.soldMonth, S.champion.soldTotal, S.champion.usdTotal] })); + ok(S.champion.renewals30d === 1 && S.weekly.renewals30d === 0, 'renewals30d: a second Champion purchase by a Champion holder', String(S.champion.renewals30d)); + ok(S.weekly.expiring7d === 2 && S.explorer.comped === 1 && S.champion.waitingOrders === 1, 'expiring7d (weekly passes ending in 7 Central days), comped, waiting orders per tier', JSON.stringify({ exp: S.weekly.expiring7d, comped: S.explorer.comped, wait: S.champion.waitingOrders })); + ok(st.passes.active === 4 && st.passes.soldTotal === 5 && st.passes.comped === 1 && st.passes.waitingOrders === 1, 'the existing all-tier passes block still adds up', JSON.stringify(st.passes)); + + // 9. the tournament pool: weekly sales only unless passTournamentTierSales + const rows = await gp.runTournament(Date.parse('2026-11-03T18:00:00Z'), { force: true }); + ok(rows.sales === 2 && rows.salesUsd === 10, 'passTournamentTierSales off: only the 2 weekly sales ($10) feed the pool', JSON.stringify({ sales: rows.sales, usd: rows.salesUsd })); + SC.passTournamentTierSales = '1'; + const rows2 = await gp.runTournament(Date.parse('2026-11-03T18:00:00Z'), { force: true }); + ok(rows2.sales === 3 && rows2.salesUsd === 50, 'passTournamentTierSales on: the Champion renewal ($40) is added', JSON.stringify({ sales: rows2.sales, usd: rows2.salesUsd })); + try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch (e) {} + console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS'); + process.exit(fails ? 1 : 0); +})().catch(e => { console.error('FAIL harness error', e && e.stack || e); process.exit(1); }); diff --git a/qa/sov-passes-stub.cjs b/qa/sov-passes-stub.cjs new file mode 100644 index 0000000..3dff7de --- /dev/null +++ b/qa/sov-passes-stub.cjs @@ -0,0 +1,19 @@ +// LOCAL TESTS ONLY (qa/sov-passes-local.mjs preloads it with `node -r`): seeds purchased-grade credits on one fake position so the +// REAL ads.gamePurchase(purchasedOnly) path can be exercised without a chain. Refuses to load in production. +// QA_SEED_EMAIL the account that owns the position (gets memberId QA_SEED_ID on its sessions) +// QA_SEED_ID the fake position's member id +// QA_SEED_CREDITS the on-chain credit balance that position reports +'use strict'; +if (process.env.NODE_ENV === 'production') throw new Error('qa/sov-passes-stub.cjs must never load in production'); +const path = require('path'); +const SITE = path.resolve(__dirname, '..'); +const chain = require(path.join(SITE, 'chain.js')); +const auth = require(path.join(SITE, 'auth.js')); +const EMAIL = String(process.env.QA_SEED_EMAIL || '').toLowerCase(), ID = Number(process.env.QA_SEED_ID) || 0, CREDITS = Number(process.env.QA_SEED_CREDITS) || 0; +const origBal = chain.creditBalance; +chain.creditBalance = async (id, type) => (ID && Number(id) === ID) ? CREDITS : origBal(id, type); +const origMember = chain.member; +chain.member = async id => (ID && Number(id) === ID) ? null : origMember(id); +const origRefresh = auth.refreshMemberId; +auth.refreshMemberId = async sess => (sess && EMAIL && String(sess.email || '').toLowerCase() === EMAIL) ? ID : origRefresh(sess); +console.log('qa stub: position #' + ID + ' holds ' + CREDITS + ' purchased credits for ' + EMAIL); diff --git a/server.js b/server.js index a807882..71d0aca 100644 --- a/server.js +++ b/server.js @@ -685,7 +685,8 @@ async function polUsdLive() { const v = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); if (v > 0) { polUsdCache.v = v; polUsdCache.at = Date.now(); } return v; } // the Game Pass flag rides in every sign-in hand-off token (3a: games get it at sign-in and on every polgrant answer) -const gpClaim = c => (c && c.email && (!c.kind || c.kind === 'sso')) ? { gamePass: gamepass.flag(c.email) } : {}; +// gamePass: { active, until, tier } (tier = the highest active pass: weekly | explorer | champion | null; a game treats a missing tier as weekly) +const gpClaim = c => { if (!(c && c.email && (!c.kind || c.kind === 'sso'))) return {}; const f = gamepass.flag(c.email); return { gamePass: { active: f.active, until: f.until, tier: f.tier } }; }; function siteConfig() { let saved = {}; try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {} @@ -716,6 +717,11 @@ function siteConfig() { geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else // Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5, + // Explorer ($20) and Champion ($40) monthly passes beside the weekly one (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md): islands and looks + // in Shards of Valor, never power, never more POL (same caps as the weekly pass). sovTiers = the sale switch for both (off: only ADMIN_EMAIL + // sees and can buy them, for testing; holders keep their pass). gamePassEnabled '0' stops one tier alone. passTournamentTierSales '1' + // would add their sales to the Pass Tournament pool (off = the pool exactly as before). + sovTiers: '0', gamePassExplorerEnabled: '1', gamePassExplorerPriceCredits: 2000, gamePassExplorerDays: 30, gamePassChampionEnabled: '1', gamePassChampionPriceCredits: 4000, gamePassChampionDays: 30, passTournamentTierSales: '0', supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat) @@ -3809,7 +3815,7 @@ const server = http.createServer(async (req, res) => { const m = Number(u.searchParams.get('m')) || 0, e = String(u.searchParams.get('e') || '').trim().toLowerCase(), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || ''); if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:' + (m > 0 ? String(m) : e) + ':' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); - const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null } }); + const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null, tier: null, tiers: { weekly: null, explorer: null, champion: null } } }); const now = gpDevNow(u.searchParams.get('devDay')); return json(res, 200, { ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email), pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled }); @@ -3842,7 +3848,7 @@ const server = http.createServer(async (req, res) => { } if (p === '/api/my/gamepass' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay')))); + return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay')), { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL })); } if (p === '/api/my/gamepass/buy' && req.method === 'POST') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); @@ -3850,14 +3856,21 @@ const server = http.createServer(async (req, res) => { const b = await readBody(req); const { ids } = await myMemberIds(s); // purchased-grade credits only, from a position's package balance (the PolyWarriors mint rule); devPaid = local tests only const charge = (!IS_PROD && b.devPaid) ? async () => ({ ok: true, campaignId: 0, dev: true }) : (price, label) => ads.gamePurchase(s.email, ids, price, label, 'https://instantadpay.com/my#games', { purchasedOnly: true }); - const r = await gamepass.buy(s.email, charge, gpDevNow(b.devDay)); + // tier: weekly (missing) | explorer | champion; Explorer/Champion are refused unless sovTiers is on, except for the ADMIN_EMAIL account (testing) + const r = await gamepass.buy(s.email, charge, gpDevNow(b.devDay), b.tier, { admin: !!ADMIN_EMAIL && String(s.email).toLowerCase() === ADMIN_EMAIL }); return json(res, r.error ? 400 : 200, r); } if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email }) }); } // local tests only if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); } if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); - const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80)); console.log('gamepass comp', e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r)); + const tier = String(b.tier || 'weekly').toLowerCase(); if (!gamepass.TIERS.includes(tier)) return json(res, 400, { error: 'unknown tier' }); + const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80), tier); console.log('gamepass comp', tier, e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r)); + } + if (p === '/api/admin/gamepass/revoke' && req.method === 'POST') { // support refund only: ends one tier now (never automatic); the record keeps what it was + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' }); + const r = gamepass.revoke(e, String(b.tier || '').toLowerCase(), String(b.why || 'support').slice(0, 80)); if (!r.error) console.log('gamepass revoke', r.tier, e, b.why || ''); + return json(res, r.error ? 400 : 200, Object.assign({ email: e }, r)); } if (p === '/api/admin/gamepass/tournament/run' && req.method === 'POST') { // settle a week by hand (the Monday job normally does this) if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req);