File size: 6,815 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
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,
  };
}