Download src/app/api/quests/submit/route.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 8.55 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/quests/submit/route.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/quests/submit/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/quests/submit/route.ts
8.55 kB
| import { NextRequest, NextResponse } from "next/server"; | |
| import { claude, parseClaudeJson } from "@/lib/claude"; | |
| import { prisma } from "@/lib/db"; | |
| // import { Prisma } from "@prisma/client"; | |
| import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; | |
| import { checkLevelUp } from "@/lib/progression"; | |
| import { EXERCISE_XP } from "@/config/xp"; | |
| import type { QuestExercise } from "../generate/route"; | |
| import { processSkillUnlocks } from "@/lib/skill-unlock"; | |
| import { getMultiplierPercent } from "@/lib/multiplier"; | |
| import { getTitleForLevel } from "@/config/titles"; | |
| import { withApiError } from "@/lib/api-error"; | |
| import { processEndOfDay } from "@/lib/streak"; | |
| interface SubmitBody { | |
| domain: string; | |
| title: string; | |
| exercises: QuestExercise[]; | |
| answers: Record<number, string>; // exerciseId → user answer | |
| durationSecs?: number; | |
| userId?: number; | |
| } | |
| interface GradedExercise { | |
| id: number; | |
| correct: boolean; | |
| feedback: string; | |
| } | |
| async function gradeShortAnswer( | |
| question: string, | |
| modelAnswer: string, | |
| userAnswer: string, | |
| ): Promise<{ correct: boolean; feedback: string }> { | |
| try { | |
| const message = await claude.messages.create({ | |
| model: "claude-haiku-4-5-20251001", | |
| max_tokens: 256, | |
| messages: [ | |
| { | |
| role: "user", | |
| content: `Grade this short-answer response. | |
| Question: ${question} | |
| Model Answer: ${modelAnswer} | |
| Student Answer: ${userAnswer} | |
| Is the student's answer substantially correct? Respond ONLY with valid JSON (no markdown): | |
| { "correct": true/false, "feedback": "One sentence of specific feedback." }`, | |
| }, | |
| ], | |
| }); | |
| const text = | |
| message.content[0].type === "text" ? message.content[0].text : ""; | |
| const result = parseClaudeJson(text) as { correct: boolean; feedback: string }; | |
| return result; | |
| } catch { | |
| // Fallback: mark as incorrect if grading fails | |
| return { | |
| correct: false, | |
| feedback: "Could not grade your answer automatically.", | |
| }; | |
| } | |
| } | |
| export const POST = withApiError(async (request: NextRequest) => { | |
| if (!process.env.ANTHROPIC_API_KEY) { | |
| return NextResponse.json( | |
| { error: "ANTHROPIC_API_KEY is not configured" }, | |
| { status: 503 }, | |
| ); | |
| } | |
| let body: SubmitBody; | |
| try { | |
| body = await request.json(); | |
| } catch { | |
| return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); | |
| } | |
| const { domain, title, exercises, answers, durationSecs } = body; | |
| if (!domain || !title || !Array.isArray(exercises) || !answers) { | |
| return NextResponse.json( | |
| { error: "domain, title, exercises, and answers are required" }, | |
| { status: 400 }, | |
| ); | |
| } | |
| // Grade each exercise | |
| const graded: GradedExercise[] = []; | |
| for (const exercise of exercises) { | |
| const userAnswer = answers[exercise.id] ?? ""; | |
| if (exercise.type === "multiple-choice") { | |
| const correct = | |
| userAnswer.trim().toLowerCase() === | |
| exercise.correctAnswer.trim().toLowerCase(); | |
| graded.push({ | |
| id: exercise.id, | |
| correct, | |
| feedback: correct | |
| ? "Correct!" | |
| : `Correct answer: ${exercise.correctAnswer}`, | |
| }); | |
| } else { | |
| // short-answer — use Claude | |
| const result = await gradeShortAnswer( | |
| exercise.question, | |
| exercise.correctAnswer, | |
| userAnswer, | |
| ); | |
| graded.push({ id: exercise.id, ...result }); | |
| } | |
| } | |
| const correctCount = graded.filter((g) => g.correct).length; | |
| const qualityScore = correctCount / exercises.length; | |
| // Fetch user | |
| const userId = body.userId ?? 1; | |
| const user = await prisma.user.findFirst({ | |
| where: { id: userId }, | |
| include: { categorySkills: { where: { category: "quests" } } }, | |
| }); | |
| if (!user) { | |
| return NextResponse.json({ error: "No user found" }, { status: 404 }); | |
| } | |
| const questSkill = user.categorySkills[0]; | |
| if (!questSkill) { | |
| return NextResponse.json( | |
| { error: "Quests CategorySkill not found" }, | |
| { status: 500 }, | |
| ); | |
| } | |
| // XP calculation (with skill tree multiplier) | |
| const { baseXp, maxQualityBonus } = EXERCISE_XP["quests"]; | |
| const isCriticalHit = rollCriticalHit(); | |
| const multiplierPercent = await getMultiplierPercent(prisma, userId, "quests"); | |
| const xpResult = calculateXpGain({ | |
| baseXp, | |
| qualityScore, | |
| maxQualityBonus, | |
| isCriticalHit, | |
| multiplierPercent, | |
| }); | |
| // Level-up checks | |
| const userLevelResult = checkLevelUp({ | |
| currentXp: user.currentXp + xpResult.totalXp, | |
| xpToNextLevel: user.xpToNextLevel, | |
| level: user.level, | |
| }); | |
| const categoryLevelResult = checkLevelUp({ | |
| currentXp: questSkill.currentXp + xpResult.totalXp, | |
| xpToNextLevel: questSkill.xpToNext, | |
| level: questSkill.level, | |
| }); | |
| // --- Title progression --- | |
| const newTitle = getTitleForLevel(userLevelResult.newLevel); | |
| const titleChanged = newTitle !== user.title; | |
| // --- Streak processing (idempotent — no-op if already run today) --- | |
| await processEndOfDay(userId); | |
| // Daily log bookkeeping | |
| const now = new Date(); | |
| const todayStart = new Date( | |
| Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), | |
| ); | |
| const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); | |
| const existingLog = await prisma.dailyLog.findFirst({ | |
| where: { | |
| userId, | |
| date: { gte: todayStart, lt: tomorrowStart }, | |
| }, | |
| }); | |
| const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; | |
| const newActivityCount = (existingLog?.activityCount ?? 0) + 1; | |
| const goalMet = newXpEarned >= user.dailyGoalXp; | |
| // Sanitise optional duration | |
| const safeDuration = | |
| typeof durationSecs === "number" && durationSecs >= 0 | |
| ? Math.round(durationSecs) | |
| : null; | |
| // Persist in a transaction | |
| let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; | |
| await prisma.$transaction(async (tx) => { | |
| await tx.activity.create({ | |
| data: { | |
| userId, | |
| category: "quests", | |
| exerciseType: "micro-lesson", | |
| description: `Skill Quest: ${title} (${domain})`, | |
| baseXp: xpResult.baseXp, | |
| qualityBonus: xpResult.qualityBonus, | |
| isCriticalHit: xpResult.isCriticalHit, | |
| totalXp: xpResult.totalXp, | |
| score: qualityScore, | |
| durationSecs: safeDuration, | |
| metadata: JSON.stringify({ | |
| domain, | |
| title, | |
| correctCount, | |
| totalExercises: exercises.length, | |
| }), | |
| }, | |
| }); | |
| await tx.user.update({ | |
| where: { id: userId }, | |
| data: { | |
| totalXp: user.totalXp + xpResult.totalXp, | |
| currentXp: userLevelResult.remainingXp, | |
| xpToNextLevel: userLevelResult.newXpToNextLevel, | |
| level: userLevelResult.newLevel, | |
| ...(titleChanged && { title: newTitle }), | |
| }, | |
| }); | |
| await tx.categorySkill.update({ | |
| where: { id: questSkill.id }, | |
| data: { | |
| totalXp: questSkill.totalXp + xpResult.totalXp, | |
| currentXp: categoryLevelResult.remainingXp, | |
| xpToNext: categoryLevelResult.newXpToNextLevel, | |
| level: categoryLevelResult.newLevel, | |
| }, | |
| }); | |
| // Auto-unlock skill tree nodes if category leveled up | |
| if (categoryLevelResult.levelsGained > 0) { | |
| unlockResult = await processSkillUnlocks( | |
| tx, userId, "quests", categoryLevelResult.newLevel, | |
| ); | |
| } | |
| if (existingLog) { | |
| await tx.dailyLog.update({ | |
| where: { id: existingLog.id }, | |
| data: { | |
| xpEarned: newXpEarned, | |
| activityCount: newActivityCount, | |
| goalMet, | |
| }, | |
| }); | |
| } else { | |
| await tx.dailyLog.create({ | |
| data: { | |
| userId, | |
| date: todayStart, | |
| xpEarned: newXpEarned, | |
| activityCount: newActivityCount, | |
| goalMet, | |
| }, | |
| }); | |
| } | |
| }); | |
| return NextResponse.json({ | |
| graded, | |
| correctCount, | |
| totalExercises: exercises.length, | |
| qualityScore, | |
| xp: { | |
| baseXp: xpResult.baseXp, | |
| qualityBonus: xpResult.qualityBonus, | |
| multiplierBonus: xpResult.multiplierBonus, | |
| multiplierPercent, | |
| totalXp: xpResult.totalXp, | |
| isCriticalHit: xpResult.isCriticalHit, | |
| }, | |
| levelUp: userLevelResult.levelsGained > 0, | |
| categoryXp: { | |
| currentXp: categoryLevelResult.remainingXp, | |
| xpToNext: categoryLevelResult.newXpToNextLevel, | |
| level: categoryLevelResult.newLevel, | |
| levelUp: categoryLevelResult.levelsGained > 0, | |
| }, | |
| newTitle: titleChanged ? newTitle : undefined, | |
| unlocks: unlockResult.unlocked, | |
| streakFreezesGranted: unlockResult.streakFreezesGranted, | |
| }); | |
| }); | |