File size: 18,374 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { validateSudoku, type SudokuGrid } from "@/lib/puzzles/sudoku";
import { scoreSequence, validateSequence } from "@/lib/puzzles/sequences";
import { validatePattern, scorePattern, type PatternCell } from "@/lib/puzzles/patterns";
import { validateWordScramble, scoreWordScramble } from "@/lib/puzzles/wordscramble";
import {
validateConstraintGrid,
scoreConstraintGrid,
type Cage,
} from "@/lib/puzzles/constraint";
import {
validateMathEquation,
type MathEquationPuzzle,
} from "@/lib/puzzles/mathequation";
import { calculateXpGain, rollCriticalHit } from "@/lib/xp";
import { checkLevelUp } from "@/lib/progression";
import { EXERCISE_XP } from "@/config/xp";
import { processSkillUnlocks } from "@/lib/skill-unlock";
import { getMultiplierPercent } from "@/lib/multiplier";
import { getTitleForLevel } from "@/config/titles";
import { withApiError } from "@/lib/api-error";
import { getPersonalBest } from "@/lib/puzzles/personal-best";
import { processEndOfDay } from "@/lib/streak";
interface SudokuSubmitBody {
puzzleType?: "sudoku";
playerGrid: SudokuGrid;
solution: SudokuGrid;
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
interface SequenceSubmitBody {
puzzleType: "sequence";
playerAnswers: number[];
solution: number[];
hiddenIndices: number[];
sequenceType: string;
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
interface PatternSubmitBody {
puzzleType: "pattern";
selectedChoice: PatternCell;
answer: PatternCell;
activeAttributes: string[];
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
interface WordScrambleSubmitBody {
puzzleType: "wordscramble";
guess: string;
answer: string;
wordCategory: string;
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
interface ConstraintSubmitBody {
puzzleType: "constraint";
playerGrid: number[][];
cages: Cage[];
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
interface MathEquationSubmitBody {
puzzleType: "mathequation";
/** The puzzle object echoed back from the generate endpoint */
puzzle: Pick<MathEquationPuzzle, "equation" | "answer" | "operationCount" | "difficulty" | "hint">;
/** The integer answer entered by the player */
playerAnswer: number;
durationSecs: number;
difficulty: "easy" | "medium" | "hard";
}
type SubmitBody = SudokuSubmitBody | SequenceSubmitBody | PatternSubmitBody | WordScrambleSubmitBody | ConstraintSubmitBody | MathEquationSubmitBody;
// ---------------------------------------------------------------------------
// Par times (seconds) per puzzle type and difficulty.
// Solving at or under par earns the full speed bonus; above par tapers to 0.
// ---------------------------------------------------------------------------
export const PAR_TIMES: Record<string, Record<string, number>> = {
sudoku: { easy: 120, medium: 240, hard: 480 },
sequence: { easy: 20, medium: 35, hard: 60 },
pattern: { easy: 25, medium: 45, hard: 75 },
wordscramble: { easy: 20, medium: 35, hard: 55 },
constraint: { easy: 60, medium: 120, hard: 200 },
mathequation: { easy: 15, medium: 30, hard: 55 },
};
/** Maximum speed bonus added to the quality score (capped). */
const MAX_SPEED_BONUS = 0.25;
/**
* Calculate a speed bonus (0–MAX_SPEED_BONUS) based on how fast the puzzle
* was solved relative to the par time.
*
* - At or under par → full MAX_SPEED_BONUS
* - At 2× par → 0 bonus (linear interpolation)
* - Over 2× par → 0 bonus (clamped)
* - durationSecs ≤ 0 → treated as instant (full bonus)
*
* The bonus is deliberately modest (max +0.25) so it adds flavour without
* dominating the difficulty-based quality score.
*/
export function calcSpeedBonus(durationSecs: number, parSecs: number): number {
if (parSecs <= 0) return 0;
const clampedDuration = Math.max(0, durationSecs);
if (clampedDuration <= parSecs) return MAX_SPEED_BONUS;
// Linear decay from parSecs (full bonus) to 2×parSecs (zero bonus)
const decay = (clampedDuration - parSecs) / parSecs;
return Math.max(0, MAX_SPEED_BONUS * (1 - decay));
}
/** Map difficulty to a quality score influencing the XP bonus (0–1). */
function difficultyQualityScore(difficulty: string): number {
switch (difficulty) {
case "easy":
return 0.3;
case "medium":
return 0.65;
case "hard":
return 1.0;
default:
return 0.5;
}
}
/**
* Combined quality score: difficulty weight + speed bonus, clamped to [0, 1].
*/
function combinedQualityScore(
puzzleType: string,
difficulty: string,
durationSecs: number,
): number {
const base = difficultyQualityScore(difficulty);
const parSecs = PAR_TIMES[puzzleType]?.[difficulty] ?? 0;
const speedBonus = calcSpeedBonus(durationSecs, parSecs);
return Math.min(1.0, base + speedBonus);
}
/** Validate the shape of the submitted grids. */
function isValidGrid(grid: unknown): grid is SudokuGrid {
if (!Array.isArray(grid) || grid.length !== 9) return false;
return grid.every(
(row) =>
Array.isArray(row) &&
row.length === 9 &&
row.every((cell) => typeof cell === "number" && cell >= 0 && cell <= 9),
);
}
/**
* POST /api/logic/submit
*
* Validates a completed puzzle (Sudoku or sequence), awards XP, and persists the activity.
* Supports:
* - puzzleType="sudoku" (default): classic Sudoku validation
* - puzzleType="sequence": number sequence validation with partial credit
*/
export const POST = withApiError(async (request: NextRequest) => {
let body: SubmitBody;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const puzzleType = body.puzzleType ?? "sudoku";
const { durationSecs, difficulty } = body;
// --- Common validation ---
if (typeof durationSecs !== "number" || durationSecs < 0) {
return NextResponse.json(
{ error: "durationSecs must be a non-negative number" },
{ status: 400 },
);
}
if (!["easy", "medium", "hard"].includes(difficulty)) {
return NextResponse.json(
{ error: "difficulty must be easy, medium, or hard" },
{ status: 400 },
);
}
// --- Puzzle-type-specific validation & scoring ---
let isCorrect: boolean;
let qualityScore: number;
let exerciseType: string;
let description: string;
let metadata: Record<string, unknown>;
if (puzzleType === "sequence") {
const seqBody = body as SequenceSubmitBody;
const { playerAnswers, solution, hiddenIndices, sequenceType } = seqBody;
if (!Array.isArray(playerAnswers) || !playerAnswers.every((v) => typeof v === "number")) {
return NextResponse.json(
{ error: "playerAnswers must be an array of numbers" },
{ status: 400 },
);
}
if (!Array.isArray(solution) || !solution.every((v) => typeof v === "number")) {
return NextResponse.json(
{ error: "solution must be an array of numbers" },
{ status: 400 },
);
}
if (!Array.isArray(hiddenIndices) || !hiddenIndices.every((v) => typeof v === "number")) {
return NextResponse.json(
{ error: "hiddenIndices must be an array of numbers" },
{ status: 400 },
);
}
isCorrect = validateSequence(playerAnswers, solution, hiddenIndices);
// Use partial credit scoring for quality (even if not fully correct)
const partialScore = scoreSequence(playerAnswers, solution, hiddenIndices);
// Combine difficulty weighting + speed bonus with actual accuracy
qualityScore = partialScore * combinedQualityScore("sequence", difficulty, durationSecs);
exerciseType = "sequence";
description = `Completed ${difficulty} ${sequenceType || "number"} sequence in ${Math.round(durationSecs)}s`;
metadata = { difficulty, sequenceType, partialScore, isCorrect };
} else if (puzzleType === "pattern") {
const patternBody = body as PatternSubmitBody;
const { selectedChoice, answer, activeAttributes } = patternBody;
if (!selectedChoice || typeof selectedChoice !== "object") {
return NextResponse.json(
{ error: "selectedChoice must be a PatternCell object" },
{ status: 400 },
);
}
if (!answer || typeof answer !== "object") {
return NextResponse.json(
{ error: "answer must be a PatternCell object" },
{ status: 400 },
);
}
isCorrect = validatePattern(selectedChoice, answer);
qualityScore = scorePattern(selectedChoice, answer) * combinedQualityScore("pattern", difficulty, durationSecs);
exerciseType = "pattern";
description = `Completed ${difficulty} pattern matrix (${(activeAttributes || []).join(", ")}) in ${Math.round(durationSecs)}s`;
metadata = { difficulty, activeAttributes, isCorrect };
} else if (puzzleType === "wordscramble") {
const wsBody = body as WordScrambleSubmitBody;
const { guess, answer: wsAnswer, wordCategory } = wsBody;
if (typeof guess !== "string" || guess.trim().length === 0) {
return NextResponse.json(
{ error: "guess must be a non-empty string" },
{ status: 400 },
);
}
if (typeof wsAnswer !== "string" || wsAnswer.trim().length === 0) {
return NextResponse.json(
{ error: "answer must be a non-empty string" },
{ status: 400 },
);
}
isCorrect = validateWordScramble(guess, wsAnswer);
qualityScore = scoreWordScramble(guess, wsAnswer) * combinedQualityScore("wordscramble", difficulty, durationSecs);
exerciseType = "wordscramble";
description = `Completed ${difficulty} word scramble (${wordCategory || "mixed"}) in ${Math.round(durationSecs)}s`;
metadata = { difficulty, wordCategory, isCorrect };
} else if (puzzleType === "constraint") {
const constraintBody = body as ConstraintSubmitBody;
const { playerGrid, cages } = constraintBody;
if (
!Array.isArray(playerGrid) ||
playerGrid.length !== 4 ||
!playerGrid.every(
(row) =>
Array.isArray(row) &&
row.length === 4 &&
row.every((v) => typeof v === "number" && v >= 0 && v <= 4),
)
) {
return NextResponse.json(
{ error: "playerGrid must be a 4×4 array of integers 0–4" },
{ status: 400 },
);
}
if (!Array.isArray(cages)) {
return NextResponse.json(
{ error: "cages must be an array" },
{ status: 400 },
);
}
isCorrect = validateConstraintGrid(playerGrid, cages);
const partialScore = scoreConstraintGrid(playerGrid, cages);
qualityScore = partialScore * combinedQualityScore("constraint", difficulty, durationSecs);
exerciseType = "constraint";
description = `Completed ${difficulty} constraint grid in ${Math.round(durationSecs)}s`;
metadata = { difficulty, partialScore, isCorrect };
} else if (puzzleType === "mathequation") {
const mathBody = body as MathEquationSubmitBody;
const { puzzle: mathPuzzle, playerAnswer } = mathBody;
if (!mathPuzzle || typeof mathPuzzle !== "object" || typeof mathPuzzle.answer !== "number") {
return NextResponse.json(
{ error: "puzzle must be a MathEquationPuzzle object with a numeric answer" },
{ status: 400 },
);
}
if (typeof playerAnswer !== "number") {
return NextResponse.json(
{ error: "playerAnswer must be a number" },
{ status: 400 },
);
}
isCorrect = validateMathEquation(mathPuzzle as MathEquationPuzzle, playerAnswer);
qualityScore = isCorrect ? combinedQualityScore("mathequation", difficulty, durationSecs) : 0;
exerciseType = "mathequation";
description = `Solved ${difficulty} math equation "${mathPuzzle.equation}" in ${Math.round(durationSecs)}s`;
metadata = { difficulty, equation: mathPuzzle.equation, playerAnswer, isCorrect };
} else {
// Sudoku
const sudokuBody = body as SudokuSubmitBody;
const { playerGrid, solution } = sudokuBody;
if (!isValidGrid(playerGrid)) {
return NextResponse.json(
{ error: "playerGrid must be a 9×9 array of integers 0–9" },
{ status: 400 },
);
}
if (!isValidGrid(solution)) {
return NextResponse.json(
{ error: "solution must be a 9×9 array of integers 0–9" },
{ status: 400 },
);
}
isCorrect = validateSudoku(playerGrid, solution);
qualityScore = combinedQualityScore("sudoku", difficulty, durationSecs);
exerciseType = "sudoku";
description = `Completed ${difficulty} Sudoku in ${Math.round(durationSecs)}s`;
metadata = { difficulty };
}
if (!isCorrect) {
return NextResponse.json(
{ correct: false, message: "Puzzle not solved correctly." },
{ status: 200 },
);
}
// --- Fetch user (always user id=1 for now) ---
const user = await prisma.user.findFirst({
where: { id: 1 },
include: { categorySkills: { where: { category: "logic" } } },
});
if (!user) {
return NextResponse.json({ error: "No user found" }, { status: 404 });
}
const logicSkill = user.categorySkills[0];
if (!logicSkill) {
return NextResponse.json(
{ error: "Logic CategorySkill not found" },
{ status: 500 },
);
}
// --- Personal best check (must run before inserting the new activity) ---
const pbResult = await getPersonalBest(1, exerciseType, difficulty, durationSecs);
// --- Speed bonus (for response transparency) ---
const parSecs = PAR_TIMES[puzzleType]?.[difficulty] ?? 0;
const speedBonus = isCorrect ? calcSpeedBonus(durationSecs, parSecs) : 0;
// --- XP calculation (with skill tree multiplier) ---
const { baseXp, maxQualityBonus } = EXERCISE_XP["logic"];
const isCriticalHit = rollCriticalHit();
const multiplierPercent = await getMultiplierPercent(prisma, 1, "logic");
const xpResult = calculateXpGain({
baseXp,
qualityScore,
maxQualityBonus,
isCriticalHit,
multiplierPercent,
});
// --- Level-up checks (user + category) ---
const userLevelResult = checkLevelUp({
currentXp: user.currentXp + xpResult.totalXp,
xpToNextLevel: user.xpToNextLevel,
level: user.level,
});
const categoryLevelResult = checkLevelUp({
currentXp: logicSkill.currentXp + xpResult.totalXp,
xpToNextLevel: logicSkill.xpToNext,
level: logicSkill.level,
});
// --- Title progression ---
const newTitle = getTitleForLevel(userLevelResult.newLevel);
const titleChanged = newTitle !== user.title;
// --- Streak processing (idempotent — no-op if already run today) ---
await processEndOfDay(user.id);
// --- 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: 1,
date: { gte: todayStart, lt: tomorrowStart },
},
});
const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp;
const newActivityCount = (existingLog?.activityCount ?? 0) + 1;
const goalMet = newXpEarned >= user.dailyGoalXp;
// --- Persist all changes in a transaction ---
let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 };
await prisma.$transaction(async (tx) => {
// Record the activity
await tx.activity.create({
data: {
userId: 1,
category: "logic",
exerciseType,
description,
baseXp: xpResult.baseXp,
qualityBonus: xpResult.qualityBonus,
isCriticalHit: xpResult.isCriticalHit,
totalXp: xpResult.totalXp,
score: qualityScore,
durationSecs: Math.round(durationSecs),
metadata: JSON.stringify(metadata),
},
});
// Update user XP and level
await tx.user.update({
where: { id: 1 },
data: {
totalXp: user.totalXp + xpResult.totalXp,
currentXp: userLevelResult.remainingXp,
xpToNextLevel: userLevelResult.newXpToNextLevel,
level: userLevelResult.newLevel,
...(titleChanged && { title: newTitle }),
},
});
// Update category skill XP and level
await tx.categorySkill.update({
where: { id: logicSkill.id },
data: {
totalXp: logicSkill.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, 1, "logic", categoryLevelResult.newLevel,
);
}
// Upsert daily log
if (existingLog) {
await tx.dailyLog.update({
where: { id: existingLog.id },
data: {
xpEarned: newXpEarned,
activityCount: newActivityCount,
goalMet,
},
});
} else {
await tx.dailyLog.create({
data: {
userId: 1,
date: todayStart,
xpEarned: newXpEarned,
activityCount: newActivityCount,
goalMet,
},
});
}
});
return NextResponse.json({
correct: true,
xp: { ...xpResult, multiplierPercent },
isCriticalHit: xpResult.isCriticalHit,
speedBonus: Math.round(speedBonus * 100) / 100,
parSecs: parSecs || null,
isPersonalBest: pbResult.isPersonalBest,
prevBestSecs: pbResult.prevBestSecs,
levelUp: userLevelResult.levelsGained > 0,
newUserLevel: userLevelResult.newLevel,
categoryLevelUp: categoryLevelResult.levelsGained > 0,
newCategoryLevel: categoryLevelResult.newLevel,
dailyGoalMet: goalMet,
categoryXp: {
currentXp: categoryLevelResult.remainingXp,
xpToNext: categoryLevelResult.newXpToNextLevel,
level: categoryLevelResult.newLevel,
levelUp: categoryLevelResult.levelsGained > 0,
},
newTitle: titleChanged ? newTitle : undefined,
unlocks: unlockResult.unlocked,
streakFreezesGranted: unlockResult.streakFreezesGranted,
message: isCriticalHit
? "Critical Hit! Puzzle solved!"
: "Puzzle solved correctly!",
});
});
|