RotNot / src /lib /coding /award.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
6.82 kB
import { prisma } from "@/lib/db";
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 { processEndOfDay } from "@/lib/streak";
import { difficultyWeight } from "./grade";
import type { CodingDifficulty } from "./types";
// ---------------------------------------------------------------------------
// Coding XP award β€” encapsulates the fetch user β†’ resolve multiplier β†’
// calculate XP β†’ persist transaction used by both coding submit routes.
//
// Code and written submissions each call this independently with their own
// exerciseType, so a user earns XP separately for correct code and correct
// written answers (two Activity rows, two awards).
//
// Follows the canonical category order required by CLAUDE.md:
// fetch user β†’ getMultiplierPercent() β†’ calculateXpGain() β†’ persist.
// XP scales with difficulty via difficultyWeight().
// ---------------------------------------------------------------------------
export interface AwardInput {
userId: number;
/** "code" or "written" β€” distinguishes the two XP paths. */
exerciseType: string;
description: string;
/** 0–1 quality of the solution (test pass ratio / judge coverage). */
qualityScore: number;
difficulty: CodingDifficulty;
metadata: Record<string, unknown>;
durationSecs?: number;
}
export interface AwardResult {
xp: {
baseXp: number;
qualityBonus: number;
isCriticalHit: boolean;
multiplierBonus: number;
totalXp: number;
multiplierPercent: number;
};
isCriticalHit: boolean;
levelUp: boolean;
newUserLevel: number;
categoryLevelUp: boolean;
newCategoryLevel: number;
categoryXp: {
currentXp: number;
xpToNext: number;
level: number;
levelUp: boolean;
};
unlocks: string[];
streakFreezesGranted: number;
newTitle?: string;
}
const CATEGORY = "coding";
export async function awardCodingXp(input: AwardInput): Promise<AwardResult> {
const { userId } = input;
const user = await prisma.user.findFirst({
where: { id: userId },
include: { categorySkills: { where: { category: CATEGORY } } },
});
if (!user) throw new Error("No user found");
const codingSkill = user.categorySkills[0];
if (!codingSkill) throw new Error("Coding CategorySkill not found");
// --- XP calculation (difficulty-weighted, with skill tree multiplier) ---
const weight = difficultyWeight(input.difficulty);
const { baseXp: rawBase, maxQualityBonus: rawMaxBonus } = EXERCISE_XP[CATEGORY];
const baseXp = Math.round(rawBase * weight);
const maxQualityBonus = Math.round(rawMaxBonus * weight);
const isCriticalHit = rollCriticalHit();
const multiplierPercent = await getMultiplierPercent(prisma, userId, CATEGORY);
const xpResult = calculateXpGain({
baseXp,
qualityScore: input.qualityScore,
maxQualityBonus,
isCriticalHit,
multiplierPercent,
});
const userLevelResult = checkLevelUp({
currentXp: user.currentXp + xpResult.totalXp,
xpToNextLevel: user.xpToNextLevel,
level: user.level,
});
const categoryLevelResult = checkLevelUp({
currentXp: codingSkill.currentXp + xpResult.totalXp,
xpToNextLevel: codingSkill.xpToNext,
level: codingSkill.level,
});
const newTitle = getTitleForLevel(userLevelResult.newLevel);
const titleChanged = newTitle !== user.title;
// Streak bookkeeping (idempotent β€” safe to run on every award).
await processEndOfDay(user.id);
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;
let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 };
await prisma.$transaction(async (tx) => {
await tx.activity.create({
data: {
userId,
category: CATEGORY,
exerciseType: input.exerciseType,
description: input.description,
baseXp: xpResult.baseXp,
qualityBonus: xpResult.qualityBonus,
isCriticalHit: xpResult.isCriticalHit,
totalXp: xpResult.totalXp,
score: input.qualityScore,
durationSecs:
input.durationSecs != null ? Math.round(input.durationSecs) : null,
metadata: JSON.stringify(input.metadata),
},
});
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: codingSkill.id },
data: {
totalXp: codingSkill.totalXp + xpResult.totalXp,
currentXp: categoryLevelResult.remainingXp,
xpToNext: categoryLevelResult.newXpToNextLevel,
level: categoryLevelResult.newLevel,
},
});
if (categoryLevelResult.levelsGained > 0) {
unlockResult = await processSkillUnlocks(
tx,
userId,
CATEGORY,
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 {
xp: { ...xpResult, multiplierPercent },
isCriticalHit: xpResult.isCriticalHit,
levelUp: userLevelResult.levelsGained > 0,
newUserLevel: userLevelResult.newLevel,
categoryLevelUp: categoryLevelResult.levelsGained > 0,
newCategoryLevel: categoryLevelResult.newLevel,
categoryXp: {
currentXp: categoryLevelResult.remainingXp,
xpToNext: categoryLevelResult.newXpToNextLevel,
level: categoryLevelResult.newLevel,
levelUp: categoryLevelResult.levelsGained > 0,
},
unlocks: unlockResult.unlocked,
streakFreezesGranted: unlockResult.streakFreezesGranted,
newTitle: titleChanged ? newTitle : undefined,
};
}