feat(gamification): Phase 1 — full kill-switch + textbook XP wrapping
Until now the 'gamification' feature flag did nothing: it had no row in
app_settings, the admin couldn't toggle it, awardXP/awardCoins ignored
it, and the CSS only hid three dashboard widgets — XP bars in textbooks
stayed visible regardless.
Phase 1 closes every hole.
Backend (source of truth):
• migration 029 seeds feature_gamification_enabled=1
• new isGamificationEnabled() helper in gamification/_shared.js with a
30s cache + invalidateGamificationCache() for instant admin toggles
• awardXP / awardCoins / updateStreak / unlockAchievement /
checkAchievements all bail out when the flag is off
• /api/gamification/* and /api/shop/* (user routes) return 404 when
disabled; admin routes remain open so the switch itself is reachable
• adminController.updateFeatures gains 'gamification' in the allow-list
and invalidates the cache on flip
Frontend:
• LS.isGamificationEnabled() (synchronous, populated by loadFeatures)
so xp.js + applyCosmetics can bail without a round-trip
• xp.js load/add/flush become no-ops when the flag is off
• applyCosmetics skips the round-trip when off
• CSS .no-gamification rule expanded to cover .hero-xp-badge, .po-xp,
.xp-card, .xp-bar, #frames-section, and a universal [data-gamified]
hook for future blocks
Textbooks (Variant 2 of the plan):
• backend/scripts/wrap_textbook_xp.py — idempotent script that adds
data-gamified to 167 XP tags across 63 textbook files (chapters +
hubs, all subjects/grades). Single CSS rule now hides everything.
Verified end-to-end: with the flag off, awardXP/awardCoins write nothing;
flipping back restores normal behavior.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
wrap_textbook_xp.py — Add `data-gamified` attribute to XP UI in textbooks.
|
||||
|
||||
Part of Phase 1 of the gamification kill-switch (Variant 2 of plan §E.3).
|
||||
The CSS rule `body.no-gamification [data-gamified] { display:none }`
|
||||
catches every wrapped block in one selector, so future authors don't have
|
||||
to invent new class names just to be hidden by the master switch.
|
||||
|
||||
What we wrap:
|
||||
• <div id="hero-xp-badge" ...> — chapter & hub hero badges
|
||||
• <div class="po-xp" ...> — hub overall-progress XP pill
|
||||
• <div class="xp-card" ...> — chapter inline progress card
|
||||
• inline JS that generates `<div class="xp-card">` HTML strings
|
||||
• `.xp-bar` containers when they're standalone
|
||||
|
||||
Idempotent: if `data-gamified` is already present on an opening tag the
|
||||
script skips it. Reports each file touched.
|
||||
|
||||
Run from repo root:
|
||||
python backend/scripts/wrap_textbook_xp.py
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2] / "frontend" / "textbooks"
|
||||
if not ROOT.is_dir():
|
||||
print(f"[wrap-xp] textbook dir not found: {ROOT}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Selectors that mark an opening tag as an XP block. The first group
|
||||
# captures `<tag` + attributes UP TO (but not including) the existing
|
||||
# `class="..."` / `id="..."` we matched, so we can splice in
|
||||
# `data-gamified` before the closing `>`.
|
||||
PATTERNS = [
|
||||
# <... id="hero-xp-badge" ...>
|
||||
re.compile(r'(<[a-zA-Z][^>]*?\bid="hero-xp-badge"[^>]*?)(>)'),
|
||||
# <... class="po-xp" ...> or class="...po-xp..."
|
||||
re.compile(r'(<[a-zA-Z][^>]*?\bclass="[^"]*\bpo-xp\b[^"]*"[^>]*?)(>)'),
|
||||
# <... class="...xp-card..."> — covers HTML and inline JS `'<div class="xp-card">'`
|
||||
re.compile(r'(<[a-zA-Z][^>]*?\bclass="[^"]*\bxp-card\b[^"]*"[^>]*?)(>)'),
|
||||
# Standalone class="hero-xp-badge"
|
||||
re.compile(r'(<[a-zA-Z][^>]*?\bclass="[^"]*\bhero-xp-badge\b[^"]*"[^>]*?)(>)'),
|
||||
]
|
||||
|
||||
# Already-wrapped check
|
||||
RX_HAS_ATTR = re.compile(r'\bdata-gamified\b')
|
||||
|
||||
|
||||
def patch_file(path: Path) -> int:
|
||||
"""Return number of opening tags newly given data-gamified."""
|
||||
text = path.read_text(encoding="utf-8")
|
||||
new = text
|
||||
changes = 0
|
||||
for rx in PATTERNS:
|
||||
def sub(m, _rx=rx):
|
||||
nonlocal changes
|
||||
head, close = m.group(1), m.group(2)
|
||||
if RX_HAS_ATTR.search(head):
|
||||
return m.group(0)
|
||||
changes += 1
|
||||
sep = "" if head.endswith(" ") else " "
|
||||
return f'{head}{sep}data-gamified{close}'
|
||||
new = rx.sub(sub, new)
|
||||
if new != text:
|
||||
path.write_text(new, encoding="utf-8")
|
||||
return changes
|
||||
|
||||
|
||||
def main():
|
||||
files = sorted(ROOT.glob("*.html"))
|
||||
total_files = 0
|
||||
total_tags = 0
|
||||
for f in files:
|
||||
try:
|
||||
n = patch_file(f)
|
||||
except Exception as e:
|
||||
print(f"[wrap-xp] {f.name}: ERROR {e}", file=sys.stderr)
|
||||
continue
|
||||
if n:
|
||||
print(f"[wrap-xp] {f.name}: +{n} tag(s)")
|
||||
total_files += 1
|
||||
total_tags += n
|
||||
print(f"[wrap-xp] done — patched {total_tags} tags across {total_files} files "
|
||||
f"(scanned {len(files)})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -509,10 +509,12 @@ function getFeatures(_req, res) {
|
||||
/* ── PATCH /api/admin/features ──────────────────────────────────────── */
|
||||
function updateFeatures(req, res) {
|
||||
const allowed = ['crossword', 'hangman', 'pet', 'red_book', 'collection',
|
||||
'flashcards', 'knowledge_map', 'board', 'biochem', 'live_quiz', 'classroom'];
|
||||
'flashcards', 'knowledge_map', 'board', 'biochem', 'live_quiz', 'classroom',
|
||||
'gamification'];
|
||||
const updates = req.body;
|
||||
const stmt = db.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)");
|
||||
const getOld = db.prepare("SELECT value FROM app_settings WHERE key = ?");
|
||||
let touchedGamification = false;
|
||||
for (const [name, enabled] of Object.entries(updates)) {
|
||||
if (!allowed.includes(name)) continue;
|
||||
const settingKey = `feature_${name}_enabled`;
|
||||
@@ -521,6 +523,15 @@ function updateFeatures(req, res) {
|
||||
const newVal = enabled ? '1' : '0';
|
||||
stmt.run(settingKey, newVal);
|
||||
audit(req, 'feature.update', `feature:${name}`, `${oldVal} -> ${newVal}`);
|
||||
if (name === 'gamification') touchedGamification = true;
|
||||
}
|
||||
// Invalidate the gamification cache so the kill-switch takes effect
|
||||
// immediately (otherwise awardXP keeps running for up to 30s).
|
||||
if (touchedGamification) {
|
||||
try {
|
||||
const { invalidateGamificationCache } = require('./gamification/_shared');
|
||||
invalidateGamificationCache();
|
||||
} catch { /* defensive — shouldn't fail */ }
|
||||
}
|
||||
res.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -187,8 +187,42 @@ const stmts = {
|
||||
ORDER BY up.purchased_at DESC LIMIT 20`),
|
||||
};
|
||||
|
||||
/* ── Kill-switch ─────────────────────────────────────────────────
|
||||
The 'gamification' feature flag is the master switch. When admin
|
||||
turns it off, ALL XP/coin awards become no-ops, /api/gamification
|
||||
routes return 404, and the front-end hides every XP/coin/streak
|
||||
element via body.no-gamification.
|
||||
|
||||
The flag is read often (every awardXP call) so we cache the value
|
||||
and only re-read after a short TTL. Toggling the flag also calls
|
||||
invalidateGamificationCache() from adminController so the change
|
||||
takes effect immediately without waiting for the TTL. */
|
||||
const _gamCache = { value: null, expiresAt: 0 };
|
||||
const _GAM_TTL_MS = 30_000;
|
||||
const _stmtFeatureGam = db.prepare("SELECT value FROM app_settings WHERE key = 'feature_gamification_enabled'");
|
||||
|
||||
function isGamificationEnabled() {
|
||||
const now = Date.now();
|
||||
if (_gamCache.value !== null && now < _gamCache.expiresAt) return _gamCache.value;
|
||||
let on = true;
|
||||
try {
|
||||
const row = _stmtFeatureGam.get();
|
||||
// Default ON if row missing (migration 029 seeds '1', but be defensive).
|
||||
on = !row || row.value === '1';
|
||||
} catch { on = true; }
|
||||
_gamCache.value = on;
|
||||
_gamCache.expiresAt = now + _GAM_TTL_MS;
|
||||
return on;
|
||||
}
|
||||
|
||||
function invalidateGamificationCache() {
|
||||
_gamCache.value = null;
|
||||
_gamCache.expiresAt = 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
xpToLevel, levelMinXp, levelMaxXp, rankName, RANKS,
|
||||
GOAL_TIERS, ACHIEVEMENT_DEFS, AVATAR_FRAMES,
|
||||
stmts,
|
||||
isGamificationEnabled, invalidateGamificationCache,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ const sse = require('../../sse');
|
||||
const { pushParentNotif } = require('../../utils/notifications');
|
||||
const {
|
||||
stmts, xpToLevel, levelMinXp, levelMaxXp, rankName,
|
||||
GOAL_TIERS, ACHIEVEMENT_DEFS,
|
||||
GOAL_TIERS, ACHIEVEMENT_DEFS, isGamificationEnabled,
|
||||
} = require('./_shared');
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════
|
||||
@@ -16,12 +16,14 @@ const {
|
||||
/* ── Coins ─────────────────────────────────────────────────────────── */
|
||||
function awardCoins(userId, amount /*, reason */) {
|
||||
if (!amount || amount <= 0) return;
|
||||
if (!isGamificationEnabled()) return; // master kill-switch
|
||||
stmts.incrCoins.run(amount, userId);
|
||||
}
|
||||
|
||||
/* ── XP ────────────────────────────────────────────────────────────── */
|
||||
function awardXP(userId, amount, reason) {
|
||||
if (!amount || amount <= 0) return;
|
||||
if (!isGamificationEnabled()) return; // master kill-switch
|
||||
stmts.insertXpLog.run(userId, amount, reason);
|
||||
stmts.incrXP.run(amount, userId);
|
||||
const user = stmts.getXP.get(userId);
|
||||
@@ -52,6 +54,7 @@ function getXPInfo(userId) {
|
||||
|
||||
/* ── Streak (called by onTestFinished) ─────────────────────────────── */
|
||||
function updateStreak(userId) {
|
||||
if (!isGamificationEnabled()) return;
|
||||
const user = stmts.getStreak.get(userId);
|
||||
if (!user) return;
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
@@ -103,6 +106,7 @@ function pushAchievementNotif(userId, ach) {
|
||||
}
|
||||
|
||||
function unlockAchievement(userId, slug) {
|
||||
if (!isGamificationEnabled()) return false;
|
||||
const ach = stmts.getAchBySlug.get(slug);
|
||||
if (!ach) return false;
|
||||
const exists = stmts.hasUserAch.get(userId, ach.id);
|
||||
@@ -114,6 +118,7 @@ function unlockAchievement(userId, slug) {
|
||||
}
|
||||
|
||||
function checkAchievements(userId) {
|
||||
if (!isGamificationEnabled()) return;
|
||||
const row = stmts.getUserForAch.get(userId);
|
||||
if (!row) return;
|
||||
const { test_count: testCount, perfect_count: perfectCount, class_count: classCount } = row;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 029: Seed the gamification feature flag
|
||||
--
|
||||
-- Until now there was no row for feature_gamification_enabled in
|
||||
-- app_settings — meaning /api/features returned `gamification: undefined`
|
||||
-- and the front-end kill-switch (`body.no-gamification`) never engaged,
|
||||
-- regardless of admin intent.
|
||||
--
|
||||
-- Default = ON. Admins can disable via PATCH /api/admin/features
|
||||
-- once 'gamification' is added to the allowed list (handled in
|
||||
-- adminController.js, not this migration).
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
INSERT OR IGNORE INTO app_settings (key, value)
|
||||
VALUES ('feature_gamification_enabled', '1');
|
||||
@@ -8,6 +8,18 @@ const {
|
||||
onLabExperiment, selfAward,
|
||||
adminAward, adminReset, adminGamStats, adminGetUser
|
||||
} = require('../controllers/gamificationController');
|
||||
const { isGamificationEnabled } = require('../controllers/gamification/_shared');
|
||||
|
||||
/* When gamification is globally disabled, user-facing routes return 404.
|
||||
Admin routes (under /admin/*) stay accessible so the kill-switch itself
|
||||
can still be flipped from the panel. */
|
||||
function gamGate(req, res, next) {
|
||||
if (req.path.startsWith('/admin/')) return next();
|
||||
if (!isGamificationEnabled()) {
|
||||
return res.status(404).json({ error: 'Gamification disabled' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
const labLimiter = rateLimit({ windowMs: 60_000, max: 30, message: 'Слишком частые запросы лаборатории' });
|
||||
const labSchema = { body: { reactionsDiscovered: { type: 'number', min: 0, max: 100, integer: true } } };
|
||||
@@ -22,6 +34,7 @@ const selfAwardSchema = {
|
||||
};
|
||||
|
||||
router.use(authMiddleware);
|
||||
router.use(gamGate);
|
||||
|
||||
router.get('/me', getMe);
|
||||
router.get('/achievements', getAchievements);
|
||||
|
||||
@@ -6,6 +6,16 @@ const {
|
||||
getItems, purchaseItem, getPurchases, getCoins, getMyActive, activateItem,
|
||||
adminGetItems, adminCreateItem, adminUpdateItem, adminDeleteItem, adminAwardCoins, adminShopStats
|
||||
} = require('../controllers/shopController');
|
||||
const { isGamificationEnabled } = require('../controllers/gamification/_shared');
|
||||
|
||||
/* Same kill-switch as gamification routes — shop is part of the gam loop. */
|
||||
function shopGate(req, res, next) {
|
||||
if (req.path.startsWith('/admin/')) return next();
|
||||
if (!isGamificationEnabled()) {
|
||||
return res.status(404).json({ error: 'Gamification disabled' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
const purchaseLimiter = rateLimit({ windowMs: 60_000, max: 10, message: 'Слишком много покупок, подождите минуту' });
|
||||
const activateSchema = { body: { type: { type: 'string', oneOf: ['frame', 'title', 'effect'] } } };
|
||||
@@ -20,6 +30,7 @@ const awardCoinsSchema = { body: {
|
||||
}};
|
||||
|
||||
router.use(authMiddleware);
|
||||
router.use(shopGate);
|
||||
|
||||
router.get('/items', getItems);
|
||||
router.post('/items/:id/purchase', requirePermission('shop.purchase'), purchaseLimiter, purchaseItem);
|
||||
|
||||
Reference in New Issue
Block a user