42 lines
1.8 KiB
Python
42 lines
1.8 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from app.database import get_db
|
|
from app.models.user import User
|
|
from app.models.lesson import Lesson, UserLesson
|
|
from app.utils.auth import get_current_user
|
|
from app.services.gamification import check_achievements
|
|
|
|
router = APIRouter(prefix="/api/lessons", tags=["lessons"])
|
|
|
|
@router.get("")
|
|
async def list_lessons(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
lessons = (await db.execute(select(Lesson).order_by(Lesson.order_num))).scalars().all()
|
|
completed = (await db.execute(
|
|
select(UserLesson.lesson_id).where(UserLesson.user_id == user.id)
|
|
)).scalars().all()
|
|
completed_ids = set(completed)
|
|
return [
|
|
{"id": str(l.id), "title": l.title, "category": l.category, "difficulty": l.difficulty,
|
|
"duration_min": l.duration_min, "content": l.content, "is_premium": l.is_premium,
|
|
"completed": l.id in completed_ids}
|
|
for l in lessons
|
|
]
|
|
|
|
@router.post("/{lesson_id}/complete")
|
|
async def complete_lesson(lesson_id: str, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
|
lesson = (await db.execute(select(Lesson).where(Lesson.id == lesson_id))).scalar_one_or_none()
|
|
if not lesson:
|
|
raise HTTPException(404, "Lesson not found")
|
|
existing = (await db.execute(
|
|
select(UserLesson).where(UserLesson.user_id == user.id, UserLesson.lesson_id == lesson_id)
|
|
)).scalar_one_or_none()
|
|
if existing:
|
|
return {"status": "already_completed"}
|
|
ul = UserLesson(user_id=user.id, lesson_id=lesson_id)
|
|
db.add(ul)
|
|
user.total_points = (user.total_points or 0) + 10
|
|
await db.commit()
|
|
await check_achievements(user.id, db)
|
|
return {"status": "completed", "points_earned": 10}
|