Files
Learn_System/backend
Maxim Dolgolyov 268ea31bb8 feat(gamification): Phase 4 — standalone coin events + coin_log
Coins were always 1:10 of XP. Now they have their own event log + a
helper that dedups by reason within a configurable window.

Backend:
  • migration 032 creates coin_log (user_id, amount, reason, created_at)
    with indices for the 'fired today?' check
  • awardCoins now records into coin_log on every call (reason defaults
    to 'xp_bonus' for the legacy XP-proportional path)
  • awardCoinsOnce(userId, amount, reason, window) — fires the bonus
    only if no row matches in the window:
      'day'     → DATE(created_at) = today
      'week'    → ISO week match
      'forever' → never twice

Wired events (Phase 4 subset of the plan):
  • Daily login — 10 coins, once/day. Hooked in updateStreak so the
    bonus rides on the existing 'daily_activity' XP trigger.
  • Daily goal completion — 15/25/40 coins (easy/medium/hard), once/day.
    Sits next to the existing tier XP bonus in updateDailyGoal.
  • Variant clear — 30 coins, once per (user, variant) forever. Fires
    from the exam-prep attempts endpoint when the user's final correct
    answer fills out a math9 variant.

Deferred (need invasive trigger hooks): weekly goal, paragraph close,
boss defeated, referral.

Verified end-to-end: awardCoinsOnce returns true→false on repeated
calls, coin_log records the first, coins balance moves once.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 20:30:14 +03:00
..

LearnSpace Backend — Фаза 1

Быстрый старт

cd backend
npm install

# 1. Скопировать и заполнить переменные окружения
cp .env.example .env

# 2. Создать базу данных в PostgreSQL
createdb learnspace

# 3. Применить миграции (создать таблицы)
npm run migrate

# 4. Загрузить тестовые вопросы
npm run seed

# 5. Запустить сервер
npm run dev

API

Auth

Метод URL Тело Описание
POST /api/auth/register { email, password, name } Регистрация
POST /api/auth/login { email, password } Вход
GET /api/auth/me Текущий пользователь

Предметы

Метод URL Описание
GET /api/subjects Список предметов
GET /api/subjects/:slug/topics Темы предмета

Сессии тестирования

Метод URL Тело Описание
POST /api/sessions { subject_slug, mode, count, topic_id? } Начать тест
POST /api/sessions/:id/answer { question_id, option_id, time_spent_sec? } Отправить ответ
POST /api/sessions/:id/finish Завершить тест + разбор
GET /api/sessions/:id/result Результат завершённого теста
GET /api/sessions/history История тестов

Все /api/sessions/* требуют заголовок:

Authorization: Bearer <token>

Добавление вопросов

Создать JSON-файл в data/ по образцу questions-bio.json:

{
  "subject": "chem",
  "topics": [{ "name": "Органическая химия", "order": 1 }],
  "questions": [
    {
      "topic": "Органическая химия",
      "difficulty": 2,
      "text": "Текст вопроса",
      "options": ["А", "Б", "В", "Г"],
      "answer": 0,
      "explanation": "Объяснение правильного ответа"
    }
  ]
}

Затем повторно запустить npm run seed.

Структура проекта

backend/
├── data/                     ← JSON с вопросами
├── src/
│   ├── server.js             ← точка входа
│   ├── middleware/auth.js    ← JWT верификация
│   ├── db/
│   │   ├── pool.js           ← соединение с PostgreSQL
│   │   ├── migrate.js        ← запуск миграций
│   │   ├── seed.js           ← загрузка вопросов
│   │   └── migrations/       ← SQL-файлы схемы
│   ├── routes/               ← маршруты
│   └── controllers/          ← бизнес-логика
└── .env.example