Files
Learn_System/backend/src/routes/gamification.js
T
Maxim Dolgolyov 660e7e2747 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>
2026-05-29 19:43:24 +03:00

67 lines
3.1 KiB
JavaScript

const router = require('express').Router();
const { authMiddleware, requireRole, requirePermission } = require('../middleware/auth');
const validate = require('../middleware/validate');
const rateLimit = require('../middleware/rateLimit');
const {
getMe, getAchievements, getLeaderboard, getXPHistory,
getChallenges, claimChallenge, setGoalTier, getFrames, setFrame,
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 } } };
const tbLimiter = rateLimit({ windowMs: 60_000, max: 30, message: 'Слишком частые начисления XP' });
const selfAwardSchema = {
body: {
amount: { type: 'number', required: true, min: 1, max: 50, integer: true },
source: { type: 'string', required: true, minLen: 1, maxLen: 60,
match: /^[a-z0-9_-]{1,60}$/i },
},
};
router.use(authMiddleware);
router.use(gamGate);
router.get('/me', getMe);
router.get('/achievements', getAchievements);
router.get('/leaderboard', getLeaderboard);
router.get('/xp-history', getXPHistory);
router.get('/challenges', getChallenges);
router.post('/challenges/:id/claim', requirePermission('gamification.challenges'), claimChallenge);
router.post('/goal-tier', requirePermission('gamification.challenges'), setGoalTier);
router.get('/frames', getFrames);
router.post('/frame', requirePermission('shop.purchase'), setFrame);
/* Учебник — начисление XP от пользователя */
router.post('/self-award', tbLimiter, validate(selfAwardSchema), selfAward);
/* Lab experiment tracking */
router.post('/lab-activity', requirePermission('simulations.access'), labLimiter, validate(labSchema), (req, res) => {
const discovered = Number(req.body.reactionsDiscovered) || 0;
onLabExperiment(req.user.id, discovered);
res.json({ ok: true });
});
/* Admin routes — award/stats/user require gamification.manage permission
(admin always passes; teachers need explicit grant from permissions UI) */
router.post('/admin/award', requirePermission('gamification.manage'), adminAward);
router.post('/admin/reset', requireRole('admin'), adminReset);
router.get('/admin/stats', requirePermission('gamification.manage'), adminGamStats);
router.get('/admin/user/:id', requirePermission('gamification.manage'), adminGetUser);
module.exports = router;