RotNot / src /app /api /logic /submit /route.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
18.4 kB
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!",
});
});